Electronic invoicing with PHP
This tutorial builds three simple PHP 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:
- PHP 7.4+ or PHP 8.x has been downloaded and installed
- Composer has been installed
- You obtained an active API Key
- You registered with the Italian Revenue Service (needed for the live environment)
We use Composer for dependency management, which is the de facto standard for modern PHP.
Tip
For an optimal PHP experience, consider using VS Code with the PHP extension or PHPStorm for a complete IDE.
Did you know?
The PHP SDK supports both Guzzle and other PSR-18 compatible HTTP clients, giving you flexibility in your implementation.
Receive
Create the app
The first step is to create the application directory:
Initialize the project with Composer:
The command created a new PHP project with a composer.json file in the current directory.
Install the SDK
Install the Invoicetronic PHP SDK:
Once that's done, open VS Code in the current directory:
Configure the SDK
Create a new file called index.php and add the following code:
<?php
require_once(__DIR__ . '/vendor/autoload.php');
// Configure the SDK
$config = Invoicetronic\Configuration::getDefaultConfiguration()
->setUsername('YOUR TEST API KEY (starts with ik_test_)');
$config->setHost('https://api.invoicetronic.com/v1');
As you can see, we configure the SDK by setting the API's host and your test API Key (not the live one). Notice how we use the setUsername() method 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
$receiveApi = new Invoicetronic\Api\ReceiveApi(
new GuzzleHttp\Client(),
$config
);
try {
$inboundInvoices = $receiveApi->receiveGet(
null, // page
null, // pageSize
null, // sort
true, // unread
true // includePayload
);
echo "Received " . count($inboundInvoices) . " invoices\n";
foreach ($inboundInvoices as $invoice) {
if ($invoice->getEncoding() === 'Xml') {
file_put_contents($invoice->getFileName(), $invoice->getPayload());
} elseif ($invoice->getEncoding() === 'Base64') {
file_put_contents($invoice->getFileName(), base64_decode($invoice->getPayload()));
}
echo "Downloaded {$invoice->getFileName()} from a vendor with VAT ID {$invoice->getPrestatore()}\n";
}
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage() . "\n";
}
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:
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 calling
getDefaultConfiguration()and setting the username (API key) withsetUsername()and the host withsetHost(). -
We must instantiate a class representing the endpoint we want to work with. In this case, we leverage
ReceiveApito download incoming invoices, passing an HTTP client (Guzzle) and 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 methods like
getEncoding(),getFileName(), andgetPayload(). The last one contains the invoice content, as plain text or Base64-encoded, as described bygetEncoding().
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 Composer:
Install the SDK
Install the Invoicetronic PHP SDK:
Once that's done, open VS Code in the current directory:
Configure the SDK
Create a new file called index.php and add the following code:
<?php
require_once(__DIR__ . '/vendor/autoload.php');
// Configure the SDK
$config = Invoicetronic\Configuration::getDefaultConfiguration()
->setUsername('YOUR TEST API KEY (starts with ik_test_)');
$config->setHost('https://api.invoicetronic.com/v1');
As you can see, we configure the SDK by setting the API's host and your test API Key (not the live one). Notice how we use the setUsername() method 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
$filePath = '/some/file/path/filename.xml';
$metaData = [
'internal_id' => '123',
'created_with' => 'myapp',
'some_other_custom_data' => 'value'
];
$sendApi = new Invoicetronic\Api\SendApi(
new GuzzleHttp\Client(),
$config
);
try {
$sendData = new Invoicetronic\Model\Send();
$sendData->setFileName(basename($filePath));
$sendData->setPayload(file_get_contents($filePath));
$sendData->setMetaData($metaData);
$sentInvoice = $sendApi->sendPost($sendData);
echo "The invoice was sent successfully, it now has the unique Id of {$sentInvoice->getId()}.\n";
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage() . "\n";
}
In the terminal, 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 class exposes a getLatestState() method 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
$fresh = $sendApi->sendIdGet($sentInvoice->getId());
echo "Current state: " . ($fresh->getLatestState() ?? 'Processing') . "\n";
Right after submission, getLatestState() may return 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 getLatestState() 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 calling
getDefaultConfiguration()and setting the username (API key) withsetUsername()and the host withsetHost(). -
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
Sendclass exposes methods likesetFileName(),setMetaData(), andsetPayload(). The last one contains the invoice content, whilesetMetaData()is optional and binds custom data to the document. -
The
Sendclass also exposesgetLatestState()with 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 getLatestState() from the Send class (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
composer init --name="invoicetronic/update-example" --type=project --no-interaction
Install the SDK
Retrieve the notification history
Create a file index.php with the following code:
<?php
require_once(__DIR__ . '/vendor/autoload.php');
// Configure the SDK
$config = Invoicetronic\Configuration::getDefaultConfiguration()
->setUsername('YOUR TEST API KEY (starts with ik_test_)');
$config->setHost('https://api.invoicetronic.com/v1');
// Id of the sent invoice we want to inspect
$sendId = 225;
$updateApi = new Invoicetronic\Api\UpdateApi(
new GuzzleHttp\Client(),
$config
);
try {
$updates = $updateApi->updateGet(
null, // companyId
null, // identifier
null, // prestatore
null, // unread
$sendId, // sendId
null, // state
null, // lastUpdateFrom
null, // lastUpdateTo
null, // dateSentFrom
null, // dateSentTo
null, // page
null, // pageSize
'last_update' // sort
);
echo "Found " . count($updates) . " notifications for invoice {$sendId}\n";
foreach ($updates as $update) {
$description = $update->getDescription() ?: 'OK';
echo " [{$update->getLastUpdate()->format('c')}] state={$update->getState()} - {$description}\n";
}
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage() . "\n";
}
Run the application:
You should obtain an output similar to this one:
Found 2 notifications for invoice 225
[2025-01-23T16:56:14+00:00] state=Inviato - OK
[2025-01-23T17:12:03+00:00] 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.