Skip to content

Electronic invoicing with JavaScript

This tutorial builds three simple Node.js applications from scratch:

  1. Receive: connects and authenticates with the Invoicetronic API and downloads any new incoming invoices.
  2. Send: connects and authenticates with the Invoicetronic API and sends an invoice to the SDI.
  3. Update: connects and authenticates with the Invoicetronic API and consults the history of notifications returned by the SDI.

Before continuing, make sure all the prerequisites below are met.

Prerequisites

We assume that these prerequisites are met:

We use Node.js and npm as they are the de facto standard for server-side JavaScript, but the examples work with other compatible runtimes as well.

Tip

For an optimal JavaScript experience, consider using VS Code which offers excellent Node.js support. Make sure the JavaScript/Node.js extension is active.

Did you know?

The JavaScript SDK supports both modern async/await and traditional Promises, giving you flexibility in your programming style.

Receive

Create the app

The first step is to create the application directory and initialize the Node.js project:

mkdir receive && cd receive

Initialize the project with npm:

npm init -y

The command created a new Node.js project with a package.json file in the current directory.

Install the SDK

Install the Invoicetronic JavaScript SDK:

npm install @invoicetronic/js-sdk --save

Once that's done, open VS Code in the current directory:

code .

Configure the SDK

Create a new file called index.js and add the following code:

Configure the SDK
const invoicetronicSdk = require('@invoicetronic/js-sdk');

// Configure the SDK
const apiClient = invoicetronicSdk.ApiClient.instance;
const basicAuth = apiClient.authentications['Basic'];
basicAuth.username = 'YOUR TEST API KEY (starts with ik_test_)';

apiClient.basePath = 'https://api.invoicetronic.com/v1';

As you can see, we configure the SDK by setting the API's base path and your test API Key (not the live one). Notice how we use the username property to set the API Key.

API Key comes in pairs

When you create your account, you obtain a pair of API Keys. One is the test key for the API Sandbox, and the other is the live API's. You can tell the difference because the former starts with ik_test_, while the latter begins with ik_live_. In this tutorial, always use the test key.

Download invoices

We are ready to make a request. We want to download new vendor invoices that may be available from the SDI. Add these lines:

Download unread invoices
const fs = require('fs');

// Download unread invoices
const receiveApi = new invoicetronicSdk.ReceiveApi();

async function downloadInvoices() {
  try {
    const opts = {
      'unread': true,
      'includePayload': true
    };

    const inboundInvoices = await receiveApi.receiveGet(opts);
    console.log(`Received ${inboundInvoices.length} invoices`);

    for (const invoice of inboundInvoices) {
      if (invoice.encoding === 'xml') {
        fs.writeFileSync(invoice.fileName, invoice.payload, 'utf8');
      } else if (invoice.encoding === 'base64') {
        const buffer = Buffer.from(invoice.payload, 'base64');
        fs.writeFileSync(invoice.fileName, buffer);
      }

      console.log(`Downloaded ${invoice.fileName} from a vendor with VAT ID ${invoice.prestatore}`);
    }
  } catch (error) {
    console.error('Error:', error.message);
  }
}

downloadInvoices();

Payload Inclusion

We set includePayload: true to retrieve the actual invoice content in the payload property. Without this parameter, the payload field would be null by default, which increases performance and reduces response size when you only need metadata.

In the terminal, run the application:

node index.js

You should obtain an output similar to this one:

Received 3 invoices
Downloaded file1.xml from a vendor with VAT ID IT06157670966
Downloaded file2.xml.p7m from a vendor with VAT ID IT01280270057
Downloaded file3.xml.p7m from a vendor with VAT ID IT01280270057

The files are in the current directory, ready for you to inspect them.

Not receiving invoices in the live environment?

Ensure you registered with the Italian Revenue Service, which is a requirement for the live environment.

What we learned

In this example, we learned several things.

  1. We must configure the SDK by setting both the basePath and basicAuth.username authentication, the latter initialized with the API key.

  2. We must instantiate a class representing the endpoint we want to work with. In this case, we leverage ReceiveApi to download incoming invoices.

  3. Endpoint classes like ReceiveApi offer methods for interacting with their target entity. We call receiveGet to retrieve invoices. Because we only want new, unread invoices, we pass unread: true. We also pass includePayload: true to retrieve the actual invoice content.

  4. Invoice objects expose valuable properties such as encoding, fileName, and payload. The last one contains the invoice content, as plain text or Base64-encoded, as described by encoding.

Source Code on GitHub

The source code for this Quickstart is also available on GitHub.

Send

Create the app

The first step is to create the application directory and initialize the Node.js project:

mkdir send && cd send

Initialize the project with npm:

npm init -y

Install the SDK

Install the Invoicetronic JavaScript SDK:

npm install @invoicetronic/js-sdk --save

Once that's done, open VS Code in the current directory:

code .

Configure the SDK

Create a new file called index.js and add the following code:

Configure the SDK
const invoicetronicSdk = require('@invoicetronic/js-sdk');

// Configure the SDK
const apiClient = invoicetronicSdk.ApiClient.instance;
const basicAuth = apiClient.authentications['Basic'];
basicAuth.username = 'YOUR TEST API KEY (starts with ik_test_)';

apiClient.basePath = 'https://api.invoicetronic.com/v1';

As you can see, we configure the SDK by setting the API's base path and your test API Key (not the live one). Notice how we use the username property to set the API Key.

API Key comes in pairs

