PHP code example of davidakis / fattura24-sdk
1. Go to this page and download the library: Download davidakis/fattura24-sdk 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/ */
davidakis / fattura24-sdk example snippets
spl_autoload_register(function ($class) {
$prefix = 'Davidakis\\Fattura24SDK\\';
$baseDir = __DIR__ . '/src/';
$len = strlen($prefix);
if (strncmp($prefix, $class, $len) !== 0) {
return;
}
$relativeClass = substr($class, $len);
$file = $baseDir . str_replace('\\', '/', $relativeClass) . '.php';
if (file_exists($file)) {
use Davidakis\Fattura24SDK\Fattura24Client;
use Davidakis\Fattura24SDK\Data\{DocumentData, DocumentType, CustomerData, RowData, InvoiceData};
// 1. Crea il client
$client = new Fattura24Client([
'apiKey' => 'your-api-key',
'source' => 'MyApp', // opzionale
'pdfDir' => '/var/www/fatture', // opzionale: salva PDF qui
]);
// 2. Prepara i dati
$document = new DocumentData(
documentType: DocumentType::FatturaElettronica,
total: 122.00,
);
$document->totalWithoutTax = 100.00;
$document->vatAmount = 22.00;
// Optional: override default payment (default is MP08 - Pagamento con carta)
$document->setPayment('MP05', 'Bonifico bancario');
$customer = new CustomerData('Mario Rossi');
$customer->customerCountry = 'IT';
$customer->setCustomerFiscalCode('RSSMRA80A01H501U'); // Auto-validato per clienti IT
$customer->customerEmail = '[email protected] ';
$row = new RowData('Consulenza', 1, 100.00, 22);
$invoice = new InvoiceData($document, $customer, [$row]);
// 3. Invia la fattura
$response = $client->saveDocument($invoice);
echo "Fattura #{$response->docNumber} creata con ID {$response->docId}\n";
use Davidakis\Fattura24SDK\Builder\InvoiceBuilder;
$invoice = InvoiceBuilder::create()
->customer('Mario Rossi', 'IT', 'mario.example.com')
->fiscalCode('RSSMRA80A01F205C')
->totals(122.00, 100.00, 22.00)
->payment('MP05', 'Bonifico bancario')
->row('Consulenza tecnica', 1, 100.00, 22)
->build();
$response = $client->saveDocument($invoice);
echo "Invoice created: {$response->docNumber}\n";
// SaveDocumentResponse
$response = $client->saveDocument($invoice);
echo $response->docId; // string - IDE autocomplete
echo $response->docNumber; // string - Type-safe
$response->isSuccess(); // bool - Helper method
// GetFileResponse con metadati
$file = $client->getFile($docId);
echo $file->filename; // "invoice_123.pdf"
echo $file->contentType; // "application/pdf"
echo $file->getHumanSize(); // "1.5 MB"
if ($file->isPdf()) {
file_put_contents('/tmp/invoice.pdf', $file->content);
}
// GetTemplatesResponse
$templates = $client->getTemplates();
foreach ($templates->invoice as $id => $name) {
echo "<option value='{$id}'>{$name}</option>";
}
// GetNumeratorsResponse con helper
$numerators = $client->getNumerators();
$defaultId = $numerators->getDefaultId('invoice');
$document->idNumerator = $defaultId;
// GetChartOfAccountsResponse con search
$pdc = $client->getChartOfAccounts();
$filtered = $pdc->search('prodotto'); // Case-insensitive
foreach ($filtered as $id => $desc) {
echo "{$id}: {$desc}\n";
}
$customer = new CustomerData('Rossi SRL');
$customer->customerCountry = 'IT';
// ✓ OK: 11 cifre
$customer->setCustomerVatCode('12345678901');
// ✗ Exception: formato non valido
$customer->setCustomerVatCode('ABC');
// InvalidArgumentException: P.IVA italiana deve essere 11 cifre numeriche
// ✓ OK: validazione solo per IT
$customer->customerCountry = 'FR';
$customer->setCustomerVatCode('FR123'); // Non validato (cliente estero)
$customer->setCustomerFiscalCode(' rssmra80a01h501u ');
// Salvato come: 'RSSMRA80A01H501U' (trim + uppercase)
$client->setPdfDirectory('/var/www/fatture');
$filepath = $client->downloadPdf($docId);
// Returns: /var/www/fatture/invoice_123.pdf
$client->setPdfDirectory(null);
$result = $client->downloadPdf($docId);
// PDF trasmesso direttamente (usando readfile())
// Returns: null (PDF già inviato)
$pdfManager = $client->getPdfManager();
// WordPress
$pdfManager->setUrlGenerator(fn($id) => home_url("/pdf/{$id}"));
// Laravel
$pdfManager->setUrlGenerator(fn($id) => route('pdf.download', ['id' => $id]));
// Symfony
$pdfManager->setUrlGenerator(fn($id) => $router->generate('pdf_download', ['id' => $id]));
// Vanilla PHP
$pdfManager->setUrlGenerator(fn($id) => "https://example.com/download.php?id={$id}");
// Compatto (posizionali)
$row = new RowData('Servizio', 1, 100.00, 22);
// Esplicito (parametri nominati) - raccomandato
$row = new RowData(
description: 'Servizio di consulenza',
qty: 1,
price: 100.00,
vatCode: 22,
);
// DocumentData semplificato (solo 2 params obbligatori)
$document = new DocumentData(
documentType: DocumentType::FatturaElettronica,
total: 122.00,
);
// Pagamento predefinito: MP08 (Pagamento con carta)
$invoice = (new InvoiceData($document, $customer, [$row]))
->withDelivery($delivery)
->withPayments([$payment]);
$document->setPayment('MP05', 'Bonifico bancario', 'IBAN: IT...');
$document = new DocumentData(
documentType: DocumentType::FatturaElettronica,
total: 100.00,
);
$document->totalWithoutTax = 100.00;
$document->vatAmount = 0.00;
$customer = new CustomerData('Studio Medico Bianchi');
$customer->customerCountry = 'IT';
$customer->setCustomerVatCode('12345678901');
$customer->feDestinationCode = '0000000';
$customer->feCustomerPec = '[email protected] ';
$row = new RowData('Visita specialistica', 1, 100.00, 0);
$row->feVatNature = 'N4'; // Esente art. 10
$invoice = new InvoiceData($document, $customer, [$row]);
$response = $client->saveDocument($invoice);
$document = new DocumentData(
documentType: DocumentType::FatturaELettronica,
total: 109.80,
);
$document->totalWithoutTax = 90.00;
$document->vatAmount = 19.80;
$row = new RowData('Prodotto', 1, 100.00, 22);
$row->discount = 10; // Sconto 10%
$invoice = new InvoiceData($document, $customer, [$row]);
$rows = [
new RowData('Bene essenziale', 1, 100.00, 10), // IVA 10%
new RowData('Servizio standard', 1, 100.00, 22), // IVA 22%
];
$document->total = 132.00;
$document->totalWithoutTax = 110.00;
$document->vatAmount = 22.00; // 10 + 22
$invoice = new InvoiceData($document, $customer, $rows);
$result = $client->testKey();
// ['returnCode' => 0, 'message' => 'OK']
$result = $client->saveDocument($invoice);
$docId = $result['docId'];
$docNumber = $result['docNumber'];
$response = $client->saveDocument($invoice);
$docId = $response->docId;
$docNumber = $response->docNumber;
// Funzione di retrocompatibilità (se necessario)
function saveDocumentLegacy($client, $invoice) {
$response = $client->saveDocument($invoice);
return [
'docId' => $response->docId,
'docNumber' => $response->docNumber,
'docType' => $response->docType,
];
}
bash
# 1. Copia il file example
cp test-manual.php.example test-manual.php
# 2. Modifica test-manual.php e inserisci la tua API key
nano test-manual.php
# Sostituisci: $API_KEY = 'YOUR_API_KEY_HERE';
# 3. Esegui i test
php test-manual.php