Skip to content

Electronic invoicing with Go

This tutorial builds three simple Go 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:

Tip

For an optimal Go experience, consider using Go modules for dependency management.

Did you know?

The Go SDK is perfect for microservices, cloud applications, and high-performance systems thanks to its compiled nature and native concurrency.

Receive

Create the app

The first step is to create the application directory and initialize a Go module:

mkdir receive && cd receive
go mod init invoicetronic-receive-example

Install the SDK

Install the Go SDK:

go get github.com/invoicetronic/go-sdk

Configure the SDK

Create the file main.go:

Configure the SDK
package main

import (
    "context"
    "encoding/base64"
    "fmt"
    "os"

    invoicetronicsdk "github.com/invoicetronic/go-sdk"
)

func main() {
    // Configure the SDK
    config := invoicetronicsdk.NewConfiguration()
    config.Servers = invoicetronicsdk.ServerConfigurations{
        {
            URL: "https://api.invoicetronic.com/v1",
        },
    }

    apiKey := "YOUR TEST API KEY (starts with ik_test_)"
    auth := apiKey + ":"
    authHeader := "Basic " + base64.StdEncoding.EncodeToString([]byte(auth))
    config.AddDefaultHeader("Authorization", authHeader)

    client := invoicetronicsdk.NewAPIClient(config)
}

As you can see, we configure the SDK by setting the server URL and HTTP Basic authentication with your test API Key (not the live one). Notice how we encode the API key followed by ":" in Base64 for the Authorization header.

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 this code to the main function:

Download unread invoices
    // Download unread invoices
    ctx := context.Background()

    unread := true
    includePayload := true

    inboundInvoices, _, err := client.ReceiveAPI.ReceiveGet(ctx).
        Unread(unread).
        IncludePayload(includePayload).
        Execute()

    if err != nil {
        fmt.Fprintf(os.Stderr, "Error: %v\\n", err)
        return
    }

    fmt.Printf("Received %d invoices\\n", len(inboundInvoices))

    for _, invoice := range inboundInvoices {
        if invoice.Encoding != nil {
            if *invoice.Encoding == "Xml" {
                err = os.WriteFile(*invoice.FileName, []byte(*invoice.Payload), 0644)
            } else if *invoice.Encoding == "Base64" {
                decoded, _ := base64.StdEncoding.DecodeString(*invoice.Payload)
                err = os.WriteFile(*invoice.FileName, decoded, 0644)
            }

            if err != nil {
                fmt.Fprintf(os.Stderr, "Error saving file: %v\\n", err)
                continue
            }

            fmt.Printf("Downloaded %s from a vendor with VAT ID %s\\n",
                *invoice.FileName, invoice.Prestatore.Get())
        }
    }

Payload Inclusion

We set IncludePayload(true) to retrieve the actual invoice content in the Payload property. Without this parameter, the Payload field would be nil by default, which increases performance and reduces response size when you only need metadata.

Build and run the application:

go run main.go

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 creating a Configuration, setting the server URL, and adding the Authorization header with HTTP Basic (API key encoded in Base64 followed by ":").

  2. We must create an API client with NewAPIClient(config) and use specific APIs like ReceiveAPI to download incoming invoices.

  3. API calls use a fluent pattern with methods like ReceiveGet(ctx).Unread(true).IncludePayload(true).Execute(). 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 use pointers for optional fields. The Encoding field can have the values "Xml" or "Base64", and Payload contains the invoice content.

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 a Go module:

mkdir send && cd send
go mod init invoicetronic-send-example

Install the SDK

Install the Go SDK:

go get github.com/invoicetronic/go-sdk

Configure the SDK

Create the file main.go:

Configure the SDK
package main

import (
    "context"
    "encoding/base64"
    "fmt"
    "os"
    "path/filepath"

    invoicetronicsdk "github.com/invoicetronic/go-sdk"
)

func main() {
    // Configure the SDK
    config := invoicetronicsdk.NewConfiguration()
    config.Servers = invoicetronicsdk.ServerConfigurations{
        {
            URL: "https://api.invoicetronic.com/v1",
        },
    }

    apiKey := "YOUR TEST API KEY (starts with ik_test_)"
    auth := apiKey + ":"
    authHeader := "Basic " + base64.StdEncoding.EncodeToString([]byte(auth))
    config.AddDefaultHeader("Authorization", authHeader)

    client := invoicetronicsdk.NewAPIClient(config)
}

