Send a new invoice data from Books to local certified solution via API json due local compliance

Send a new invoice data from Books to local certified solution via API json due local compliance

Greetings,  
I hope you are doing well and staying safe.  

Due to local compliance regulations, I am required to issue invoices exclusively using locally certified software, which Zoho Books is not. However, we would like to continue using Zoho Books, so we need to send invoice data to an external certified solution each time a new invoice is issued. This external system should automatically generate a corresponding invoice, essentially mirroring the one created in Zoho Books.  

I have access to the API documentation for the external certified solution and have attempted to create a custom function to extract invoice data, format it in JSON, and send it to the external system. However, due to my limited knowledge, I have been unable to save the custom function successfully, as the Deluge editor consistently flags syntax errors.  

The API documentation for the external solution can be found here: https://api.factplus.co.ao/documentation/  

Below are some of the approaches I have attempted:  

===
void EnviarFctraParaFctpls( Map invoice, Map organization, Map user )
{
    // A função já recebe os detalhes da fatura e organização como 'invoice' e 'organization'
    // Não precisamos usar zoho.books.getRecordsByID para os dados básicos da fatura.
    // Usaremos 'invoice' diretamente.

    // 1. Extrair Detalhes da Fatura (diretamente do 'invoice' Map)
    invoiceData = invoice; // 'invoice' já é o mapa com os dados da fatura
    organizationId = organization.get("organization_id"); // ID da sua organização no Zoho Books

    invoiceNumber = invoiceData.get("invoice_number");
    invoiceDate = invoiceData.get("date"); // Formato 'YYYY-MM-DD'
    dueDate = invoiceData.get("due_date"); // Formato 'YYYY-MM-DD'
    reference = invoiceData.get("reference_number"); // Pode usar o número de referência do Zoho Books
    currency = invoiceData.get("currency_code");
    // observation = invoiceData.get("notes"); // Supondo que 'notes' seja para observações
    
    // ATENÇÃO: Verifique na documentação do Factplus como lidar com 'retention'.
    // Se o Zoho Books não tiver um campo direto para 'retention', você pode precisar de lógica extra
    // ou definir como "0" se não for aplicável no seu caso.
    retention_value = "0"; 
    
    // Dados do Cliente
    customerData = invoiceData.get("customer_details");
    clientName = customerData.get("customer_name");
    clientNIF = customerData.get("vat_reg_no"); // Assumindo que NIF seja o VAT Registration Number
    clientEmail = customerData.get("email");
    clientCity = customerData.get("city");
    clientAddress = customerData.get("billing_address").get("address"); // Endereço de fatura
    clientPostalCode = customerData.get("billing_address").get("zip"); // CEP de fatura
    clientCountry = customerData.get("billing_address").get("country"); // País de fatura

    // Itens da Fatura
    lineItems = invoiceData.get("line_items");
    factplusItems = collection(); // Coleção para armazenar os itens formatados para o Factplus

    for each item in lineItems
    {
        // Para itemcode, é ideal usar um ID que seja único e identificável no Factplus.
        // item.get("item_id") é o ID interno do Zoho Books, o que pode não ser ideal se o Factplus
        // espera um código de item de produto/serviço. Considere usar item.get("name") ou um campo personalizado.
        itemCode = item.get("item_id"); 
        description = item.get("description");
        price = item.get("rate");
        quantity = item.get("quantity");
        taxRate = item.get("tax_percentage"); // Taxa de imposto
        discount = item.get("discount"); // Desconto por linha de item
        
        // ATENÇÃO: exemption_code e retention por item precisam ser verificados na API do Factplus.
        exemptionCode = ""; // Valor padrão, ajuste se tiver campo correspondente
        itemRetention = "0"; // Valor padrão, ajuste se tiver campo correspondente

        factplusItem = Map();
        factplusItem.put("itemcode", itemCode);
        factplusItem.put("description", description);
        factplusItem.put("price", price);
        factplusItem.put("quantity", quantity);
        factplusItem.put("tax", taxRate);
        factplusItem.put("discount", discount);
        factplusItem.put("exemption_code", exemptionCode);
        factplusItem.put("retention", itemRetention);
        
        factplusItems.add(factplusItem);
    }
    
    // 2. Construir o Objeto JSON para a API do Factplus
    // ATENÇÃO: SUBSTITUA 'SUA_CHAVE_API_AQUI' PELA SUA CHAVE DE 32 DÍGITOS DO FACTPLUS
    factplusPayload = Map();
    factplusPayload.put("apicall", "CREATE");
    factplusPayload.put("apikey", "SUA_CHAVE_API_AQUI"); // <-- SUA CHAVE API DO FACTPLUS AQUI!

    documentMap = Map();
    documentMap.put("type", "factura"); // Tipo de documento, confirme se "factura" é o correto
    documentMap.put("date", invoiceDate);
    documentMap.put("duedate", dueDate);
    documentMap.put("vref", invoiceNumber); // Usando o número da fatura como referência. Verifique se o Factplus aceita este formato.
    // A "serie" é crucial. O exemplo do Factplus mostra "2020". Você precisa definir uma série apropriada.
    // Se o Zoho Books não tiver um campo para série, pode ser um valor fixo ou derivado.
    documentMap.put("serie", "2024"); // <-- ATENÇÃO: Defina a série correta para o Factplus (ex: "2024", "FS_A")
    documentMap.put("currency", currency);
    documentMap.put("exchange_rate", "0"); // Ajuste se houver taxa de câmbio
    // documentMap.put("observation", invoiceData.get("notes")); // Se usar campo de notas
    documentMap.put("retention", retention_value);

    clientMap = Map();
    clientMap.put("name", clientName);
    clientMap.put("nif", clientNIF);
    clientMap.put("email", clientEmail);
    clientMap.put("city", clientCity);
    clientMap.put("address", clientAddress);
    clientMap.put("postalcode", clientPostalCode);
    clientMap.put("country", clientCountry);
    
    factplusPayload.put("document", documentMap);
    factplusPayload.put("client", clientMap);
    factplusPayload.put("items", factplusItems);

    // Converter o mapa Deluge para string JSON
    jsonString = factplusPayload.toString();

    // 3. Fazer a Chamada HTTP POST para a API do Factplus
    // ATENÇÃO: Você PRECISA substituir "https://api.factplus.co.ao" pelo ENDPOINT COMPLETO
    // da API do Factplus para a criação de faturas.
    // Ex: "https://api.factplus.co.ao/v1/invoices" ou similar.
    factplusAPI_URL = "https://api.factplus.co.ao"; // <-- SUBSTITUIR PELO ENDPOINT ESPECÍFICO DE CRIAÇÃO DE FATURA

    // Cabeçalhos (Content-Type é essencial para JSON)
    headers = Map();
    headers.put("Content-Type", "application/json");

    // Executar a chamada API
    apiResponse = invokeurl
    [
        url : factplusAPI_URL
        type : POST
        headers: headers
        content : jsonString
    ];

    // 4. Tratar a Resposta da API
    info "Request sent to Factplus: " + jsonString; // Para depuração, mostre o que foi enviado
    info "Factplus API Response: " + apiResponse;

    // Adicione lógica para verificar a resposta aqui.
    // Ex: if (apiResponse.get("status") == "success") { ... }
    // ou if (apiResponse.get("code") == 200) { ... }
    // Logar erros se a resposta indicar falha e talvez enviar um email de alerta.
    if (apiResponse.get("status") == "success") // Supondo que a API retorne um campo 'status'
    {
        info "Fatura enviada com sucesso para o Factplus!";
        // Opcional: Atualizar a fatura no Zoho Books com um campo de status "Enviado para Factplus"
        // Ou armazenar o ID de retorno do Factplus.
    }
    else
    {
        error "Erro ao enviar fatura para o Factplus: " + apiResponse.get("message"); // Supondo campo 'message'
        // Opcional: Enviar email de erro para o cliente ou para o administrador
    }
}
===