When you create your account, you obtain a pair of API Keys. One is the test key for the API Sandbox, and the other is the live API's. You can tell the difference because the former starts with ik_test_, while the latter begins with ik_live_. In this tutorial, always use the test key.

Send an invoice

We are ready to make a request. We want to send an invoice to the SDI. Add the following code:

Send an invoice
const fs = require('fs');
const path = require('path');

// Send an invoice
const filePath = '/some/file/path/filename.xml';

const metaData = {
  'internal_id': '123',
  'created_with': 'myapp',
  'some_other_custom_data': 'value'
};

const sendApi = new invoicetronicSdk.SendApi();

async function sendInvoice() {
  try {
    const sendData = new invoicetronicSdk.Send(fs.readFileSync(filePath, 'utf8'));
    sendData.fileName = path.basename(filePath);
    sendData.metaData = metaData;

    const sentInvoice = await sendApi.sendPost(sendData);

    console.log(`The invoice was sent successfully, it now has the unique Id of ${sentInvoice.id}.`);
  } catch (error) {
    console.error('Error:', error.message);
  }
}

sendInvoice();

In the terminal, run the application:

node index.js

You should obtain an output similar to this one:

The invoice filename.xml was sent successfully, it now has the unique Id of 123.

Check the invoice state

When you forward an invoice to the SDI, delivery is not instantaneous: the SDI runs a series of checks and returns a sequence of notifications that describe the state of the process (Inviato, Consegnato, Scartato, etc.). The Send model exposes a latest_state property with the current state, sparing you a separate /update call when you only need to know how it went.

Read the current state
// Fetch the most recent state of an already-sent invoice
const fresh = await sendApi.sendIdGet(sentInvoice.id);
console.log(`Current state: ${fresh['latest_state'] || 'Processing'}`);

Right after submission, latest_state may be undefined: the SDI has not processed the document yet. Check again after a few seconds or, better, configure a webhook to receive a push notification on every state change.

Save API calls

Use latest_state on Send whenever you only need the current state: a single call instead of one to /send plus one to /update. Reach for UpdateApi only when you need the full transition history.

What we learned

In this example, we learned several things.

  1. We must configure the SDK by setting both the basePath and basicAuth.username authentication, the latter initialized with the API key.

  2. We must instantiate a class representing the endpoint we want to work with. In this case, we leverage SendApi to send invoices. Endpoint classes like SendApi offer methods for interacting with their target entity. We call sendPost to send an invoice.

  3. The Send class exposes valuable properties such as fileName, metaData, and payload. The last one contains the invoice content, while metaData is optional and binds custom data to the document.

  4. The Send class also exposes latest_state with the current SDI state, readable via sendIdGet(id). It saves a /update call when you only need to know the state.

Source Code on GitHub

The source code for this Quickstart is also available on GitHub.

Update

For the current state of a sent invoice, just read latest_state from the Send model (see Check the invoice state). If instead you need the full transition history — for example to understand why an invoice was rejected, render every state transition with timestamps in your UI, or track the notifications returned by a public administration entity — use UpdateApi.

/update queries are free of charge

Requests to /update are not counted against your plan: you can poll the notification history as often as you need.

Create the app

mkdir update && cd update
npm init -y

Install the SDK

npm install @invoicetronic/js-sdk --save

Retrieve the notification history

Create a file index.js with the following code:

Notification history for an invoice
const invoicetronicSdk = require('@invoicetronic/js-sdk');

// Configure the SDK
const apiClient = invoicetronicSdk.ApiClient.instance;
const basicAuth = apiClient.authentications['Basic'];
basicAuth.username = 'YOUR TEST API KEY (starts with ik_test_)';
apiClient.basePath = 'https://api.invoicetronic.com/v1';

// Id of the sent invoice we want to inspect
const sendId = 225;

const updateApi = new invoicetronicSdk.UpdateApi();

async function fetchUpdates() {
  try {
    const updates = await updateApi.updateGet({
      sendId: sendId,
      sort: 'last_update'
    });

    console.log(`Found ${updates.length} notifications for invoice ${sendId}`);

    for (const update of updates) {
      console.log(`  [${update.lastUpdate}] state=${update.state} - ${update.description || 'OK'}`);
    }
  } catch (error) {
    console.error('Error:', error.message);
  }
}

fetchUpdates();

Run the application:

node index.js

You should obtain an output similar to this one:

Found 2 notifications for invoice 225
  [2025-01-23T16:56:14.111Z] state=Inviato - OK
  [2025-01-23T17:12:03.842Z] state=Consegnato - OK

The state field is the most important property. The most common values are:

Value Name Description
2 Inviato Sent to the SDI.
5 Consegnato Delivered to the recipient.
7 Scartato Rejected by the SDI. The reason is in description.

The complete list of values is available in the API Reference. You can also filter by state, for example to retrieve only rejected invoices:

const updates = await updateApi.updateGet({ state: 'Scartato' });

Always monitor the state of your sent invoices

A state of Inviato only means that the document has been accepted by the SDI, not that it has been delivered. A Scartato state indicates that the invoice was not accepted and may require a correction and a fresh submission.

What we learned

  1. To consult the notification history we use the UpdateApi class instead of SendApi or ReceiveApi.

  2. The updateGet() method accepts filters such as sendId (notifications for a specific sent invoice), state (filter by state), lastUpdateFrom/lastUpdateTo (date range) and others.

  3. /update queries are free of charge and do not count against your plan, so you can poll them as often as you need.

Source Code on GitHub

The source code for this Quickstart is also available on GitHub.