As you can see, we configure the SDK by setting the server URL and HTTP Basic authentication with your test API Key (not the live one).

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 this code to the main function:

Send an invoice
    // Send an invoice
    filePath := "/some/file/path/filename.xml"

    metaData := map[string]string{
        "internal_id":             "123",
        "created_with":            "myapp",
        "some_other_custom_data": "value",
    }

    ctx := context.Background()

    payload, err := os.ReadFile(filePath)
    if err != nil {
        fmt.Fprintf(os.Stderr, "Error reading file: %v\\n", err)
        return
    }

    fileName := filepath.Base(filePath)
    payloadStr := string(payload)

    sendData := *invoicetronicsdk.NewSend(payloadStr)
    sendData.SetFileName(fileName)
    sendData.SetMetaData(metaData)

    sentInvoice, _, err := client.SendAPI.SendPost(ctx).Send(sendData).Execute()

    if err != nil {
        fmt.Fprintf(os.Stderr, "Error: %v\\n", err)
        return
    }

    fmt.Printf("The invoice was sent successfully, it now has the unique Id of %s.\\n",
        *sentInvoice.Id)

Build and run the application:

go run main.go

You should obtain an output similar to this one:

The invoice 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 LatestState field 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
    fresh, _, err := client.SendAPI.SendIdGet(ctx, *sentInvoice.Id).Execute()
    if err != nil {
        fmt.Fprintf(os.Stderr, "Error: %v\\n", err)
        return
    }

    state := fresh.GetLatestState()
    if state == "" {
        state = "Processing"
    }
    fmt.Printf("Current state: %s\\n", state)

Right after submission, GetLatestState() may return an empty string (HasLatestState() returns false): 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 LatestState 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 creating a Configuration, setting the server URL, and adding the Authorization header with HTTP Basic.

  2. We must create an API client and use SendAPI to send invoices. API calls use the pattern SendPost(ctx).Send(sendData).Execute().

  3. The Send model is created with NewSend() and configured with setters: SetFileName(), SetPayload(), and SetMetaData(). The payload contains the invoice content, while MetaData is optional and binds custom data to the document.

  4. The Send model also exposes LatestState with the current SDI state, readable via client.SendAPI.SendIdGet(ctx, id).Execute() and the GetLatestState() getter. 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 LatestState 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 application

mkdir update && cd update
go mod init invoicetronic-update-example

Install the SDK

go get github.com/invoicetronic/go-sdk

Retrieve the notification history

Create the file main.go:

Notification history for an invoice
package main

import (
    "context"
    "encoding/base64"
    "fmt"
    "os"

    invoicetronicsdk "github.com/invoicetronic/go-sdk"
)

func main() {
    // Configure the SDK
    config := invoicetronicsdk.NewConfiguration()
    config.Servers = invoicetronicsdk.ServerConfigurations{
        {
            URL: "https://api.invoicetronic.com/v1",
        },
    }

    apiKey := "YOUR TEST API KEY (starts with ik_test_)"
    auth := apiKey + ":"
    authHeader := "Basic " + base64.StdEncoding.EncodeToString([]byte(auth))
    config.AddDefaultHeader("Authorization", authHeader)

    client := invoicetronicsdk.NewAPIClient(config)

    // Id of the sent invoice we want to inspect
    sendId := int32(225)

    ctx := context.Background()

    updates, _, err := client.UpdateAPI.UpdateGet(ctx).
        SendId(sendId).
        Sort("last_update").
        Execute()

    if err != nil {
        fmt.Fprintf(os.Stderr, "Error: %v\n", err)
        return
    }

    fmt.Printf("Found %d notifications for invoice %d\n", len(updates), sendId)

    for _, update := range updates {
        description := "OK"
        if update.Description.IsSet() && update.Description.Get() != nil {
            description = *update.Description.Get()
        }
        fmt.Printf("  [%s] state=%v - %s\n", update.LastUpdate.Format("2006-01-02T15:04:05Z"), *update.State, description)
    }
}

Compile and run the application:

go run main.go

You should obtain an output similar to this one:

Found 2 notifications for invoice 225
  [2025-01-23T16:56:14Z] state=Inviato - OK
  [2025-01-23T17:12:03Z] 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

  1. To consult the notification history we use UpdateAPI instead of SendAPI or ReceiveAPI.

  2. API calls use the fluent pattern UpdateGet(ctx).SendId(...).Sort(...).Execute(). Filters such as SendId, State, LastUpdateFrom/LastUpdateTo and others are available.

  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.