PHP code example of b2brouter / b2brouter-php
1. Go to this page and download the library: Download b2brouter/b2brouter-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/ */
b2brouter / b2brouter-php example snippets
2BRouter\B2BRouterClient;
// Initialize the client
$client = new B2BRouterClient('your-api-key-here');
$accountId = 'your-account-id';
// Create an invoice with proper tax structure
$invoice = $client->invoices->create($accountId, [
'invoice' => [
'number' => 'INV-2025-001',
'date' => '2025-01-15',
'due_date' => '2025-02-15',
'currency' => 'EUR',
'contact' => [
'name' => 'Acme Corporation',
'tin_value' => 'ESB12345678',
'country' => 'ES',
'email' => '[email protected] ',
],
'invoice_lines_attributes' => [
[
'description' => 'Professional Services',
'quantity' => 10,
'price' => 100.00,
'taxes_attributes' => [
[
'name' => 'IVA',
'category' => 'S',
'percent' => 21.0,
]
]
]
]
]
]);
echo "Invoice created: {$invoice['id']}\n";
echo "Total: €{$invoice['total']}\n";
$client = new B2BRouterClient('your-api-key', [
// 'api_base' => 'https://api.b2brouter.net', // Production URL
// 'api_base' => 'https://api-staging.b2brouter.net', // Staging URL (default)
'api_version' => '2026-04-20', // API version
'timeout' => 80, // Request timeout in seconds
'max_retries' => 3, // Maximum retry attempts
]);
$client = new B2BRouterClient('your-api-key', [
'api_version' => '2026-03-02', // Use older API version
]);
$client = new B2BRouterClient('your-api-key', [
'app_info' => [
'name' => 'B2BRouter-WooCommerce', // nal
],
]);
$invoice = $client->invoices->create($accountId, [
'invoice' => [
'number' => 'INV-2025-001',
'date' => '2025-01-15',
'due_date' => '2025-02-15',
'currency' => 'EUR',
'contact' => [
'name' => 'Customer Name',
'tin_value' => 'ESB12345678',
'country' => 'ES',
'email' => '[email protected] ',
],
'invoice_lines_attributes' => [
[
'description' => 'Service or Product',
'quantity' => 1,
'price' => 1000.00,
'taxes_attributes' => [
[
'name' => 'IVA',
'category' => 'S', // Standard rate
'percent' => 21.0,
]
]
]
]
],
'send_after_import' => false // Set to true to send immediately
]);
$invoice = $client->invoices->retrieve($invoiceId);
echo "Invoice {$invoice['number']}: €{$invoice['total']}\n";
$invoice = $client->invoices->update($invoiceId, [
'invoice' => [
'extra_info' => 'Payment terms: 30 days net'
]
]);
$result = $client->invoices->delete($invoiceId);
$invoices = $client->invoices->all($accountId, [
'limit' => 25,
'offset' => 0,
'date_from' => '2025-01-01',
'date_to' => '2025-12-31',
]);
foreach ($invoices as $invoice) {
echo "Invoice {$invoice['number']}: €{$invoice['total']}\n";
}
// Download invoice as PDF
$pdfData = $client->invoices->downloadPdf($invoiceId);
file_put_contents('invoice.pdf', $pdfData);
// Download with custom parameters
$pdfData = $client->invoices->downloadPdf($invoiceId, [
'disposition' => 'attachment',
'filename' => 'invoice-2025-001.pdf'
]);
// Download Spanish Facturae 3.2.2 XML format
$facturaeData = $client->invoices->downloadAs($invoiceId, 'xml.facturae.3.2.2');
file_put_contents('invoice-facturae.xml', $facturaeData);
// Download UBL BIS3 format
$ublData = $client->invoices->downloadAs($invoiceId, 'xml.ubl.invoice.bis3');
file_put_contents('invoice-ubl.xml', $ublData);
$invoice = $client->invoices->import($accountId, [
'invoice' => [
'number' => 'EXT-2025-001',
'date' => '2025-01-15',
'currency' => 'EUR',
'contact' => [
'name' => 'External Customer',
'tin_value' => 'ESB12345678',
'country' => 'ES',
],
'invoice_lines_attributes' => [
[
'description' => 'Imported Service',
'quantity' => 1,
'price' => 500.00,
'taxes_attributes' => [
['name' => 'IVA', 'category' => 'S', 'percent' => 21.0]
]
]
]
],
'send_after_import' => true // Optionally send immediately
]);
// Validate an invoice
$validation = $client->invoices->validate($invoiceId);
// Send an invoice to customer and generate tax reports
$result = $client->invoices->send($invoiceId);
// Mark invoice state (new, sent, paid, etc.)
$invoice = $client->invoices->markAs($invoiceId, [
'state' => 'sent'
]);
// Acknowledge a received invoice
$result = $client->invoices->acknowledge($invoiceId, [
'ack' => true
]);
$accounts = $client->accounts->all(['limit' => 25]);
foreach ($accounts as $account) {
echo "Account {$account['name']}: {$account['tin_value']}\n";
}
$account = $client->accounts->retrieve($accountId);
echo "Account: {$account['name']}\n";
$account = $client->accounts->create([
'account' => [
'name' => 'New Company S.L.',
'tin_value' => 'ESB12345678',
'email' => '[email protected] ',
'phone' => '+34600000000',
'address' => 'Calle Gran Vía 1',
'city' => 'Madrid',
'postalcode' => '28001',
'province' => 'Madrid',
'country' => 'es',
]
]);
// Update an account
$account = $client->accounts->update($accountId, [
'account' => ['name' => 'Updated Name']
]);
// Delete (archive) an account
$result = $client->accounts->delete($accountId);
// Unarchive an account
$account = $client->accounts->unarchive($accountId);
// Upload a logo (raw binary data)
$logoData = file_get_contents('/path/to/logo.png');
$account = $client->accounts->uploadLogo($accountId, $logoData);
// Delete a logo
$account = $client->accounts->deleteLogo($accountId);
$contacts = $client->contacts->all($accountId, [
'limit' => 25,
'is_client' => true,
]);
foreach ($contacts as $contact) {
echo "Contact {$contact['name']}: {$contact['tin_value']}\n";
}
$contact = $client->contacts->create($accountId, [
'contact' => [
'name' => 'Customer Company',
'email' => '[email protected] ',
'tin_value' => 'ESB87654321',
'country' => 'ES',
'address' => 'Calle Mayor 10',
'city' => 'Barcelona',
'postalcode' => '08001',
'province' => 'Barcelona',
]
]);
// Retrieve a contact
$contact = $client->contacts->retrieve($contactId);
// Update a contact
$contact = $client->contacts->update($contactId, [
'contact' => ['name' => 'Updated Customer']
]);
// Delete a contact
$result = $client->contacts->delete($contactId);
// Create Verifactu settings
$settings = $client->taxReportSettings->create($accountId, [
'tax_report_setting' => [
'code' => 'VeriFactu',
'start_date' => '2025-01-01',
'auto_generate' => true,
'auto_send' => true,
'reason_vat_exempt' => 'E1',
'special_regime_key' => '01',
]
]);
// Retrieve settings
$settings = $client->taxReportSettings->retrieve($accountId, 'VeriFactu');
// Update settings
$settings = $client->taxReportSettings->update($accountId, 'VeriFactu', [
'tax_report_setting' => [
'auto_send' => false // Disable automatic submission
]
]);
// List all settings
$allSettings = $client->taxReportSettings->all($accountId);
// Delete settings
$client->taxReportSettings->delete($accountId, 'VeriFactu');
// Create a Verifactu tax report
$taxReport = $client->taxReports->create($accountId, [
'tax_report' => [
'type' => 'Verifactu',
'invoice_date' => '2025-01-15',
'invoice_number' => '2025-001',
'description' => 'Professional services',
'customer_party_tax_id' => 'B12345678',
'customer_party_country' => 'es',
'customer_party_name' => 'Cliente S.L.',
'tax_inclusive_amount' => 121.0,
'tax_amount' => 21.0,
'invoice_type_code' => 'F1',
'currency' => 'EUR',
'tax_breakdowns' => [
[
'name' => 'IVA',
'category' => 'S',
'non_exemption_code' => 'S1',
'percent' => 21.0,
'taxable_base' => 100.0,
'tax_amount' => 21.0,
'special_regime_key' => '01'
]
]
]
]);
// Get tax report ID from invoice response
$taxReportId = $invoice['tax_report_ids'][0];
// Retrieve the tax report with QR code
$taxReport = $client->taxReports->retrieve($taxReportId);
echo "Tax Report ID: {$taxReport['id']}\n";
echo "State: {$taxReport['state']}\n";
// Save QR code (base64 encoded PNG)
if (!empty($taxReport['qr'])) {
file_put_contents('qr_code.png', base64_decode($taxReport['qr']));
}
$taxReports = $client->taxReports->all($accountId, [
'limit' => 25,
'offset' => 0,
'invoice_id' => $invoiceId, // Filter by invoice
'sent_at_from' => '2025-01-01', // Filter by sent date
]);
foreach ($taxReports as $report) {
echo "Tax Report: {$report['label']} - {$report['state']}\n";
}
$xml = $client->taxReports->download($taxReportId);
file_put_contents("tax_report_{$taxReportId}.xml", $xml);
$correctedReport = $client->taxReports->update($taxReportId, [
'tax_report' => [
'description' => 'CORRECTED: Updated description',
'tax_inclusive_amount' => 133.1,
'tax_amount' => 23.1,
'tax_breakdowns' => [
[
'name' => 'IVA',
'category' => 'S',
'non_exemption_code' => 'S1',
'percent' => 21.0,
'taxable_base' => 110.0,
'tax_amount' => 23.1,
'special_regime_key' => '01'
]
]
]
]);
$annullation = $client->taxReports->delete($taxReportId);
echo "Annullation ID: {$annullation['id']}\n";
echo "State: {$annullation['state']}\n";
2BRouter\B2BRouterClient;
$client = new B2BRouterClient($_ENV['B2B_API_KEY']);
$accountId = $_ENV['B2B_ACCOUNT_ID'];
// Create and send a Spanish invoice
$invoice = $client->invoices->create($accountId, [
'invoice' => [
'number' => 'INV-ES-2025-001',
'date' => date('Y-m-d'),
'due_date' => date('Y-m-d', strtotime('+30 days')),
'currency' => 'EUR',
'language' => 'es',
'contact' => [
'name' => 'Cliente Ejemplo SA',
'tin_value' => 'ESB12345678',
'country' => 'ES',
'address' => 'Calle Gran Vía, 123',
'city' => 'Madrid',
'postalcode' => '28013',
'email' => '[email protected] ',
],
'invoice_lines_attributes' => [
[
'description' => 'Servicios de consultoría',
'quantity' => 10,
'price' => 150.00,
'taxes_attributes' => [
[
'name' => 'IVA',
'category' => 'S', // Standard rate (21%)
'percent' => 21.0,
]
]
]
],
],
'send_after_import' => true // Send immediately and generate tax report
]);
echo "Invoice created: {$invoice['id']}\n";
echo "State: {$invoice['state']}\n";
// Get the tax report
if (!empty($invoice['tax_report_ids'])) {
$taxReportId = $invoice['tax_report_ids'][0];
$taxReport = $client->taxReports->retrieve($taxReportId);
echo "Tax Report ID: {$taxReport['id']}\n";
echo "Tax Report State: {$taxReport['state']}\n";
echo "QR Code: " . (!empty($taxReport['qr']) ? 'Generated' : 'Pending') . "\n";
echo "Verification URL: {$taxReport['identifier']}\n";
}
$invoices = $client->invoices->all($accountId, [
'limit' => 25,
'offset' => 0,
]);
// Iterate through current page
foreach ($invoices as $invoice) {
echo "Invoice: {$invoice['number']}\n";
}
// Check pagination info
echo "Total invoices: {$invoices->getTotal()}\n";
echo "Current count: {$invoices->count()}\n";
echo "Has more: " . ($invoices->hasMore() ? 'yes' : 'no') . "\n";
$offset = 0;
$limit = 100;
$allInvoices = [];
do {
$page = $client->invoices->all($accountId, [
'limit' => $limit,
'offset' => $offset,
]);
foreach ($page as $invoice) {
$allInvoices[] = $invoice;
}
$offset += $limit;
} while ($page->hasMore());
echo "Fetched " . count($allInvoices) . " total invoices\n";
use B2BRouter\Exception\ApiErrorException;
use B2BRouter\Exception\AuthenticationException;
use B2BRouter\Exception\PermissionException;
use B2BRouter\Exception\ResourceNotFoundException;
use B2BRouter\Exception\InvalidRequestException;
use B2BRouter\Exception\ApiConnectionException;
try {
$invoice = $client->invoices->create($accountId, [
'invoice' => [ /* ... */ ]
]);
} catch (AuthenticationException $e) {
// Invalid API key (401)
echo "Authentication failed: {$e->getMessage()}\n";
exit(1);
} catch (PermissionException $e) {
// Insufficient permissions (403)
echo "Permission denied: {$e->getMessage()}\n";
exit(1);
} catch (ResourceNotFoundException $e) {
// Resource not found (404)
echo "Not found: {$e->getMessage()}\n";
exit(1);
} catch (InvalidRequestException $e) {
// Invalid parameters (400, 422)
echo "Invalid request: {$e->getMessage()}\n";
echo "HTTP Status: {$e->getHttpStatus()}\n";
// Get detailed error information
$errorBody = $e->getJsonBody();
if ($errorBody) {
echo "Error details: " . json_encode($errorBody, JSON_PRETTY_PRINT) . "\n";
}
exit(1);
} catch (ApiConnectionException $e) {
// Network/connection errors
echo "Connection error: {$e->getMessage()}\n";
exit(1);
} catch (ApiErrorException $e) {
// All other API errors (500, etc.)
echo "API error: {$e->getMessage()}\n";
echo "HTTP Status: {$e->getHttpStatus()}\n";
echo "Request ID: {$e->getRequestId()}\n";
exit(1);
}
try {
// API call
} catch (ApiErrorException $e) {
error_log("API Error - Request ID: {$e->getRequestId()}, Message: {$e->getMessage()}");
}
$client = new B2BRouterClient('api-key', [
'api_base' => 'https://api.b2brouter.net', // API endpoint
'api_version' => '2026-04-20', // API version
'timeout' => 80, // Request timeout (seconds)
'max_retries' => 3, // Retry attempts on connection failure
'http_client' => $customClient, // Custom HTTP client (optional)
'app_info' => [ // Identify the integrating app in User-Agent (optional)
'name' => 'My-App', // bash
composer bash
# Invoice examples
php examples/create_simple_invoice.php
php examples/download_invoice_documents.php
php examples/list_invoices.php
php examples/invoices.php
# Tax report examples (VeriFactu, TicketBAI)
php examples/tax_reports.php
php examples/verifactu_tax_report.php
php examples/ticketbai_tax_report.php
# See all available examples
ls examples/
B2BRouter-PHP/1.3.0 (PHP/8.2.10; curl/8.5.0) B2BRouter-WooCommerce/1.0.3 (https://shop.example.com)
bash
# Invoice examples
php examples/create_simple_invoice.php
php examples/download_invoice_documents.php
# Tax report examples
php examples/tax_reports.php
php examples/verifactu_tax_report.php
# Spanish compliance
php examples/invoicing_in_spain_with_verifactu.php