And

===
// Função para enviar fatura do Zoho Books para o Factplus
// Parâmetro: invoice_id (ID da fatura criada)
invoice_id = input.invoice_id;

// Obter detalhes da fatura do Zoho Books
invoice = zoho.books.getRecordsByID("Invoices", organization_id, invoice_id);
invoice_data = invoice.get("invoice");

// Mapear dados do cliente
customer_id = invoice_data.get("customer_id");
customer = zoho.books.getRecordsByID("Contacts", organization_id, customer_id);
customer_data = customer.get("contact");
client_map = Map();
client_map.put("name", customer_data.get("contact_name"));
client_map.put("nif", customer_data.get("tax_reg_no", ""));
client_map.put("email", customer_data.get("email", ""));
client_map.put("city", customer_data.get("billing_address").get("city", ""));
client_map.put("address", customer_data.get("billing_address").get("address", ""));
client_map.put("postalcode", customer_data.get("billing_address").get("zip", ""));
client_map.put("country", customer_data.get("billing_address").get("country", "Angola"));

// Mapear itens da fatura
items_list = List();
for each item in invoice_data.get("line_items")
{
    item_map = Map();
    item_map.put("itemcode", item.get("item_id", "ITEM" + item.get("line_item_id")));
    item_map.put("description", item.get("name"));
    item_map.put("price", item.get("rate").toString());
    item_map.put("quantity", item.get("quantity").toString());
    item_map.put("tax", "14"); // Ajuste conforme a tributação aplicável
    item_map.put("discount", item.get("discount", "0").toString());
    item_map.put("exemption_code", "");
    item_map.put("retention", "");
    item_map.put("unit", "Unidade");
    items_list.add(item_map);
}

