Electronic invoicing with TypeScript
This tutorial builds three simple TypeScript applications from scratch:
- Receive: connects and authenticates with the Invoicetronic API and downloads any new incoming invoices.
- Send: connects and authenticates with the Invoicetronic API and sends an invoice to the SDI.
- 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:
- Node.js 14+ has been downloaded and installed
- npm or yarn is installed (comes with Node.js)
- TypeScript is installed (will be installed as a project dependency)
- You obtained an active API Key
- You registered with the Italian Revenue Service (needed for the live environment)
We use npm for dependency management, but you can also use yarn if you prefer.
Tip
For an optimal TypeScript experience, consider using VS Code with TypeScript extensions or WebStorm for a complete IDE.
Did you know?
The TypeScript SDK offers full type safety, IDE autocomplete, and compile-time error detection, making integration safer and faster.
Receive
Create the app
The first step is to create the application directory:
Initialize the project with npm:
The command created a new Node.js project with a package.json file in the current directory.
Install the SDK
Install the Invoicetronic TypeScript SDK and TypeScript:
Once that's done, open VS Code in the current directory:
Configure TypeScript
Create a tsconfig.json file with the following configuration:
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"lib": ["ES2020"],
"outDir": "./dist",
"rootDir": "./",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true
},
"include": ["*.ts"],
"exclude": ["node_modules"]
}
Configure the SDK
Create a new file called index.ts and add the following code:
import { Configuration, ReceiveApi } from '@invoicetronic/ts-sdk';
// Configure the SDK
const config = new Configuration({
username: 'YOUR TEST API KEY (starts with ik_test_)',
basePath: 'https://api.invoicetronic.com/v1'
});
As you can see, we configure the SDK by passing your test API Key (not the live one) and the API host. Notice how we use the username field 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:
import * as fs from 'fs';
// Download unread invoices
const receiveApi = new ReceiveApi(config);
async function downloadInvoices() {
try {
const inboundInvoices = await receiveApi.receiveGet(
undefined, // companyId
undefined, // identifier
true, // unread
undefined, // committente
undefined, // prestatore
undefined, // fileName
undefined, // lastUpdateFrom
undefined, // lastUpdateTo
undefined, // dateSentFrom
undefined, // dateSentTo
undefined, // documentDateFrom
undefined, // documentDateTo
undefined, // documentNumber
true // includePayload
);
console.log(`Received ${inboundInvoices.data.length} invoices`);
for (const invoice of inboundInvoices.data) {
if (invoice.encoding === 'Xml') {
fs.writeFileSync(invoice.file_name!, invoice.payload!, 'utf8');
} else if (invoice.encoding === 'Base64') {
const buffer = Buffer.from(invoice.payload!, 'base64');
fs.writeFileSync(invoice.file_name!, buffer);
}
console.log(`Downloaded ${invoice.file_name} from a vendor with VAT ID ${invoice.prestatore}`);
}
} catch (error: any) {
console.error('Error:', error.message);
if (error.response) {
console.error('Details:', error.response.data);
}
}
}
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.
Add a build script in package.json:
In the terminal, build and run the application:
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.
-
We must configure the SDK by creating a
Configurationinstance and passing username (API key) and basePath (API URL). -
We must instantiate a class representing the endpoint we want to work with. In this case, we leverage
ReceiveApito download incoming invoices, passing the configuration. -
Endpoint classes like
ReceiveApioffer methods for interacting with their target entity. We callreceiveGet()to retrieve invoices. Because we only want new, unread invoices, we passtruefor theunreadparameter. We also passtrueforincludePayloadto retrieve the actual invoice content. -
Invoice objects expose properties like
encoding,file_name, andpayload. The last one contains the invoice content, as plain text or Base64-encoded, as described byencoding.
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:
Initialize the project with npm:
Install the SDK
Install the Invoicetronic TypeScript SDK and TypeScript:
Once that's done, open VS Code in the current directory:
Configure TypeScript
Create a tsconfig.json file with the following configuration:
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"lib": ["ES2020"],
"outDir": "./dist",
"rootDir": "./",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true
},
"include": ["*.ts"],
"exclude": ["node_modules"]
}
Configure the SDK
Create a new file called index.ts and add the following code:
import { Configuration, SendApi, Send } from '@invoicetronic/ts-sdk';
// Configure the SDK
const config = new Configuration({
username: 'YOUR TEST API KEY (starts with ik_test_)',
basePath: 'https://api.invoicetronic.com/v1'
});
As you can see, we configure the SDK by passing your test API Key (not the live one) and the API host. Notice how we use the username field 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:
import * as fs from 'fs';
import * as path from 'path';
// Send an invoice
const filePath = '/some/file/path/filename.xml';
const metaData: { [key: string]: string } = {
'internal_id': '123',
'created_with': 'myapp',
'some_other_custom_data': 'value'
};
const sendApi = new SendApi(config);
async function sendInvoice() {
try {
const sendData: Send = {
file_name: path.basename(filePath),
payload: fs.readFileSync(filePath, 'utf8'),
meta_data: metaData
};
const sentInvoice = await sendApi.sendPost(sendData);
console.log(`The invoice was sent successfully, it now has the unique Id of ${sentInvoice.data.id}.`);
} catch (error: any) {
console.error('Error:', error.message);
if (error.response) {
console.error('Details:', error.response.data);
}
}
}
sendInvoice();
Add a build script in package.json:
In the terminal, build and run the application:
You should obtain an output similar to this one:
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 interface exposes a latest_state property with the current state, sparing you a separate /update call when you only need to know how it went.
// Fetch the most recent state of an already-sent invoice
const fresh = await sendApi.sendIdGet(sentInvoice.data.id!);
console.log(`Current state: ${fresh.data.latest_state ?? 'Processing'}`);
Right after submission, latest_state may be null: 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.
-
We must configure the SDK by creating a
Configurationinstance and passing username (API key) and basePath (API URL). -
We must instantiate a class representing the endpoint we want to work with. In this case, we leverage
SendApito send invoices. Endpoint classes likeSendApioffer methods for interacting with their target entity. We callsendPost()to send an invoice. -
The
Sendinterface exposes properties likefile_name,meta_data, andpayload. The last one contains the invoice content, whilemeta_datais optional and binds custom data to the document. -
The
Sendinterface also exposeslatest_statewith the current SDI state, readable viasendIdGet(id). It saves a/updatecall 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 interface (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 application
Install the SDK
Retrieve the notification history
Create a file index.ts with the following code:
import { Configuration, UpdateApi } from '@invoicetronic/ts-sdk';
// Configure the SDK
const config = new Configuration({
username: 'YOUR TEST API KEY (starts with ik_test_)',
basePath: 'https://api.invoicetronic.com/v1'
});
// Id of the sent invoice we want to inspect
const sendId = 225;
const updateApi = new UpdateApi(config);
async function fetchUpdates() {
try {
const response = await updateApi.updateGet(
undefined, // companyId
undefined, // identifier
undefined, // prestatore
undefined, // unread
sendId, // sendId
undefined, // state
undefined, // lastUpdateFrom
undefined, // lastUpdateTo
undefined, // dateSentFrom
undefined, // dateSentTo
undefined, // page
undefined, // pageSize
'last_update' // sort
);
console.log(`Found ${response.data.length} notifications for invoice ${sendId}`);
for (const update of response.data) {
console.log(` [${update.last_update}] state=${update.state} - ${update.description || 'OK'}`);
}
} catch (error: any) {
console.error('Error:', error.message);
}
}
fetchUpdates();
Compile and run the application:
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.
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
-
To consult the notification history we use the
UpdateApiclass instead ofSendApiorReceiveApi. -
The
updateGet()method accepts filters such assendId(notifications for a specific sent invoice),state(filter by state),lastUpdateFrom/lastUpdateTo(date range) and others. -
/updatequeries 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.