PHP code example of ticketbaiws / ticketbaiws-php

1. Go to this page and download the library: Download ticketbaiws/ticketbaiws-php library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

ticketbaiws / ticketbaiws-php example snippets




use TicketbaiWS\Client;

$tbai = new Client('TU_TOKEN', 'B01000012', ['entorno' => 'test']); // 'test' o 'real'

$r = $tbai->crearFactura([
    'fecha'         => date('d/m/Y'),
    'hora'          => date('H:i:s'),
    'serie'         => 'T2026',
    'numero'        => '000001',
    'simplificada'  => true,
    'nif'           => '',
    'nombre'        => '',
    'rectificativa' => false,
    'retencion'     => 0,
    'lineas'        => [
        ['descripcion' => 'Café', 'cantidad' => 2, 'importe_unitario' => 1.5, 'tipo_iva' => 10, 'tipo_req' => 0],
    ],
    'total_factura' => 3.30,
]);

if ($r->isSuccess()) {
    $identificador = $r->getData('huella_tbai') ?: $r->getData('huella'); // TicketBAI | Verifactu
    $urlCotejo     = $r->getData('url');
    $qrPng         = base64_decode($r->getData('qr'));
} else {
    echo $r->getMessageText();
}

use TicketbaiWS\Exception\TicketbaiWSException;

try {
    $r = $tbai->crearFactura($factura);
    if ($r->isError()) {
        // Error de validación o rechazo de Hacienda: corrige y reenvía (subsanarFactura)
        log_error($r->getMessageText(' | '));
    }
} catch (TicketbaiWSException $e) {
    // Sin respuesta de la API: reintenta más tarde
}

$r = $tbai->crearFactura([
    'fecha' => '21/11/2026', 'hora' => '10:30:00',
    'serie' => 'F2026', 'numero' => '000123',
    'simplificada' => false,
    'nif' => 'B89670855', 'nombre' => 'Cliente S.L.',
    'direccion' => 'Calle Mayor 1', 'cp' => '01001',   // obligatorios en Araba y Gipuzkoa
    'rectificativa' => false, 'retencion' => 0,
    'lineas' => [
        ['descripcion' => 'Servicio', 'cantidad' => 1, 'importe_unitario' => 100, 'tipo_iva' => 21, 'tipo_req' => 0],
    ],
    'total_factura' => 121.00,
    'sincrono' => true,
]);

$r = $tbai->crearFactura([
    // ... mismos datos de cabecera
    'rectificativa'       => true,
    'clave_rectificativa' => 'R1',  // R1-R4, o R5 en simplificadas
    'tipo_rectificativa'  => 'I',   // I: por diferencias, S: sustitutiva
    'rectificadas'        => [['serie' => 'F2026', 'numero' => '000123', 'fecha' => '21/11/2026']],
    'lineas'              => [['cantidad' => -1, 'importe_unitario' => 100, 'tipo_iva' => 21, 'tipo_req' => 0]],
    'total_factura'       => -121.00,
]);

file_put_contents('factura.pdf', base64_decode($tbai->pdfFactura('F2026', '000123')->getData()));
file_put_contents('qr.png', base64_decode($r->getData('qr')));

$modelo = $tbai->modeloDocRepresentante([           // solo personas jurídicas
    'nombre_representante' => 'Ane Etxeberria', 'nif_representante' => '12345678Z',
    'poblacion_representante' => 'Bilbao', 'direccion_representante' => 'Calle Mayor 1',
]);
file_put_contents('representacion.pdf', base64_decode($modelo->getData()));

// ...firmado con certificado reconocido (FNMT, Izenpe...)
$tbai->enviarDocRepresentante('representacion-firmado.pdf');
$tbai->descargarDocRepresentante();
$tbai->revocarDocRepresentante();   // solo antes del primer envío en real

use TicketbaiWS\Resource\Spfe;

$spfe = $tbai->spfe();

