Verifactu API for PHP
Send your invoices to the AEAT (Spanish Tax Agency) with Verifactu from your PHP application with an open source library. You send the invoice data and Ticketbai WS generates the invoicing record, calculates the fingerprint, chains it, submits it to the AEAT and returns the fingerprint, the verification URL and the QR code. You don't need a digital certificate on your server or to implement the AEAT web service.
View on GitHub Packagist Create a test account
The same library works for TicketBAI and Verifactu: the API decides which tax authority to send to based on how the issuing company is registered. Do you have customers in the Basque Country? See the TicketBAI API for PHP. Not using PHP? The Verifactu API is REST and works with any language.
Installation
composer require ticketbaiws/ticketbaiws-phpRequirements: PHP 7.2 or later with the curl and json extensions. It has no other dependencies.
You need a Ticketbai WS account. In the private area, each company has a test token (for https://api-test.ticketbaiws.eus, with no tax validity) and a production token (for https://api.ticketbaiws.eus). Always start in the test environment.
<?php
require 'vendor/autoload.php';
use TicketbaiWS\Client;
$tbai = new Client(
getenv('TBAIWS_TOKEN'), // the company's test or production token
'B89670855', // NIF of the issuing company
['entorno' => 'test'] // 'test' or 'real' (production)
);First invoice
A simplified invoice (a receipt) is the simplest case: it carries no customer data. Line amounts are excluding VAT and total_factura is the total including VAT.
$r = $tbai->crearFactura([
'fecha' => '29/11/2026',
'hora' => '10:30:00',
'serie' => 'T2026',
'numero' => '1024',
'simplificada' => true,
'lineas' => [
['descripcion' => 'Café con leche', 'cantidad' => 2, 'importe_unitario' => 1.3636, 'tipo_iva' => 10, 'tipo_req' => 0],
['descripcion' => 'Pintxo de tortilla', 'cantidad' => 1, 'importe_unitario' => 2.7273, 'tipo_iva' => 10, 'tipo_req' => 0],
],
'total_factura' => 6.0,
]);
if ($r->isSuccess()) {
$identificador = $r->getData('huella');
$urlCotejo = $r->getData('url');
file_put_contents('qr.png', base64_decode($r->getData('qr')));
} else {
echo $r->getMessageText(); // reasons for the error
}API response ($r->toArray()):
{
"result": "PENDING",
"return": {
"huella": "8FB32E1469E1998F9EE8A0358E374203C9858799D22CBC0389EFDAE42F6A311D",
"qr": "iVBORw0KGgo… (PNG en base64)",
"url": "https://www2.agenciatributaria.gob.es/wlpl/TIKE-CONT/ValidarQR?nif=B89670855&numserie=T20261024&fecha=29-11-2026&importe=6.00"
},
"msg": null
}Print the QR code and the "VERI*FACTU" legend on the invoice. The QR code is already valid even if the response is PENDING: the invoice is registered and queued for submission to the AEAT.
You can try this same JSON without an account in the test terminal. More cases (intra-EU, exports, exempt, equivalence surcharge…) are in the API examples: the PHP array is the same as the JSON.
Responses and errors
Every method returns a TicketbaiWS\Response object with the API result:
| Method | Returns |
|---|---|
getResult() | OK, PENDING (accepted and queued for submission) or ERROR |
isSuccess() | true with OK or PENDING |
isOk(), isPending(), isError() | — |
getData('campo') | One field of the result (huella, qr, url…) or everything if you don't pass a field |
getMessageText() | The error or warning messages as a single text, ready to display or store |
getMessages() | The messages as a list |
A rejection from the tax authority is not an exception: it arrives as a response with ERROR and the reasons in the message. The library only throws exceptions when there is no response to process: no connection, rate limit exceeded after the automatic retries, or text that is not UTF-8.
use TicketbaiWS\Exception\TicketbaiWSException;
try {
$r = $tbai->crearFactura($factura);
if ($r->isError()) {
// Validation error or rejection by the tax authority: fix the data and resend
guardarError($factura['serie'], $factura['numero'], $r->getMessageText(' | '));
}
} catch (TicketbaiWSException $e) {
// No response from the API: keep the invoice queued and retry later
}If you exceed the rate limit (HTTP 429), the library retries automatically with increasing delays and honors the Retry-After header.
Tax authority status
The API responds immediately and sends the invoice to the AEAT in the background, retrying if it doesn't respond. To get the final result:
- Webhook (recommended): we notify you when the invoice changes to OK or ERROR. See Webhooks.
- Query:
$tbai->consultarFactura($serie, $numero)returns the status ingetData('status'). - Synchronous submission: add
'sincrono' => trueto the invoice to wait for the tax authority's response in the same call.
$estado = $tbai->consultarFactura('T2026', '1024');
switch ($estado->getData('status')) {
case 'OK': /* accepted */ break;
case 'PENDING': /* queued: check again later */ break;
case 'ERROR': echo $estado->getMessageText(); break;
}Verifactu specifics
PENDINGresponse. Withoutsincrono, the API registers the invoice, calculates the fingerprint and chains it immediately, and submits it to the AEAT in the background. For your application it is a success (isSuccess()).- Identifier: the field is
huella(in TicketBAI,huella_tbai). If your application supports both systems, use$r->getData('huella_tbai') ?: $r->getData('huella'). - Individual customers: the AEAT checks that the name and NIF match its records. Validate them before issuing with
validarNif()(production only). - EU customers: check the EU VAT number with
validarNifVies($nif, $pais).
$v = $tbai->validarNif('12345678Z', 'MARTINEZ RODRIGUEZ JUAN');
if ($v->getData('resultado') !== 'IDENTIFICADO') {
// Ask the customer to check their name and NIF before issuing the invoice
}Full invoice
Invoice with the customer's data, waiting for the response from the AEAT with sincrono:
$r = $tbai->crearFactura([
'fecha' => '29/11/2026',
'hora' => '10:30:00',
'fecha_operacion' => '28/11/2026',
'nif' => 'B12345674',
'nombre' => 'Cliente Ejemplo S.L.',
'direccion' => 'Calle Mayor 1',
'cp' => '01001',
'pais_cliente' => 'ES',
'serie' => 'A2026',
'numero' => '000153',
'simplificada' => false,
'rectificativa' => false,
'tipo_operacion' => 'servicios',
'retencion' => 0,
'lineas' => [
['descripcion' => 'Mantenimiento web — octubre', 'cantidad' => 1, 'importe_unitario' => 120, 'tipo_iva' => 21, 'tipo_req' => 0],
['descripcion' => 'Horas de soporte', 'cantidad' => 3, 'importe_unitario' => 45, 'tipo_iva' => 21, 'tipo_req' => 0],
],
'total_factura' => 308.55,
'sincrono' => true,
]);{
"result": "OK",
"return": {
"huella": "9DBD2CADA92791C47A8D157D19F58442F6FB9CE789C8325571461C8E8092B074",
"qr": "iVBORw0KGgo… (PNG en base64)",
"url": "https://www2.agenciatributaria.gob.es/wlpl/TIKE-CONT/ValidarQR?nif=B89670855&numserie=A2026000153&fecha=29-11-2026&importe=308.55"
},
"msg": null
}Corrective invoices, resubmission and cancellation
Corrective invoice
A corrective invoice by differences carries negative amounts and lists the invoices it corrects. If the original invoice was not issued with Ticketbai WS, add its amounts (base, cuota, recargo) to each element of rectificadas.
$r = $tbai->crearFactura([
// ...same customer data as the original invoice
'serie' => 'R2026',
'numero' => '000012',
'rectificativa' => true,
'clave_rectificativa' => 'R1', // R1 to R4; R5 for simplified invoices
'tipo_rectificativa' => 'I', // I: by differences; S: by substitution
'rectificadas' => [
['serie' => 'A2026', 'numero' => '000153', 'fecha' => '03/11/2026'],
],
'lineas' => [
['descripcion' => 'Refund of support hours', 'cantidad' => -1, 'importe_unitario' => 45, 'tipo_iva' => 21, 'tipo_req' => 0],
],
'total_factura' => -54.45,
]);Resubmission
If the tax authority returns errors or warnings, resend the invoice with the corrected data. The series, number and total must be those of the original.
$r = $tbai->subsanarFactura($facturaCorregida); // adds 'zuzendu' => trueCancellation
Cancel an invoice sent by mistake. The number cannot be reused.
$r = $tbai->anularFactura('A2026', '000153');
// With several invoices with the same series and number, pass the date: anularFactura('A2026', '000153', '03/11/2026')PDF, XML and QR
// Invoice PDF (base64)
file_put_contents('factura.pdf', base64_decode($tbai->pdfFactura('A2026', '000153')->getData()));
// XML sent and tax authority response
$xml = $tbai->xmlFactura('A2026', '000153');
$xml->getData('xml_request');
$xml->getData('xml_response');
// FacturaE 3.2 (base64), with the DIR3 codes if it goes to FACe. Production only.
$fe = $tbai->facturae('A2026', '000153', [
'cod_organo_gestor' => 'CODIGO_DIR3_ORGANO',
'cod_unidad_tramitadora' => 'CODIGO_DIR3_UNIDAD',
'cod_oficina_contable' => 'CODIGO_DIR3_OFICINA',
]);The QR code of each invoice comes in the response of crearFactura() and consultarFactura() as a base64 PNG, together with the verification URL it contains.
Customers and products
If the company uses the invoicing tool in the private area, you can search its customers and products and issue the invoice with their data. The fields have the same names as in crearFactura(). They don't depend on the environment: the test token reads and modifies the same data as the production token.
use TicketbaiWS\Resource\Productos;
$cliente = $tbai->clientes()->buscar('Uribe')->getData()[0];
$producto = $tbai->productos()->buscar('maintenance')->getData()[0];
$r = $tbai->crearFactura([
// ...fecha, hora, serie, numero...
'nif' => $cliente['nif'],
'nombre' => $cliente['nombre'],
'direccion' => $cliente['direccion'],
'cp' => $cliente['cp'],
'lineas' => [Productos::linea($producto, 3)], // 3 units
// ...
]);
// Create a new customer
$tbai->clientes()->crear(['nombre' => 'Nuevo Cliente S.L.', 'nif' => 'B89670855', 'pais' => 'ES']);B2B e-invoicing (SPFE)
The Ley Crea y Crece (Royal Decree 238/2026 and Order HAC/1028/2026) requires invoices between companies and professionals to be issued in electronic format and their status to be reported: payment, collection, rejection or non-payment. Ticketbai WS automatically sends to the AEAT's SPFE (Spanish public B2B e-invoicing platform), in UBL, the full invoices to Spanish customers with a NIF that you issue with crearFactura(), and downloads every hour the ones you receive from your suppliers. You don't have to generate the UBL or connect to the AEAT.
It is enabled per company in the private area ("Factura electrónica B2B") or via API with $cuenta->activarSpfe($nif). Once enabled, invoices are sent from that day on. More about B2B e-invoicing.
use TicketbaiWS\Resource\Spfe;
$spfe = $tbai->spfe();
// New received invoices since the last sync
$r = $spfe->recibidasDesde($ultimoId);
foreach ($r->getData() as $recibida) {
// factura, fecha_factura, nif_emisor, nombre_emisor, base, cuota, total, vencimiento, estado...
$ultimoId = $recibida['id'];
}
// Payment or rejection of a received invoice: pass the row as is
$spfe->pago($recibida, '10/11/2026', $recibida['vencimiento']);
$spfe->rechazo($recibida, Spfe::RECHAZO_COMERCIAL);
// Collection or non-payment of an invoice you issued
$spfe->cobro('A2026', '000153', '10/11/2026');
$spfe->impago('A2026', '000153', '03/12/2026');
// Result of each status: PENDING (queued), OK or ERROR
$spfe->estados(['serie' => 'A2026']);Statuses are sent to the AEAT through a queue; add 'sincrono' => true to the options to wait for its response. If the AEAT doesn't allow querying received invoices (the company's certificate or power of attorney is missing), getMessageText() tells you.
Authorization with the tax authority
To send in production with the Ticketbai WS certificate, each company signs a representation document once. You can manage it from your application:
// 1. PDF template (for legal entities, with the legal representative's details)
$modelo = $tbai->modeloDocRepresentante([
'nombre_representante' => 'Ane Etxeberria Goikoetxea',
'nif_representante' => '12345678Z',
'poblacion_representante' => 'Bilbao',
'direccion_representante' => 'Calle Mayor 1',
]);
file_put_contents('representacion.pdf', base64_decode($modelo->getData()));
// 2. Once signed with a qualified certificate (FNMT, Izenpe...), upload it
$tbai->enviarDocRepresentante('representacion-firmada.pdf');It can also be signed and uploaded from the private area. If the company prefers to use its own certificate, it uploads it there and doesn't need the document.
Webhooks
Get notified every time an invoice's status changes (cambio_estado) and, if you use B2B e-invoicing, of the submission to the SPFE (spfe_envio), of each payment or collection reported (spfe_estado) and of each received invoice (spfe_recibida). Test and production webhooks are independent: create one in each environment.
$w = $tbai->crearWebhook('https://your-site.com/tbaiws-aviso.php', 'a-long-random-secret', false, true, \TicketbaiWS\Webhook::EVENTOS);
$codigo = $w->getData('codigo');
// Error notifications only
$tbai->modificarWebhook($codigo, ['solo_errores' => true]);In the receiver, the library verifies the HMAC-SHA256 signature (X-Tbaiws-Hmac-Sha256 header) before you process anything:
<?php // tbaiws-aviso.php
require 'vendor/autoload.php';
use TicketbaiWS\Webhook;
use TicketbaiWS\Exception\WebhookException;
try {
$aviso = Webhook::recibir('a-long-random-secret');
} catch (WebhookException $e) {
http_response_code(401); // invalid signature
exit;
}
$aviso['evento']; // cambio_estado, spfe_envio, spfe_estado or spfe_recibida
$aviso['entorno']; // 'test' or 'real'
$aviso['datos']; // notification payload
http_response_code(200);With Laravel or Symfony, pass the request body and headers: Webhook::recibir($secret, $request->getContent(), $request->headers->all()).
Integrators: companies via API
If your software invoices for many companies (ERP, POS, accounting firms), you can register them and manage their licenses from your code with TicketbaiWS\Cuenta. Use the developer token and your account NIF from the private area, not those of a company. These methods only exist in production.
use TicketbaiWS\Cuenta;
use TicketbaiWS\Diputacion;
$cuenta = new Cuenta(getenv('TBAIWS_TOKEN_DESARROLLADOR'), getenv('TBAIWS_NIF_CUENTA'));
$r = $cuenta->crearEmpresa([
'nombre_social' => 'Mi Cliente S.L.',
'nif' => 'B89670855',
'direccion' => 'Calle Mayor 1',
'poblacion' => 'Madrid',
'provincia' => 'Madrid',
'cp' => '28001',
'diputacion' => Diputacion::VERIFACTU, // ARABA, BIZKAIA, GIPUZKOA or VERIFACTU
]);
// $r->getData() includes the new company's test and production tokens
$cuenta->editarEmpresa('B89670855', ['email' => 'facturas@micliente.com']);
$cuenta->listarEmpresas();Integrating many customers? Contact us for partner terms.
Method reference
Client method | Endpoint |
|---|---|
crearFactura(array $factura) | POST /tbai/ |
subsanarFactura(array $factura) | POST /tbai/ with zuzendu |
consultarFactura($serie, $numero) | GET /tbai/ |
anularFactura($serie, $numero, $fecha = null) | DELETE /tbai/ |
listarFacturas(array $filtros) | GET /tbai-list/ |
completarFactura(array $datos) | POST /tbai-completar/ |
pdfFactura(), xmlFactura(), facturae() | GET /tbai-pdf/, /tbai-xml/, /facturae/ (FacturaE production only) |
reenviarFactura($serie, $numero) | PUT /reset-tbai/ |
estado(), estaOperativo() | GET /status/ |
validarNif(), validarNifVies() | POST /validar-nif/, /validar-nif-vies/ |
modeloDocRepresentante(), enviarDocRepresentante(), descargarDocRepresentante(), revocarDocRepresentante() | /doc-representante/ |
lroeRecibidas(), lroeGastosSinFactura(), lroeCriterioCajaCobros(), lroeCriterioCajaPagos(), epigrafes() | Batuz LROE (Bizkaia only) |
clientes()->buscar(), porNif(), obtener(), crear(), modificar() | /clientes/ (invoicing tool) |
productos()->buscar(), obtener(), Productos::linea() | GET /productos/ |
spfe()->pago(), rechazo(), cobro(), impago(), comunicarEstado(), anularEstado(), estados() | /spfe-estados/ (B2B e-invoicing) |
spfe()->recibidas(), recibidasDesde() | GET /spfe-recibidas/ |
crearWebhook(), modificarWebhook(), listarWebhooks() | /webhooks/ |
peticion($metodo, $ruta, array $datos) | Any other API method |
Constructor options: entorno (test, real or a URL), timeout (60 s), verificar_ssl (true), reintentos_429 (3) and transport (your own HTTP client, for example for tests). All the fields of each method are in the API documentation and in the OpenAPI specification.
Single-file class
Your project doesn't use Composer, or you already use the class_ticketbaiwsclient class? It is still included in the package, up to date, in legacy/class_ticketbaiwsclient.php. A single require is enough:
require 'class_ticketbaiwsclient.php';
$tbai = new class_ticketbaiwsclient(class_ticketbaiwsclient::URL_PRUEBAS, $token, 'B89670855');
$return = $tbai->nuevo_tbai($factura);
if ($tbai->get_last_result() === 'ERROR') {
echo is_array($return) ? implode("\n", $return) : $return;
}With Composer, the old class is loaded automatically alongside the new one, so you can migrate gradually. The equivalence table is in the README.
Frequently asked questions
Why is the response PENDING?
With Verifactu the API accepts the invoice, calculates the fingerprint and queues it for submission to the AEAT. You can already print the QR code. The final result reaches you by webhook or with consultarFactura(); if you want to wait for the AEAT in the same call, add sincrono: true.
Does the same code work for TicketBAI?
Yes. If you have customers in Araba, Bizkaia or Gipuzkoa, the API sends their invoices to the corresponding provincial tax authority based on the issuer's NIF, with no changes to your code.
Do I need a digital certificate on my server?
No. Ticketbai WS signs the invoices with its own certificate (with your authorization to act on your behalf) or with yours if you upload it to the private area. Your server only makes HTTPS requests.
Which PHP versions does the library support?
PHP 7.2 to 8.5. It only needs the curl and json extensions, with no other dependencies.
Does it work with Laravel, Symfony, WordPress or PrestaShop?
Yes. It is a dependency-free PHP library installed with Composer. If your project doesn't use Composer, you can include the single file legacy/class_ticketbaiwsclient.php.
Can I use the library in commercial software?
Yes. It is MIT licensed: you can use, modify and distribute it in proprietary projects.
