Crea facturas electrónicas con VeriFactu desde tu aplicación PHP, Laravel o Symfony.
Guía paso a paso con ejemplos reales de cURL, Guzzle y Laravel HTTP Client.
La API REST de InvoCash usa JSON estándar y autenticación JWT, compatible con cualquier proyecto PHP 7.4+. Crea facturas homologadas con VeriFactu desde tu ERP, e-commerce o aplicación a medida sin gestionar la infraestructura fiscal.
Solo necesitas cURL habilitado (disponible por defecto en cualquier servidor PHP) y tus credenciales de InvoCash para empezar a facturar en minutos. También puedes usar Guzzle o el HTTP Client de Laravel si ya forman parte de tu stack.
cURL viene habilitado por defecto. No necesitas instalar ningún paquete para empezar a llamar a la API.
Usa el HTTP Client de Laravel, que ya gestiona reintentos, timeouts y logging sin configuración adicional.
InvoCash gestiona la cadena de hashes, la firma y el envío a la AEAT. Tu código solo crea la factura.
Desde un script puntual hasta miles de facturas diarias. La API aguanta cualquier volumen sin cambios en tu código.
Lo que necesitas para conectar tu proyecto PHP con InvoCash
Desde la autenticación hasta crear y enviar tu primera factura
Llama a POST /api/auth/login con tus credenciales para obtener un JWT. Para integraciones automáticas usa directamente la API Key en el header X-API-Key — sin gestión de tokens.
function getToken(string $email, string $password): string { $ch = curl_init('https://{su-tenant}.invo.cash/api/auth/login'); curl_setopt_array($ch, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_HTTPHEADER => ['Content-Type: application/json'], CURLOPT_POSTFIELDS => json_encode([ 'email' => $email, 'password' => $password, ]), ]); $data = json_decode(curl_exec($ch), true); curl_close($ch); return $data['access_token']; // válido por 20 minutos } // Alternativa recomendada para backends: API Key (no caduca) // Header en cada petición: 'X-API-Key: {tu_api_key}'
POST /api/invoices requiere que calcules tax_base, tax_amount y total antes de enviar — la API no los calcula automáticamente. Fórmulas: tax_base = precio × cantidad · tax_amount = tax_base × (iva / 100) · total_factura = tax_base + tax_amount.
function crearFactura(string $token, int $customerId, string $descripcion, float $precio, int $iva = 21): array { $taxBase = $precio; $taxAmount = round($taxBase * $iva / 100, 2); $payload = [ 'customer_id' => $customerId, 'due' => date('Y-m-d', strtotime('+30 days')), 'verifactu_issuer_territory' => 'MAINLAND', 'simplified' => false, 'lines' => [[ 'description' => $descripcion, 'quantity' => 1, 'unit_price' => $precio, 'tax_base' => $taxBase, 'tax_pctge' => $iva, 'tax_amount' => $taxAmount, 'tax_withholding_pctge' => 0, 'tax_withholding_amount' => 0, 'tax_type' => 'IVA', 'clave_regimen' => '01', 'qualification_operation' => 'S1', 'exempt_operation' => null, 'total' => $taxBase, ]], 'total' => round($taxBase + $taxAmount, 2), ]; $ch = curl_init('https://{su-tenant}.invo.cash/api/invoices'); curl_setopt_array($ch, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_HTTPHEADER => [ 'Content-Type: application/json', "Authorization: Bearer $token", ], CURLOPT_POSTFIELDS => json_encode($payload), ]); $result = json_decode(curl_exec($ch), true); curl_close($ch); return $result['data'][0]; }
use GuzzleHttp\Client; function crearFactura(string $token, int $customerId, string $descripcion, float $precio, int $iva = 21): array { $taxBase = $precio; $taxAmount = round($taxBase * $iva / 100, 2); $client = new Client(); $response = $client->post('https://{su-tenant}.invo.cash/api/invoices', [ 'headers' => [ 'Content-Type' => 'application/json', 'Authorization' => "Bearer $token", ], 'json' => [ 'customer_id' => $customerId, 'due' => date('Y-m-d', strtotime('+30 days')), 'verifactu_issuer_territory' => 'MAINLAND', 'simplified' => false, 'lines' => [[ 'description' => $descripcion, 'quantity' => 1, 'unit_price' => $precio, 'tax_base' => $taxBase, 'tax_pctge' => $iva, 'tax_amount' => $taxAmount, 'tax_withholding_pctge' => 0, 'tax_withholding_amount' => 0, 'tax_type' => 'IVA', 'clave_regimen' => '01', 'qualification_operation' => 'S1', 'exempt_operation' => null, 'total' => $taxBase, ]], 'total' => round($taxBase + $taxAmount, 2), ], ]); return json_decode($response->getBody()->getContents(), true)['data'][0]; }
use Illuminate\Support\Facades\Http; function crearFactura(string $token, int $customerId, string $descripcion, float $precio, int $iva = 21): array { $taxBase = $precio; $taxAmount = round($taxBase * $iva / 100, 2); $response = Http::withToken($token) ->post('https://{su-tenant}.invo.cash/api/invoices', [ 'customer_id' => $customerId, 'due' => now()->addDays(30)->toDateString(), 'verifactu_issuer_territory' => 'MAINLAND', 'simplified' => false, 'lines' => [[ 'description' => $descripcion, 'quantity' => 1, 'unit_price' => $precio, 'tax_base' => $taxBase, 'tax_pctge' => $iva, 'tax_amount' => $taxAmount, 'tax_withholding_pctge' => 0, 'tax_withholding_amount' => 0, 'tax_type' => 'IVA', 'clave_regimen' => '01', 'qualification_operation' => 'S1', 'exempt_operation' => null, 'total' => $taxBase, ]], 'total' => round($taxBase + $taxAmount, 2), ]); $response->throw(); // lanza excepción si la API devuelve error HTTP return $response->json('data.0'); }
Obtén el estado de validación de la factura con la AEAT en tiempo real. El campo verifactu_status puede ser validated, pending o error.
function estadoVerifactu(string $token, int $invoiceId): array { $ch = curl_init("https://{su-tenant}.invo.cash/api/invoice/$invoiceId/verifactu"); curl_setopt_array($ch, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ["Authorization: Bearer $token"], ]); $data = json_decode(curl_exec($ch), true); curl_close($ch); return $data; } // Uso: // $estado = estadoVerifactu($token, 1234); // $estado['verifactu_status'] => 'validated' | 'pending' | 'error'
El PDF se genera automáticamente al crear la factura. Puedes descargarlo o enviarlo directamente al email del cliente con un solo endpoint.
function descargarPdf(string $token, int $id, string $ruta): void { $ch = curl_init("https://{su-tenant}.invo.cash/api/invoice/$id/downloadPdf"); curl_setopt_array($ch, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ["Authorization: Bearer $token"], ]); file_put_contents($ruta, curl_exec($ch)); curl_close($ch); } function enviarEmail(string $token, int $id): bool { $ch = curl_init("https://{su-tenant}.invo.cash/api/invoice/$id/communicate/email"); curl_setopt_array($ch, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_HTTPHEADER => [ 'Content-Type: application/json', "Authorization: Bearer $token", ], CURLOPT_POSTFIELDS => '{}', ]); $r = json_decode(curl_exec($ch), true); curl_close($ch); return ($r['status'] ?? '') === 'success'; }
VeriFactu incluido automáticamente: todas las facturas creadas mediante la API de InvoCash se procesan con el sistema VeriFactu de la AEAT. Cumplimiento de la Ley Antifraude y el RD 1007/2023 sin ningún desarrollo adicional por tu parte.
¿Dudas durante la integración?
Nuestro equipo técnico te da respuesta ágil dentro del horario laboral. No hace falta que seas cliente.
Los endpoints que usarás con más frecuencia en tu integración PHP. La documentación completa está disponible dentro de la plataforma.
| Método | Endpoint | Descripción |
|---|---|---|
| POST | /api/auth/login | Autenticar y obtener token JWT |
| GET | /api/customers | Listar clientes |
| POST | /api/invoices | Crear una o varias facturas |
| GET | /api/invoices | Listar facturas (paginado, con filtros) |
| GET | /api/invoice/{id} | Detalle de una factura |
| PUT | /api/invoice/{id} | Actualizar factura (solo si no está validada) |
| GET | /api/invoice/{id}/verifactu | Estado de validación VeriFactu en la AEAT |
| GET | /api/invoice/{id}/downloadPdf | Descargar el PDF de la factura |
| POST | /api/invoice/{id}/communicate/email | Enviar la factura por email al cliente |
| POST | /api/invoice/{id}/validate | Enviar manualmente a VeriFactu |
Una tienda online en Laravel detecta un pago completado vía webhook de Stripe. Un Job en la cola procesa el pedido, llama a la API de InvoCash para crear la factura con los datos del cliente y las líneas con IVA calculado, la valida con VeriFactu y envía el PDF por email al cliente — todo en menos de 2 segundos y sin intervención manual.
Nuestro equipo técnico te acompaña en todo el proceso. Sin compromiso.