Araba · Bizkaia · GipuzkoaPHP 7.2 – 8.5ComposerMIT

TicketBAI API for PHP

Issue TicketBAI invoices in Araba, Bizkaia (Batuz) and Gipuzkoa from your PHP application with an open source library. You send the invoice data and Ticketbai WS generates the XML, signs it, chains it, sends it to the provincial tax authority (Hacienda Foral) and returns the TBAI identifier, the verification URL and the QR code. You don't need a digital certificate on your server or to know the TicketBAI XSD.

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. Issuing invoices in the rest of Spain? See the Verifactu API for PHP.

Installation

composer require ticketbaiws/ticketbaiws-php

Requirements: 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_tbai');
    $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()) for a company in Gipuzkoa:

{
    "result": "OK",
    "return": {
        "huella_tbai": "TBAI-B89670855-291126-j7MuFGnhmY+e6-062",
        "qr": "iVBORw0KGgo… (PNG en base64)",
        "url": "https://tbai.egoitza.gipuzkoa.eus/qr/?id=TBAI-B89670855-291126-j7MuFGnhmY%2Be6-062&s=T2026&nf=1024&i=6&cr=003"
    },
    "msg": null
}

Print the QR code and the TBAI identifier on the invoice. It is mandatory. Also store the URL and the identifier in your database so you can reprint it.

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:

MethodReturns
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_tbai, 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 provincial tax authority 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 in getData('status').
  • Synchronous submission: add 'sincrono' => true to 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;
}

The three territories

The code is the same for Araba, Bizkaia and Gipuzkoa. The API chooses the tax authority from the NIF of the issuing company and applies the differences of each one:

ArabaBizkaia (Batuz)Gipuzkoa
Customer address and postal codeRequiredRecommendedRequired
Submission deadline24 hoursUntil the 25th of the month after the quarter (January 31 for the fourth quarter)7 days
Authorization for Ticketbai WSDevice certificate registrationRepresentation documentRepresentation document
Purchase and expense books—LROE (lroeRecibidas(), lroeGastosSinFactura()…)—

In Bizkaia, self-employed individuals (form 140) can specify the IAE activity code on each invoice (epigrafe) or on each line. The catalog of activity codes is available in $tbai->epigrafes().

Full invoice

Invoice with the customer's data, waiting for the response from the tax authority 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_tbai": "TBAI-B89670855-291126-nb0sraknkcR6j-001",
        "qr": "iVBORw0KGgo… (PNG en base64)",
        "url": "https://tbai.egoitza.gipuzkoa.eus/qr/?id=TBAI-B89670855-291126-nb0sraknkcR6j-001&s=A2026&nf=000153&i=308.55&cr=175"
    },
    "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 (zuzendu)

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. In Bizkaia it applies to invoices rejected by Batuz and keeps the fingerprint and the QR code; to change an invoice that has already been accepted, issue a corrective invoice.

$r = $tbai->subsanarFactura($facturaCorregida);   // adds 'zuzendu' => true

Cancellation

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.

Batuz LROE (Bizkaia)

Issued invoices go to the LROE automatically. For the other books, each one has alta(), modificar(), consultar() and anular():

BookMethod
Received invoices (purchases)$tbai->lroeRecibidas()
Expenses without invoice (form 140, section 2.2)$tbai->lroeGastosSinFactura()
Cash accounting: collections$tbai->lroeCriterioCajaCobros()
Cash accounting: payments$tbai->lroeCriterioCajaPagos()
// Self-employed social security fee and bank fee for September
$r = $tbai->lroeGastosSinFactura()->alta([
    'ejercicio' => 2026,
    'gastos'    => [
        ['fecha_operacion' => '30/09/2026', 'concepto' => '64201', 'epigrafe' => '165140', 'linea' => 1, 'importe' => 294.00],
        ['fecha_operacion' => '30/09/2026', 'concepto' => '626',   'epigrafe' => '165140', 'linea' => 1, 'importe' => 12.50],
    ],
]);

// Purchases from a supplier in the fiscal year
$compras = $tbai->lroeRecibidas()->consultar(['ejercicio' => 2026, 'nif' => 'B01000012']);

Authorization with the tax authority

To send in production with the Ticketbai WS certificate, each company authorizes us once. In Bizkaia and Gipuzkoa a representation document is signed, which you can manage from your application. In Araba the device certificate is registered on the Provincial Council's (Diputación Foral) website (registration guide).

// 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'     => 'Donostia',
    'provincia'     => 'Gipuzkoa',
    'cp'            => '20001',
    'diputacion'    => Diputacion::GIPUZKOA,   // 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 methodEndpoint
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

Does the same code work for Araba, Bizkaia and Gipuzkoa?

Yes. The API knows which provincial tax authority (Hacienda Foral) to send to from the NIF of the issuing company. Only a few requirements change, such as the customer's address and postal code, which are required in Araba and Gipuzkoa.

What if I get customers in the rest of Spain (Verifactu) later on?

The code is the same: the company is registered as Verifactu and the library sends the invoices to the AEAT with no changes to your application.

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.

Create a test account Quick start guide