// 1. Facturas recibidas nuevas desde la última sincronización
$r = $spfe->recibidasDesde($ultimoId);
foreach ($r->getData() as $recibida) {
    // id, factura, fecha_factura, nif_emisor, nombre_emisor, base, cuota, total, vencimiento, estado...
    $ultimoId = $recibida['id'];
}
if ($r->getMessageText() !== '') {
    // Aviso: falta autorizar la consulta de recibidas (certificado de la empresa o apoderamiento)
}

// 2. Pago o rechazo de una recibida (se le pasa la fila tal cual)
$spfe->pago($recibida, '10/11/2026', $recibida['vencimiento']);
$spfe->rechazo($recibida, Spfe::RECHAZO_COMERCIAL);

// 3. Cobro o impago de una factura que has emitido
$spfe->cobro('A', '2026000245', '10/11/2026');
$spfe->impago('A', '2026000245', '03/12/2026');

// Resultado: PENDING (en cola), OK o ERROR. Con 'sincrono' => true se espera a la AEAT
$spfe->estados(['serie' => 'A']);
$spfe->anularEstado(['estado' => 'cobro', 'serie' => 'A', 'numero' => '2026000245']);

$r = $tbai->lroeGastosSinFactura()->alta([
    'ejercicio' => 2026,
    'gastos' => [
        ['fecha_operacion' => '30/09/2026', 'concepto' => '64201', 'epigrafe' => '165140', 'linea' => 1, 'importe' => 294.00],
    ],
]);

$compras = $tbai->lroeRecibidas()->consultar(['ejercicio' => 2026, 'nif' => 'B01000012']);

use TicketbaiWS\Webhook;

$w = $tbai->crearWebhook('https://tu-web.com/tbaiws-aviso.php', 'un-secret-largo', $soloErrores = false, true, Webhook::EVENTOS);
$codigo = $w->getData('codigo');

$tbai->modificarWebhook($codigo, ['activo' => false]);
$tbai->listarWebhooks(['activo' => true]);

use TicketbaiWS\Webhook;
use TicketbaiWS\Exception\WebhookException;

try {
    $aviso = Webhook::recibir('un-secret-largo');   // lee php://input y las cabeceras
} catch (WebhookException $e) {
    http_response_code(401);
    exit;
}
$aviso['evento'];    // cambio_estado, spfe_envio, spfe_estado o spfe_recibida
$aviso['entorno'];   // 'test' o 'real' (cabecera X-TbaiWs-Environment)
$aviso['datos'];     // cuerpo del aviso decodificado

use TicketbaiWS\Cuenta;
use TicketbaiWS\Diputacion;

$cuenta = new Cuenta('TOKEN_DESARROLLADOR', 'NIF_DE_TU_CUENTA');

$r = $cuenta->crearEmpresa([
    'nombre_social' => 'Mi Cliente S.L.', 'nif' => 'B89670855',
    'direccion' => 'Calle Mayor 1', 'poblacion' => 'Bilbao', 'provincia' => 'Bizkaia', 'cp' => '48001',
    'diputacion' => Diputacion::BIZKAIA,   // ARABA, BIZKAIA, GIPUZKOA o VERIFACTU
]);
// $r->getData() incluye los tokens de pruebas y de producción de la empresa

$cuenta->editarEmpresa('B89670855', ['email' => '[email protected]']);
$cuenta->activarSpfe('B89670855');   // factura electrónica B2B (Ley Crea y Crece)
$cuenta->listarEmpresas();
$cuenta->crearLicencia($plan, $cantidad = 1, $meses = 12, 'anual');
$cuenta->listarLicencias();

$tbai = new Client($token, $nif, [
    'entorno'        => 'test',   // 'test' | 'real' | URL base
    'timeout'        => 60,       // segundos
    'verificar_ssl'  => true,
    'reintentos_429' => 3,        // reintentos con espera creciente (respeta Retry-After)
    'transport'      => null,     // TicketbaiWS\Http\TransportInterface propio
]);

$r = $tbai->peticion('GET', 'nuevo-metodo', ['param' => 'valor']);

$client = new TicketbaiWS\Client($token, $nif, ['entorno' => 'test']); // or 'real'
$res = $client->crearFactura($invoice);  // POST /tbai/
$res->isSuccess(); $res->getData('qr'); $res->getMessageText();
bash
composer