Verifactu in Visual Basic: how to send invoices with the Verifactu API
With the Verifactu API you send an invoice from Visual Basic .NET with HttpClient: a JSON POST request to https://api.verifacti.com/verifactu/create that immediately returns the QR in Base64, the hash and a uuid. In VB6 it works the same with WinHttpRequest through COM. You don't need to generate the XML, compute the hash or use a digital certificate.
This tutorial uses VB.NET on .NET 6 or later with HttpClient and System.Text.Json. For VB6 and VBA, the WinHttpRequest variant is at the end of step 1.
Before you start
- A free Verifacti account: it includes a test environment and a test NIF.
- The test API key of the test NIF (it starts with
vf_test_) in theVERIFACTI_API_KEYenvironment variable. Never write it in the code. - The .NET 6 SDK or later (dotnet new console -lang VB).
To register your own NIFs later, follow the Verifactu API quick start guide.
1. Authentication
Every call carries the Authorization: Bearer header with your API key. The API key sets the issuing NIF and the environment (test or production): you don't send them in the request. The base URL is https://api.verifacti.com, the same in test and production.
This tutorial uses a single HttpClient for the whole application. Add this module as Verifacti.vb to a console project and replace Program.vb with the example of each step (each one has its own Sub Main).
' Verifacti.vb: una sola función para todas las llamadas a la API de Verifacti.
' Lee la API key de la variable de entorno VERIFACTI_API_KEY.
Imports System.Net.Http
Imports System.Net.Http.Headers
Imports System.Net.Http.Json
Imports System.Text.Json
Public Module Verifacti
Private ReadOnly Http As New HttpClient() With {
.BaseAddress = New Uri("https://api.verifacti.com"),
.Timeout = TimeSpan.FromSeconds(30)
}
Sub New()
Http.DefaultRequestHeaders.Authorization =
New AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("VERIFACTI_API_KEY"))
End Sub
Public Function Hoy() As String
Return TimeZoneInfo.ConvertTimeBySystemTimeZoneId(DateTime.UtcNow, "Europe/Madrid").ToString("dd-MM-yyyy")
End Function
Public Async Function Send(method As HttpMethod, path As String, Optional body As Object = Nothing,
Optional idempotencyKey As String = Nothing) As Task(Of (Status As Integer, Body As JsonElement))
Using request As New HttpRequestMessage(method, path)
If body IsNot Nothing Then request.Content = JsonContent.Create(body)
If idempotencyKey IsNot Nothing Then request.Headers.Add("Idempotency-Key", idempotencyKey)
Using response = Await Http.SendAsync(request)
Dim json = Await response.Content.ReadFromJsonAsync(Of JsonElement)()
Return (CInt(response.StatusCode), json)
End Using
End Using
End Function
End ModuleWith another HTTP client
VB6 and VBA have no HttpClient: use WinHttpRequest (reference «Microsoft WinHTTP Services, version 5.1»). The JSON is built as text.
' VB6 / VBA: referencia "Microsoft WinHTTP Services, version 5.1"
Function VerifactiCrear(ByVal json As String) As String
Dim http As New WinHttp.WinHttpRequest
http.Open "POST", "https://api.verifacti.com/verifactu/create", False
http.SetRequestHeader "Authorization", "Bearer " & Environ$("VERIFACTI_API_KEY")
http.SetRequestHeader "Content-Type", "application/json; charset=utf-8"
http.Option(9) = &H800 ' WinHttpRequestOption_SecureProtocols = TLS 1.2
http.Send json
VerifactiCrear = http.Status & " " & http.ResponseText
End Function
Sub EnviarFactura()
Dim hoy As String, json As String
hoy = Format$(Date, "dd-mm-yyyy")
json = "{""serie"":""A"",""numero"":""1"",""fecha_expedicion"":""" & hoy & """," & _
"""tipo_factura"":""F1"",""descripcion"":""Servicios de consultoria""," & _
"""nif"":""A15022510"",""nombre"":""Empresa Cliente SL""," & _
"""lineas"":[{""base_imponible"":""200.00"",""tipo_impositivo"":""21"",""cuota_repercutida"":""42.00""}]," & _
"""importe_total"":""242.00""}"
Debug.Print VerifactiCrear(json)
End Sub2. Create the invoice
Create the invoice with POST /verifactu/create. This is a full invoice (F1) with one line at 21%. fecha_expedicion is today's date as DD-MM-YYYY: the test environment only accepts today's (or yesterday's).
Amounts go as text, with a decimal point and at most two decimals. importe_total must match the sum of base_imponible and cuota_repercutida of the lines. nif and nombre are the recipient's: the issuing NIF comes from the API key.
Imports System.IO
Imports System.Net.Http
Module Crear
Function Main() As Integer
Dim factura = New With {
.serie = "A",
.numero = "1",
.fecha_expedicion = Verifacti.Hoy(),
.tipo_factura = "F1",
.descripcion = "Servicios de consultoría",
.nif = "A15022510",
.nombre = "Empresa Cliente SL",
.lineas = {New With {.base_imponible = "200.00", .tipo_impositivo = "21", .cuota_repercutida = "42.00"}},
.importe_total = "242.00"
}
Dim resultado = Verifacti.Send(HttpMethod.Post, "/verifactu/create", factura).Result
If resultado.Status <> 200 Then
Console.WriteLine($"Error {resultado.Status}: {resultado.Body}")
Return 1
End If
Console.WriteLine($"uuid: {resultado.Body.GetProperty("uuid")}")
Console.WriteLine($"estado: {resultado.Body.GetProperty("estado")}")
File.WriteAllText("respuesta.json", resultado.Body.GetRawText())
Return 0
End Function
End ModuleFor other invoice types (simplified F2, corrective R1–R5, exempt…), see the Verifactu invoice examples.
3. Read the response and the QR
The response arrives straight away, without waiting for the AEAT:
uuid: identifier of the invoicing record. Store it to check the status.estado: alwaysPendienteon creation. Verifacti queues the record and sends it to the Spanish Tax Agency (AEAT), usually within one or two minutes.url: AEAT verification URL encoded in the QR.qr: PNG image of the QR (290 × 290 px) in Base64.huella: hash of the record, already chained to the previous one.
{
"estado": "Pendiente",
"uuid": "b018ced3-b362-4494-8776-9eefff1c160c",
"url": "https://prewww2.aeat.es/wlpl/TIKE-CONT/ValidarQR?nif=B12345674&numserie=A1&fecha=19-11-2026&importe=242.00",
"qr": "iVBORw0KGgoAAAANSUhEUgAAASIAAAEi...",
"huella": "B11F3A015173AD99075E2720F61E2DE1FF08CBFEDD85C6F73C77AD835301B2A3"
}Imports System.IO
Imports System.Text.Json
Module Qr
Sub Main()
Dim respuesta = JsonDocument.Parse(File.ReadAllText("respuesta.json")).RootElement
File.WriteAllBytes("qr.png", Convert.FromBase64String(respuesta.GetProperty("qr").GetString()))
Console.WriteLine($"QR guardado en qr.png. URL de verificación: {respuesta.GetProperty("url")}")
End Sub
End ModuleQR size, position and legend on the invoice, in Verifactu QR.
4. Place the QR on the PDF invoice
To place the QR on a PDF from VB.NET you can use PDFsharp or iText. This PDFsharp example (dotnet add package PDFsharp) inserts the PNG you saved in the previous step at 35 × 35 mm.
' dotnet add package PDFsharp
Imports PdfSharp.Drawing
Imports PdfSharp.Pdf
Module Pdf
Sub Main()
Dim documento As New PdfDocument()
Dim pagina = documento.AddPage()
Using gfx = XGraphics.FromPdfPage(pagina)
Dim qr = XImage.FromFile("qr.png")
gfx.DrawImage(qr, XUnit.FromMillimeter(10).Point, XUnit.FromMillimeter(14).Point,
XUnit.FromMillimeter(35).Point, XUnit.FromMillimeter(35).Point)
End Using
documento.Save("factura.pdf")
End Sub
End ModuleWith the API you don't need to generate the QR: it comes in the response. If you still want to generate it from the url, you can use ZXing.Net.
5. Check the status
Check the record status with GET /verifactu/status?uuid=…. Do it after a minute or, better, get the result by webhook (step 8). Never in a loop without a wait.
The possible states are Pendiente, Correcto, Aceptado con errores, Incorrecto, Duplicado, Anulado, Factura inexistente, No registrado and Error servidor AEAT. With Aceptado con errores or Incorrecto, the response carries the AEAT's codigo_error and mensaje_error: what to do in each case, in Verifactu errors.
Imports System.IO
Imports System.Net.Http
Imports System.Text.Json
Module Estado
Sub Main()
Dim uuid = JsonDocument.Parse(File.ReadAllText("respuesta.json")).RootElement.GetProperty("uuid").GetString()
Dim resultado = Verifacti.Send(HttpMethod.Get, $"/verifactu/status?uuid={Uri.EscapeDataString(uuid)}").Result
Dim estado = resultado.Body.GetProperty("estado").GetString()
Console.WriteLine($"estado: {estado}")
If estado = "Incorrecto" OrElse estado = "Aceptado con errores" Then
Console.WriteLine($"AEAT {resultado.Body.GetProperty("codigo_error")}: {resultado.Body.GetProperty("mensaje_error")}")
End If
End Sub
End Module{
"nif": "B12345674",
"serie": "A",
"numero": "1",
"fecha_expedicion": "19-11-2026",
"operacion": "Alta",
"estado": "Correcto",
"url": "https://prewww2.aeat.es/wlpl/TIKE-CONT/ValidarQR?nif=B12345674&numserie=A1&fecha=19-11-2026&importe=242.00",
"qr": "iVBORw0KGgoAAAANSUhEUgAAASIAAAEi...",
"codigo_error": null,
"mensaje_error": null,
"estado_registro_duplicado": null
}6. Corrective invoices and cancellations
- Corrective invoice: a new invoice with
tipo_facturaR1 to R5, created with the samePOST /verifactu/create. See corrective invoice. - Cancellation:
POST /verifactu/cancel, only for invoices that should never have been issued. See cancellation. - Correction:
PUT /verifactu/modify, to fix data of a record already sent. See correction.
Imports System.Net.Http
Module Anular
Sub Main()
Dim anulacion = New With {.serie = "A", .numero = "1", .fecha_expedicion = Verifacti.Hoy()}
Dim resultado = Verifacti.Send(HttpMethod.Post, "/verifactu/cancel", anulacion).Result
Console.WriteLine($"{resultado.Status} {resultado.Body}")
End Sub
End ModuleThe cancellation answers with its own uuid, estado Pendiente and huella.
7. Retries without duplicates
Send the optional Idempotency-Key header on /create, /create_bulk, /modify and /cancel. Generate a UUID per invoice and reuse it on the retries of that same invoice:
- Same body and same key: the API returns the first response, with the
Idempotent-Replayed: trueheader, and creates no new record. 409: the first request is still in progress. Wait a few seconds and repeat.422: you used the key with a different body. Use a new key.- A
400is stored too: if you fix the data, use a new key.5xxresponses are not stored, and the retry is processed again. - The key is remembered for 24 hours and is tied to the issuing NIF. If more than 24 hours have passed without a response, check with
POST /verifactu/status(serie,numeroandfecha_expedicion) whether the invoice was registered before sending it again.
Imports System.Net.Http
Imports System.Text.Json
Imports System.Threading
Module Reintentos
Function CrearFactura(factura As Object, clave As String) As (Status As Integer, Body As JsonElement)
For intento = 1 To 5
Try
Dim resultado = Verifacti.Send(HttpMethod.Post, "/verifactu/create", factura, clave).Result
If resultado.Status <> 409 AndAlso resultado.Status < 500 Then Return resultado
Catch ex As AggregateException
End Try
If intento < 5 Then Thread.Sleep(TimeSpan.FromSeconds(2 ^ intento))
Next
Throw New Exception("Sin respuesta tras 5 intentos: reintenta más tarde con la misma clave")
End Function
Sub Main()
Dim factura = New With {
.serie = "A",
.numero = "2",
.fecha_expedicion = Verifacti.Hoy(),
.tipo_factura = "F1",
.descripcion = "Servicios de consultoría",
.nif = "A15022510",
.nombre = "Empresa Cliente SL",
.lineas = {New With {.base_imponible = "100.00", .tipo_impositivo = "21", .cuota_repercutida = "21.00"}},
.importe_total = "121.00"
}
Dim clave = Guid.NewGuid().ToString()
Dim resultado = CrearFactura(factura, clave)
Console.WriteLine(If(resultado.Status = 200, $"200 {resultado.Body.GetProperty("uuid")}", $"{resultado.Status} {resultado.Body}"))
End Sub
End Module8. Webhooks
Instead of checking the status, get the result by webhook. Webhooks are created with the NIF management API and linked to one or more NIFs. That API uses the account API key (it starts with vfn_, in the VERIFACTI_NIFS_API_KEY variable), available with an active subscription. With the free account you can create one webhook from the dashboard.
Imports System.Net.Http
Imports System.Net.Http.Headers
Imports System.Net.Http.Json
Module CrearWebhook
Sub Main()
Using http As New HttpClient()
http.DefaultRequestHeaders.Authorization =
New AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("VERIFACTI_NIFS_API_KEY"))
Dim webhook = New With {
.url = "https://tu-dominio.com/webhook",
.entorno = "test",
.secret = Environment.GetEnvironmentVariable("VERIFACTI_WEBHOOK_SECRET"),
.nifs = {"B12345674"} ' el NIF de prueba de tu cuenta
}
Dim response = http.PostAsJsonAsync("https://api.verifacti.com/webhooks", webhook).Result
Console.WriteLine($"{CInt(response.StatusCode)} {response.Content.ReadAsStringAsync().Result}")
End Using
End Sub
End ModuleReceive the notification
Each notification is a POST with a JSON array of records, with the same fields as GET /verifactu/status plus the uuid (and without the QR). If you set a secret, the X-Webhook-Signature header carries the hex HMAC-SHA256 of the body: compute it over the body as received, before parsing it. X-Webhook-Id is the same on every retry of a notification: use it to avoid processing it twice. Answer 2xx within 10 seconds. This receiver uses HttpListener, with no dependencies, and compares the signature with CryptographicOperations.FixedTimeEquals.
Imports System.IO
Imports System.Net
Imports System.Security.Cryptography
Imports System.Text
Imports System.Text.Json
Module Webhook
Sub Main()
Dim secret = Encoding.UTF8.GetBytes(Environment.GetEnvironmentVariable("VERIFACTI_WEBHOOK_SECRET"))
Dim listener As New HttpListener()
' En Windows, ejecútalo como administrador o reserva la URL:
' netsh http add urlacl url=http://+:8080/ user=TU_USUARIO
listener.Prefixes.Add("http://+:8080/")
listener.Start()
While True
Dim contexto = listener.GetContext()
Try
Dim cuerpo = New StreamReader(contexto.Request.InputStream, Encoding.UTF8).ReadToEnd()
Dim esperada = Convert.ToHexString(HMACSHA256.HashData(secret, Encoding.UTF8.GetBytes(cuerpo))).ToLowerInvariant()
Dim firma = If(contexto.Request.Headers("X-Webhook-Signature"), "")
If Not CryptographicOperations.FixedTimeEquals(Encoding.ASCII.GetBytes(esperada), Encoding.ASCII.GetBytes(firma)) Then
contexto.Response.StatusCode = 401
Else
Dim avisoId = contexto.Request.Headers("X-Webhook-Id")
For Each registro In JsonDocument.Parse(cuerpo).RootElement.EnumerateArray()
Console.WriteLine($"{avisoId} {registro.GetProperty("serie")}{registro.GetProperty("numero")}: {registro.GetProperty("estado")}")
Next
contexto.Response.StatusCode = 200
End If
Catch ex As Exception
Console.Error.WriteLine(ex.Message)
Finally
contexto.Response.Close()
End Try
End While
End Sub
End ModuleFull example in a single file
One file that creates the invoice with Idempotency-Key, saves the QR as PNG and checks the status. Create a project with dotnet new console -lang VB, paste the file into Program.vb and run it with VERIFACTI_API_KEY=vf_test_… dotnet run. It uses the current time as the invoice number so you can run it several times.
' Verifactu en Visual Basic con la API de Verifacti: crea una factura, guarda el QR y consulta el estado.
' Uso: dotnet new console -lang VB, pega este archivo en Program.vb y ejecuta
' VERIFACTI_API_KEY=vf_test_... dotnet run
Imports System.IO
Imports System.Net.Http
Imports System.Net.Http.Headers
Imports System.Net.Http.Json
Imports System.Text.Json
Imports System.Threading
Module Program
Private ReadOnly Http As New HttpClient() With {.BaseAddress = New Uri("https://api.verifacti.com"), .Timeout = TimeSpan.FromSeconds(30)}
Function Send(method As HttpMethod, path As String, Optional body As Object = Nothing,
Optional clave As String = Nothing) As (Status As Integer, Body As JsonElement)
Using request As New HttpRequestMessage(method, path)
If body IsNot Nothing Then request.Content = JsonContent.Create(body)
If clave IsNot Nothing Then request.Headers.Add("Idempotency-Key", clave)
Using response = Http.SendAsync(request).Result
Return (CInt(response.StatusCode), response.Content.ReadFromJsonAsync(Of JsonElement)().Result)
End Using
End Using
End Function
Function Main() As Integer
Http.DefaultRequestHeaders.Authorization =
New AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("VERIFACTI_API_KEY"))
Dim madrid = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(DateTime.UtcNow, "Europe/Madrid")
Dim factura = New With {
.serie = "A",
.numero = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(),
.fecha_expedicion = madrid.ToString("dd-MM-yyyy"),
.tipo_factura = "F1",
.descripcion = "Servicios de consultoría",
.nif = "A15022510",
.nombre = "Empresa Cliente SL",
.lineas = {New With {.base_imponible = "200.00", .tipo_impositivo = "21", .cuota_repercutida = "42.00"}},
.importe_total = "242.00"
}
' 1. Crear la factura. La misma Idempotency-Key en cada reintento: nunca se duplica.
Dim clave = Guid.NewGuid().ToString()
Dim alta As (Status As Integer, Body As JsonElement) = (0, Nothing)
For intento = 1 To 5
Try
alta = Send(HttpMethod.Post, "/verifactu/create", factura, clave)
If alta.Status <> 409 AndAlso alta.Status < 500 Then Exit For
Catch ex As AggregateException
End Try
If intento < 5 Then Thread.Sleep(TimeSpan.FromSeconds(2 ^ intento))
Next
If alta.Status <> 200 Then
Console.Error.WriteLine($"Error {alta.Status}: {alta.Body}")
Return 1
End If
Dim uuid = alta.Body.GetProperty("uuid").GetString()
Console.WriteLine($"Factura {factura.serie}{factura.numero} creada. uuid: {uuid}")
' 2. Guardar el QR para la factura impresa o en PDF.
File.WriteAllBytes("qr.png", Convert.FromBase64String(alta.Body.GetProperty("qr").GetString()))
Console.WriteLine("QR guardado en qr.png")
' 3. Consultar el estado. El envío a la AEAT suele tardar uno o dos minutos.
Dim registro As JsonElement
Dim ultimo = 0
For consulta = 1 To 6
Thread.Sleep(TimeSpan.FromSeconds(30))
Dim resultado = Send(HttpMethod.Get, $"/verifactu/status?uuid={uuid}")
registro = resultado.Body
ultimo = resultado.Status
If resultado.Status = 200 AndAlso registro.GetProperty("estado").GetString() <> "Pendiente" Then Exit For
Next
If ultimo <> 200 Then
Console.Error.WriteLine($"Sin respuesta del estado: {ultimo}")
Return 1
End If
Console.WriteLine($"Estado: {registro.GetProperty("estado")}")
Dim codigo As JsonElement
If registro.TryGetProperty("codigo_error", codigo) AndAlso codigo.ValueKind <> JsonValueKind.Null Then
Console.WriteLine($"AEAT {codigo}: {registro.GetProperty("mensaje_error")}")
End If
Return 0
End Function
End ModuleCommon errors
| Code | Cause | Fix |
|---|---|---|
| 401 | Missing or invalid API key | Check the Authorization header and that the key belongs to the NIF. |
| 403 | NIF deactivated | Activate it in the dashboard or with the NIF management API. |
400 vf-verifactu-fecha_expedicion_hoy | fecha_expedicion is not today's date (test environment) | Send today's date as DD-MM-YYYY, Spanish time. |
400 vf-verifactu-importe_total_cuadre | importe_total does not match the sum of the lines | Recalculate base, tax and surcharge of every line. |
400 vf-verifactu-factura_duplicada | An invoice with the same serie, numero and fecha_expedicion already exists | Check your numbering. |
| 409 | Another request with the same Idempotency-Key is still in progress | Wait a few seconds and repeat with the same key. |
| 422 | Idempotency-Key reused with a different body | Use a new key for the corrected request. |
Every code and state, in Verifactu errors.
Your own library or an API?
To comply with Verifactu you can integrate directly with the AEAT: generate the XML (Verifactu XML structure), compute the hash and chaining, send with a certificate and follow the flow control. Or use a REST API like Verifacti's, which takes JSON and needs no certificate.
| What you have to solve | Generate and send the XML yourself | With the Verifactu API |
|---|---|---|
| Format | Build the XML against the AEAT XSD schemas | You send JSON |
| Hash and chaining | Compute the SHA-256 hash of every record and keep the previous one per NIF | Verifacti does it; the hash comes back in the response |
| Certificate | Authenticated call with an electronic certificate, yours or your customer’s | No certificate: Verifacti sends as a colaborador social with each NIF’s representation form |
| Sending | Follow the AEAT flow control (by default one submission per minute unless you collect 1,000 records) and manage queues and retries | Immediate response; Verifacti queues and sends |
| QR | Generate the verification URL and the QR | Included in the response (PNG in Base64) |
| Record keeping | Store records and responses | Query, list and export the XML through the API |
Next step
Read the Verifactu API documentation, copy the invoice examples or follow the quick start guide to move to production. See pricing.
Other Verifactu tutorials
What those who have integrated it say

«La integración con Verifactu fue muy sencilla y el soporte ha sido excelente. Siempre atentos y rápidos para resolver dudas. Muy contento con el servicio.»
«Hemos integrado nuestro software en tiempo récord. La documentación es clara y sencilla, y los ejemplos variados y muy útiles. El equipo de soporte me ha ayudado con todas las dudas.»
“Verifacti’s SaaS platform is intuitive and reliable, and their team’s deep expertise and prompt, crystal-clear answers helped us reach our goals on time. They’re not only highly knowledgeable and professional but also a genuine pleasure to work with.”
“Verifacti made Veri*factu compliance surprisingly straightforward. Their API is clean, well-documented, and their support team responds with real solutions — not generic replies. For any SaaS serving Spanish businesses, Verifacti is the partner you want.”Questions about Verifactu in Visual Basic
Is there an official Verifactu library for Visual Basic?
Do I need a digital certificate to send invoices to Verifactu from Visual Basic?
How do I get the invoice QR?
POST /verifactu/create response, in the qr field: a PNG image in Base64. Decode it and place it on the invoice; you don't need to generate it.Can I test without tax effects?
vf_test_…).How do I retry a submission without duplicating the invoice?
Idempotency-Key header: generate a UUID per invoice and repeat it on every retry. If the first request got through, the API returns the same response and creates no new record.Try the code with the free account
It gives you the test API key the whole tutorial works with.