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

                                                                                                        • Out of Office not working

                                                                                                          I have set up out of office on zoho mail, however, it does not reply to every mail sent to it. I have tested it by sending several test messages from multiple different email accounts, I will get a response to some of them, but not all of them this is
                                                                                                        • Error message that says only images and no text

                                                                                                          I filled out a template for a weekly newsletter with text and images throughout but when I click save and next an error message comes up that says "Campaign content has only images and no text" which is not true at all. I have no idea how to fix this issue and don't know where the problem is. 
                                                                                                        • Link project invoices to sales orders

                                                                                                          As a business owner and project manager I create estimates with my clients which then become sales orders. When billing for project work I want to invoice against the agreed sales order. I see that I can create invoices and link them to sales orders in
                                                                                                        • Contacts Don't Always Populate

                                                                                                          I've noticed that some contacts can easily be added to an email when I type their name. Other times, a contact doesn't appear even though I KNOW it is in my contact list. It is possible the ones I loaded from a spreadsheet are not an issue and the ones
                                                                                                        • Cannot add zoho email to gmail acc

                                                                                                          I'm trying to set up my zoho mail to connect to my gmail acc but no matter what I try I always get this problem. What should I do now? Password is up-to-date. Authentication failed. Please check your username/password. [Server response: 535 Authentication
                                                                                                        • 553 Relaying disallowed - Invalid Domain

                                                                                                          I have this error "553 Relaying disallowed. Invalid Domain" when sending an email to any email address. But I still receiving email from other emails. I checked MX, DKIM, SPF and it's ok. Could you check and help? Thanks
                                                                                                        • Function #25: Automatically generate purchase orders from a sales order

                                                                                                          We kicked off the "Function Fridays" series with the goal of helping you automate your everyday accounting tasks. As we delve into today's post, I'm delighted to announce that we're here to present the 25th custom function in this series. While it is
                                                                                                        • Turn off Organization Contact List

                                                                                                          We need to be able to turn off the Organization Contact list for some of our staff. Once the Organization Contact list is turned off for a user, we would then like to be able to create a list of contacts on per user basis that would not be editable by
                                                                                                        • In the Blue Print Transition requirement received it will show 8 check field in pop up if they any one of this field then only move to next stage Ist quote

                                                                                                          In the Blue Print Transition requirement received it will show 8 check field in pop up if they any one of this field then only move to next stage Ist quote Pls help how i fix this
                                                                                                        • Unable to send massage Reason 553/ Relaying Disallowed. Invalid Domain

                                                                                                          Cant sed massages from my email. All massages from my domain received the same issue Unable to send massage Reason 553/ Relaying Disallowed. Invalid Domain
                                                                                                        • Kaizen #194 : Trigger Client Script via Custom buttons

                                                                                                          Hello everyone! Welcome back to another interesting and useful Kaizen post. We know that Client Scripts can be triggered with Canvas buttons and we discussed this with a use case in Kaizen#180. Today, let us discuss how to trigger Client Script when a
                                                                                                        • Issue with POST request creating Calls in CRM

                                                                                                          Hello, I am in the middle of integrating some 3rd party Call center API with Zoho CRM and going through our logs I see some discrepencies. We sometimes get an error: {"data":[{"code":"INVALID_DATA","details":{"api_name":"Call_Duration","json_path":"$.data[0].Call_Duration"},"message":"Please
                                                                                                        • Make record entry more organized with the Sections component in Wizards

                                                                                                          Hello everyone! Wizards in Zoho CRM have always helped you break long record-detail pages or large sets of fields into multiple screens, making data entry smoother and more user-friendly. Now, we’re taking a major step forward with a new Sections component—giving
                                                                                                        • Allowing subqueries in FROM clause

                                                                                                          When building a Query table in Zoho Reports, I encountered an error when attempting to put a subquery in the "FROM" clause of my statement.  Why isn't this currently supported?  Is there a plan to implement this functionality in the future?
                                                                                                        • GSTIN Public Search API

                                                                                                          Does zohobooks have an api using which i can search GST numbers and get their details?
                                                                                                        • External @zoho.com mail stopped working today, yesterday no issues

                                                                                                          Hello, Over a sudden mail stopped being delivered to inbox. Domain is standard zoho.com worked no problem yesterday, today nothing in inbox. Sent several test emails from corporate account & from gmail.com, logs show acceptance by zoho mail server, but
                                                                                                        • I wan to schedule a meeting report From previous Thursday to this thursday of this week on Every 6 pm want to recive this report in zoho CRM

                                                                                                          I wan to schedule a meeting report From previous Thursday to this thursday of this week on Every 6 pm want to recive this report in zoho CRM. How I Can achive this in Zoho CRM.
                                                                                                        • Quotes

                                                                                                          Has anyone figured out how to automatically upload a quote that was signed via Zoho Sign and insert it directly to that leads file and push it through the pipeline to proposal signed status?
                                                                                                        • Suggestion: Smart Purchasing Module for Zoho Inventory and Zoho Books

                                                                                                          Suggestion: Smart Purchasing Module for Zoho Inventory and Zoho Books As an active user of Zoho Inventory and Zoho Books, I’ve noticed that the suite already provides valuable tools for managing inventory, analyzing trends, and processing purchase orders.
                                                                                                        • TDS Filing

                                                                                                          Is there any option for automatic 26Q and 24Q filing in Zoho books. Even Tally has this option. Why don't Zoho has this ? Is there any customisation available for this ?
                                                                                                        • Adding bank details to the contact through API

                                                                                                          How to add bank-related information to the contact while creating it using API? The account number needs to be encrypted before sending it through API but not sure how to encrypt and get those values. Please guide me in this.
                                                                                                        • average cost display

                                                                                                          Hello there, I'm using the average cost valuation method, and the cost price shown in the Items menu should reflect the latest WAC (Weighted Average Cost). However, it doesn't update automatically. Is there a way to display the current average cost without
                                                                                                        • Apple Mail issues

                                                                                                          Dear Sir or Madam, I am trying to configure my Zoho mail account to Apple Mail. It is not working. It seems to need more information (perhaps a path prefix?) than is shown in your tutorial (<www.zoho.com/mail/help/apple-mac-imap.html>). After plugging
                                                                                                        • Assistance Required for Migrating Data from Odoo Inventory to Zoho Inventory

                                                                                                          Hi Team, I previously used Odoo Inventory to manage my stock and transactions, and I’ve now moved to Zoho Inventory. I’d like to migrate my data from Odoo—including product details, stock, purchase, and vendor information- into Zoho Inventory for continuity
                                                                                                        • I need my entire Zoho Account (mail/organization) deleted!

                                                                                                          Hey! I used zoho for my email aaron@aaronglass.me with domain forwarding/mx all that. I got rid of the mx info on my godaddy account and still Google won't let me sign up with my aaron@aaronglass.me email. (I'm moving to Google for business) SO! I was
                                                                                                        • Error: "Invalid Element warehouse_id" when sending order to Zoho

                                                                                                          i'm getting the error "Invalid Element warehouse_id" when trying to send an order to Zoho via API. Has anyone faced this issue before? How can I fix it?
                                                                                                        • No way to sell individual and case units smoothly in Zoho

                                                                                                          Currently, Zoho Inventory handles inventory primarily at the case level, which can be challenging for businesses that frequently need to break down cases into individual units for retail sales or smaller shipments. Although Zoho Inventory currently supports
                                                                                                        • How to handle multiple languages (Resume parser, Job opening, job board, career site) ?

                                                                                                          We are looking to bring Zoho Recruit to a market that needs to support 2 languages. The first thing we need to make sure is that the Candidate be flag with the language they speak. This is easy enough make a custom field that as the desire languages.
                                                                                                        • Multi-Card Selection and Cross-Zobot Copy-Paste Functionality

                                                                                                          Dear Zoho SalesIQ Team, We’d like to suggest a productivity-enhancing feature for the Zobot builder in Zoho SalesIQ: the ability to select multiple cards (modules) at once using a selection area, and then copy-paste them either within the same canvas
                                                                                                        • Shipping Labels

                                                                                                          Hi, Can we generate Packing Labels for manual shipping same as the format as Airway Bill in zoho books or inventory?
                                                                                                        • Add a Way to Duplicate Cards in the Same Canvas (Retain All Settings)

                                                                                                          Dear Zoho SalesIQ Team, We would like to request a new feature in Zoho SalesIQ: the ability to duplicate an existing card within the same canvas while retaining all of its information and settings, including conditions, configurations, and display preferences.
                                                                                                        • Session "Ask Me Anything" Zoho France - Le 26 Juin 2025 14h à 17h (en Français

                                                                                                          Chers Utilisateurs, Vous cherchez à mieux comprendre Zoho CRM ou Zoho Desk ? Nos experts seront disponibles pour répondre à toutes vos questions lors de notre session Ask Me Anything. Rejoignez-nous ici pour en discuter en ligne. Pendant trois heures,
                                                                                                        • How to work with getFieldNames formdata functions ,Any Examples

                                                                                                          I don't find any example showing usage of getFieldNames. Where do i find .is there any Help documents available
                                                                                                        • Empowered Custom Views: Cross-Module Criteria Now Supported in Zoho CRM

                                                                                                          Hello everyone, We’re excited to introduce cross-module criteria support in custom views! Custom views provide personalized perspectives on your data and that you can save for future use. You can share these views with all users or specific individuals
                                                                                                        • Managing two books in Zoho Books

                                                                                                          is it possible to effectively manage two separate books within Zoho Books? My organization is considering handling accounting for two distinct subsidiaries, and we would like to understand the best way to achieve this within the Zoho Books.
                                                                                                        • Unit Measurement Sign,

                                                                                                          Dear Zoho Support Team, I hope you are doing well. We recently purchased Zoho Inventory based on recommendations of your team that “it would be a great fit for our Shopify operations”. However, we are currently facing several urgent issues that require
                                                                                                        • Leadchain into a custom module

                                                                                                          Hello ZOHO Community ! is it possible to put the leads collected by leadchain into a custom module instaed of leads module ? Best wishes Niels
                                                                                                        • Deluge script issue : Mismatch of data type expression. Expected BIGINT but found STRING

                                                                                                          I'm building a Zoho Creator form to take inputs for Email, Bootcamp Name, and Tag. If a record with the same Email + Bootcamp exists in a custom module (bootcampattendence), I want to update it by adding a new tag. If it doesn’t exist, I want to create
                                                                                                        • Urgent: How to Bulk Upload Images in Zoho Inventory? Any Workarounds?

                                                                                                          We are currently onboarding 5,000+ items from Shopify into Zoho Inventory, but we’re struggling with the lack of a bulk image upload feature. Right now, we have to manually upload and assign images one by one, which is extremely time-consuming and inefficient.
                                                                                                        • Can I automatically update COGS and Inventory account when creating an item?

                                                                                                          I have been trying to get Zoho to update the other two fields when I update one (Sales Account, COGS account, and Inventory Account). I know this seems like not a huge time saver, but I am all about efficiency and being an independent taproom, I create
                                                                                                        • Next Page