// Construir o corpo da requisição para o Factplus
payload = Map();
payload.put("apicall", "CREATE");
payload.put("apikey", "SUA_CHAVE_API_FACTPLUS"); // Substitua pela sua chave de API
document_map = Map();
document_map.put("type", "factura");
document_map.put("date", invoice_data.get("date"));
document_map.put("duedate", invoice_data.get("due_date"));
document_map.put("vref", invoice_data.get("invoice_number"));
document_map.put("serie", invoice_data.get("date").left(4)); // Ano da fatura
document_map.put("currency", "AOA");
document_map.put("exchange_rate", "0");
document_map.put("observation", "");
document_map.put("retention", "0");
payload.put("document", document_map);
payload.put("client", client_map);
payload.put("items", items_list);

// Enviar requisição para o Factplus
headers = Map();
headers.put("Content-Type", "application/json");
response = invokeurl
[
    type: POST,
    parameters: payload.toString(),
    headers: headers,
    connection: "FactplusAPI"
];

// Logar a resposta para depuração
info response;
===

Any help?
Thanks in advance.

    Access your files securely from anywhere







                            Zoho Developer Community





                                                  Use cases

                                                  Make the most of Zoho Desk with the use cases.

                                                   
                                                    

                                                  eBooks

                                                  Download free eBooks and access a range of topics to get deeper insight on successfully using Zoho Desk.

                                                   
                                                    

                                                  Videos

                                                  Watch comprehensive videos on features and other important topics that will help you master Zoho Desk.

                                                   
                                                    

                                                  Webinar

                                                  Sign up for our webinars and learn the Zoho Desk basics, from customization to automation and more

                                                   
                                                    
                                                  • Desk Community Learning Series


                                                  • Meetups


                                                  • Ask the Experts


                                                  • Kbase


                                                  • Resources


                                                  • Glossary


                                                  • Desk Marketplace


                                                  • MVP Corner






                                                            Manage your brands on social media



                                                                  Zoho TeamInbox Resources



                                                                      Zoho CRM Plus Resources

                                                                        Zoho Books Resources


                                                                          Zoho Subscriptions Resources

                                                                            Zoho Projects Resources


                                                                              Zoho Sprints Resources


                                                                                Qntrl Resources


                                                                                  Zoho Creator Resources



                                                                                      Zoho CRM Resources

                                                                                      • CRM Community Learning Series

                                                                                        CRM Community Learning Series


                                                                                      • Kaizen

                                                                                        Kaizen

                                                                                      • Functions

                                                                                        Functions

                                                                                      • Meetups

                                                                                        Meetups

                                                                                      • Kbase

                                                                                        Kbase

                                                                                      • Resources

                                                                                        Resources

                                                                                      • Digest

                                                                                        Digest

                                                                                      • CRM Marketplace

                                                                                        CRM Marketplace

                                                                                      • MVP Corner

                                                                                        MVP Corner







                                                                                          Design. Discuss. Deliver.

                                                                                          Create visually engaging stories with Zoho Show.

                                                                                          Get Started Now


                                                                                            Zoho Show Resources


                                                                                              Zoho Writer Writer

                                                                                              Get Started. Write Away!

                                                                                              Writer is a powerful online word processor, designed for collaborative work.

                                                                                                Zoho CRM コンテンツ








                                                                                                  Nederlandse Hulpbronnen


                                                                                                      ご検討中の方




                                                                                                            • Recent Topics

                                                                                                            • Can Zoho Flows repeat Actions more than once?

                                                                                                              I'm attempting to make an intentional Zoho Flow loop using the below layout. However, when "WithinLimit" condition is met, the program fails to execute the action "Get & Add Request Co..." again. Is this by design? Is Zoho Flows unable to repeat actions
                                                                                                            • How to update "Lead Status" to more than 100 records

                                                                                                              Hello Zoho CRM, How do I update "Lead Status" to more than 100 records at once? To give you a background, these leads were uploaded or Imported at once but the lead status record was incorrectly chosen. So since there was a way to quickly add records in the system no matter how many they are, we are also wondering if there is a quicker way to update these records to the correct "Lead Status". I hope our concern makes sense and that there will be a fix for it. All the best, Jonathan
                                                                                                            • Adding branded signature to tickets reply

                                                                                                              Hi, i am unable to figure out how to add signatures with logo to tickets reply. please advice .
                                                                                                            • Ship via Carrier Not Working Since Commerce Update

                                                                                                              Since the recent update to the Commerce platform, I can no longer use the ship via carrier function. It will take me to the address screen and let me verify them but when I go to save and move tot he next screen it will not do anything. This is happening
                                                                                                            • Zoho Marketing Automation 2.0 - Landing Page function not working

                                                                                                              Dear Zoho Team, I am working on implementing Zoho Marketing Automation 2.0, and am now looking into the section "Lead Generation". If I open the "Landing Pages" section, I immediately get an Error code: Error: internal error occurred. Can you help me
                                                                                                            • automations: Can I execute a step on a specific date?

                                                                                                              I have created a form in Zoho forms, and created a contacts list. I have also begun setting up an automation with the intention of sending the form to the contact list on a specific date every month (via email) for the entire year (essentially sending
                                                                                                            • Nimble enhancements to WhatsApp for Business integration in Zoho CRM: Enjoy context and clarity in business messaging

                                                                                                              Dear Customers, We hope you're well! WhatsApp for business is a renowned business messaging platform that takes your business closer to your customers; it gives your business the power of personalized outreach. Using the WhatsApp for Business integration
                                                                                                            • Image Upload Field | Zoho Canvas

                                                                                                              I'm working on making a custom view for one of our team's modules. It's an image upload field (Placement Photo) that would allow our sales reps to upload a picture of the house their working on. However, I don't see that field as a opinion when building
                                                                                                            • Zoho Expense - The ability to add detail to a Trip during booking

                                                                                                              As an admin, I would like the ability to add more detail to the approved Trips. At present a requestor can add flights, accommodation details and suggest their preferences. It would be great if the exact details of the trip could be added either by the
                                                                                                            • Simplified Call Logging

                                                                                                              Our organization would like to start logging calls in our CRM; however, with 13 fields that can't be removed, our team is finding it extremely cumbersome. For our use case, we only need to record that a call happened theirfor would only need the following
                                                                                                            • Signup forms behaviour : Same email & multiple submissions

                                                                                                              My use case is that I have a signup form (FormA) that I use in several places on my website, with a hidden field so I can see where the contact has been made from. I also have a couple of other signup forms (FormB and FormC) that slight differences. All
                                                                                                            • Adding Folders in Android App

                                                                                                              Is it possible to create a new email folder within the Zoho Mail Android app?  Or can this only be done from the desktop version of Zoho Mail? Cheers!
                                                                                                            • Schedule Exports for Regular Project Updates

                                                                                                              Tracking project data often means exporting data at regular intervals. Instead of manually exporting data every time, users can schedule exports for Phases, Tasks, and Tasks in Zoho Projects. These exports can be set to run once, daily, weekly, or monthly
                                                                                                            • Question about custom fields using Pivot Tables.

                                                                                                              I have created a pivot table showing annual revenue of a client and how much payment that client is paying my company. Is there a way using pivot table to add an additional field that subtracts those to fields / shows me a percentage of that difference?
                                                                                                            • Request for Light/Dark Mode

                                                                                                              Would love the ability to switch between Light and Dark mode similar to Zoho CRM. https://help.zoho.com/portal/en/community/topic/introducing-dark-mode-light-mode-a-new-look-for-your-crm
                                                                                                            • Settings Icon No Longer in ZOHO Desk?

                                                                                                              In ZOHO desk, there has been a gear icon for settings. as of yesterday, it is no longer there. I showed up briefly this morning but is gone again.  Anybody else experiecing this? 
                                                                                                            • Signature field is showing black

                                                                                                              Hello, When customer signed the service form, it is showing as below picture Phone model: iPhone 16 Pro We tried delete and install application, but it not solved. This has on phone of a few person. There is any advice to solve this?
                                                                                                            • Range names in Zoho Sheet are BROKEN!

                                                                                                              Hi - you've pushed an update that has broken range names. A previously working spreadsheet now returns errors because the range names are not updating the values correctly. I've shared a video with the support desk to illustrate the problem. This spreadsheet
                                                                                                            • Journey Email - Ignored Contacts

                                                                                                              I have a journey setup which simply sends a string of emails over time. For some reason I am getting large amounts of the contacts who enter the first email being ignored and I can't find anywhere in reports or audit logs why these contacts are not
                                                                                                            • Involved account types are not applicable when create journals

                                                                                                              { "journal_date": "2016-01-31", "reference_number": "20160131", "notes": "SimplePay Payroll", "line_items": [{ "account_id": "538624000000035003", "description": "Net Pay", "amount": 26690.09, "debit_or_credit": "credit" }, { "account_id": "538624000000000403", "description": "Gross", "amount": 32000, "debit_or_credit": "debit" }, { "account_id": "538624000000000427", "description": "CPP", "amount": 1295.64, "debit_or_credit": "debit" }, { "account_id": "538624000000000376", "description":
                                                                                                            • Zoho Books - Include Payment Terms as a Custom View filter

                                                                                                              It would be great if you could created a custom view based on Payment Terms. This would be really handy for seeing a list of customers who have credit terms. A workaround is not required. I could do something with a creditor checkbox, but it would be
                                                                                                            • How to update changed purchase account of item in invoice

                                                                                                              I have selected the wrong purchase account for various articles and created invoices. I had to adjust the purchase account in the article afterwards, but the old purchase account is still posted in the transaction-journal of the invoice. To adjust the
                                                                                                            • Help - Zoho CRM notification on mobile (IOS/Android)

                                                                                                              Hello Community! Can I get the IOS/Andoid CRM app to notify me of events, calls, etc. due as I can with MANY other apps?   I am running the free Zoho I would like this to be native to the Zoho CRM app. I do not want to write a sep. mobile app
                                                                                                            • Zoho Books Idea - Include another field in Bank Details for Address

                                                                                                              Hi Books team, Currently use the Description field in the Bank Details to store the bank's address. This works fine but it would be great if you could add another field for Bank Address, so that other notes about the bank account could be stored in the
                                                                                                            • Reverse payment on accidentally closed invoice.

                                                                                                              An invoice was closed accidentally with the full payment added. However, only partial payment was paid. How can I reopen the invoice and reverse this to update it to show partial payment?
                                                                                                            • a question about the COQL API v8

                                                                                                              When I specify eight or more values in a WHERE IN clause and execute it, an error occurs. Is there a limit to the number of values that can be specified in a WHERE IN clause? ↓Error select * FROM Vendors WHERE (id in (1, 2, 3, 4, 5, 6, 7, 8, 9)) ↓Success
                                                                                                            • Zoho Books Idea - Bank Details Button on Banking

                                                                                                              Hi Books team, Sometimes I'm asked to share bank details with a customer or a colleague. So I go to the Banking Module, find the correct bank account, click Setting > Edit, then copy and paste the bank details. Wouldn't it be great if there was a button
                                                                                                            • JS SDK 8.0 – TypeError: Cannot read properties of undefined (reading 'getCacheStore') with sample code

                                                                                                              Hello Zoho Support Team, I’m integrating the Zoho CRM JavaScript SDK v8.0 and I’m getting the error below when running your official sample. I tested directly from: https://github.com/zoho/zohocrm-javascript-sdk-8.0/blob/main/samples/create_records_sample/create_records.js
                                                                                                            • Function #55: Convert multiple quotes to single SO using Custom Button

                                                                                                              Hello everyone, and welcome back to our series! In Zoho Books, after a quote is accepted by your customer, it can be converted into a sales order or an invoice. Often, a customer might have multiple quotes, and for easier billing or upon the customer's
                                                                                                            • Sending emails from an outlook account

                                                                                                              Hi, I need to know if it's possible to send automatic emails from an Outlook account configured in Zoho CRM and, if so, how I can accomplish that. To give you some context, I set up a domain and created a function that generates PDF files to be sent later
                                                                                                            • Zoho One - Syncing Merchants and Vendors Between Zoho Expense and Zoho Books

                                                                                                              Hi, I'm exploring the features of Zoho One under the trial subscription and have encountered an issue with syncing Merchant information between Zoho Expense and Zoho Books. While utilizing Zoho Expense to capture receipts, I noticed that when I submit
                                                                                                            • More controls for User Fields in CRM

                                                                                                              Dear All, We are here with a minor but crucial enhancement to the user fields—now set accessibility permissions to the records for user field. User field allows you to extend co-ownership of records to your peers. You can collaborate with them for certain
                                                                                                            • Rich Text For Notes in Zoho CRM

                                                                                                              Hello everyone, As you know, notes are essential for recording information and ensuring smooth communication across your records. With our latest update, you can now use Rich Text formatting to organize and structure your notes more efficiently. By using
                                                                                                            • Time based workflow without edit/action

                                                                                                              Hello I need help solving this problem if possible. We have Deals come into the CRM via Live Transfer which have the field properties: Stage = New Channel = Inbound Some of them don't get answered so we want these to automatically go into our Outbound
                                                                                                            • What's New - August 2025 | Zoho Backstage

                                                                                                              Every month, Zoho Backstage grows with you. These updates aren't just features and fixes, they're about making your workday smoother, your events more impactful, and your attendees happier. We’ve listened, learned, and shaped this release to keep things
                                                                                                            • Introducing notifications in the vendor portal

                                                                                                              Imagine this: You're a recruiter working with multiple vendors on a high-volume hiring project. You’ve just updated a job description after a last-minute change from the hiring manager. One of your vendors, however, is still working off the older version
                                                                                                            • Calls to accounts rather than leads or contacts?

                                                                                                              So..... We have a dilemma and I'm hoping someone has encountered this before and figured out a fix. We have just migrated to Zoho. It's great.....expect for how "Calls" are handled.... We are B2B. We do not use the leads module. A "Lead/Prospect" for
                                                                                                            • prevent selling expired items

                                                                                                              Hello. I need to make a constraint on expired batch items not to be sold. Is it possible in Zoho Inventory? if so, then how? Thanks for further help.
                                                                                                            • ZOHO BOOKS - EXCESSIVELY SLOW TODAY

                                                                                                              Dear Zoho Books This is not the first time but it seems to be 3 times per week now that the system is extremely slow. I work on Zoho Books 95% of my day so this is very frustrating. Zoho you need to do something about this. I have had my IT guy check
                                                                                                            • Product details removed during update from other system

                                                                                                              We maintain our product details in an other system. These details are synchronized with Zoho at the end of each day, through an API. This has worked perfectly sofar. But last Monday, all product codes and some other product data have been wiped during
                                                                                                            • Next Page