PHP code example of vimatech / laravel-einvoicing

1. Go to this page and download the library: Download vimatech/laravel-einvoicing 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/ */

    

vimatech / laravel-einvoicing example snippets


use Vimatech\EInvoicing\Dtos\{CanonicalInvoice, Party, LineItem, TaxBreakdown};

$invoice = new CanonicalInvoice(
    number: 'INV-2024-0001',
    issueDate: new DateTimeImmutable('2024-01-15'),
    currency: 'EUR',
    seller: new Party(
        name: 'Acme Trading Ltd.',
        countryCode: 'BE',
        endpointId: '0123456789',        // Peppol electronic address (BT-34), bare
        endpointScheme: '0208',          // EAS scheme id, emitted as schemeID
        vatId: 'BE0123456789',
        legalRegistrationId: '0123456789',
        legalRegistrationScheme: '0208',
        street: 'Main street 1',
        city: 'Brussels',
        postalZone: '1050',
    ),
    buyer: new Party(
        name: 'Globex NV',
        countryCode: 'BE',
        endpointId: '9876543210',
        endpointScheme: '0208',
        vatId: 'BE9876543210',
        street: 'Market square 9',
        city: 'Antwerp',
        postalZone: '2000',
    ),
    lines: [
        new LineItem(
            id: '1',
            name: 'Laptop computer',
            quantity: 5.0,
            netPrice: 200.0,
            lineExtensionAmount: 1000.0,
            taxCategory: 'S',
            taxPercent: 21.0,
        ),
    ],
    taxBreakdowns: [
        new TaxBreakdown(category: 'S', percent: 21.0, taxableAmount: 1000.0, taxAmount: 210.0),
    ],
    dueDate: new DateTimeImmutable('2024-02-14'),
    buyerReference: 'PO-98765',
);

new CanonicalInvoice(
    // ...
    currency: 'JPY',
    amountDecimals: 0, // 0 for JPY, 2 for EUR, 3 for TND; 0 to 4 accepted
);

use Vimatech\EInvoicing\Facades\EInvoice;
use Vimatech\EInvoicing\Enums\Format;

$document = EInvoice::format(Format::Ubl)->generate($invoice);

$document->contents;        // the XML string
$document->mimeType;        // application/xml
$document->profile;         // urn:cen.eu:en16931:2017#compliant#urn:fdc:peppol.eu:2017:poacc:billing:3.0
$document->save('/path/to/INV-2024-0001.xml');

use Vimatech\EInvoicing\Dtos\PrecedingInvoiceReference;

$creditNote = new CanonicalInvoice(
    // ...
    typeCode: CanonicalInvoice::TYPE_CREDIT_NOTE,
    precedingInvoiceReference: new PrecedingInvoiceReference(
        number: 'INV-2024-0001',                       // BT-25
        issueDate: new DateTimeImmutable('2024-01-15'), // BT-26, optional
    ),
);

use Vimatech\EInvoicing\Exceptions\InvalidInvoice;

try {
    EInvoice::format(Format::Ubl)->generate($invoice);
} catch (InvalidInvoice $e) {
    $e->violations(); // ['BT-1: invoice number is 

use Vimatech\EInvoicing\Enums\ValidationProfile;
use Vimatech\EInvoicing\Formats\Support\InvoiceValidator;

InvoiceValidator::assertConformsTo($invoice, ValidationProfile::PeppolBis);

(new InvoiceValidator)->violations($invoice); // EN 16931 core, as a list

$result = EInvoice::send($invoice); // Format defaults to config('einvoicing.default_format')

$result->status;       // LifecycleStatus::Delivered | Submitted | Rejected | ...
$result->messageId;    // poll later with fetchStatus()
$result->successful(); // bool

EInvoice::send($invoice, Format::Ubl, networkKey: 'peppol');

EInvoice::route('BE');        // network responsible for Belgium
EInvoice::network('peppol');  // a network by key

// messageId is null when the network returned none (NullDriver, a partner that
// does not acknowledge with an id), so guard before polling.
if ($result->messageId !== null) {
    $status = EInvoice::network('peppol')->fetchStatus($result->messageId);
}

use Vimatech\EInvoicing\Dtos\GeneratedDocument;

$document = GeneratedDocument::fromStored(Format::Ubl, $storedXml, $invoice->number);

$result = EInvoice::transmit($document, $invoice); // or transmit($document, $invoice, 'peppol')

foreach (EInvoice::receive('peppol') as $inbound) {
    $inbound->contents;  // decoded document body
    $inbound->senderId;  // sender electronic address
}
// each inbound document also fires an EInvoiceReceived event

use Vimatech\EInvoicing\Exceptions\UnrecognisedInboundDocument;

$exceptions->reportable(function (UnrecognisedInboundDocument $e) {
    // $e->network, $e->messageId, $e->declaredFormat, $e->raw
});

'networks' => [
    'peppol' => [
        'driver' => 'peppol',
        'base_url' => env('PEPPOL_BASE_URL'),
        'token' => env('PEPPOL_API_TOKEN'),
        'paths' => ['send' => '/documents', 'status' => '/documents/{id}/status', 'inbound' => '/inbound'],
        'status_map' => [],   // map partner status strings -> LifecycleStatus values
    ],
    'fr_pdp' => ['driver' => 'fr_pdp', 'base_url' => env('FR_PDP_BASE_URL'), 'token' => env('FR_PDP_API_TOKEN')],
    'sandbox' => ['driver' => 'null'],
],

'routing' => [
    'FR' => 'fr_pdp',
    'BE' => 'peppol',
    'NL' => 'peppol',
    // ...
],

'fallback' => env('EINVOICING_FALLBACK_NETWORK'), // null => unmatched countries throw

'peppol' => [
    'driver' => 'peppol',
    'base_url' => env('PEPPOL_BASE_URL'),
    'token' => env('PEPPOL_API_TOKEN'),
    'timeout' => env('PEPPOL_TIMEOUT', 30),
    'paths' => [
        'send' => '/v2/outbound',
        'status' => '/v2/messages/{id}',
        'inbound' => '/v2/inbound',
    ],
    'status_map' => [
        'in_progress' => 'in_transit',
        'done' => 'delivered',
    ],
],

'peppol' => [
    'driver' => 'peppol',
    'base_url' => env('PEPPOL_BASE_URL'),
    'auth' => 'none',
    'headers' => ['X-Api-Signature' => env('PEPPOL_SIGNATURE')],
],

'routing' => [
    'ES' => 'peppol',
    'IT' => 'peppol',
],

use Vimatech\EInvoicing\Facades\EInvoice;

EInvoice::router()->overrideUsing(function (string $country, ?CanonicalInvoice $invoice) {
    return tenant()->prefersDirectPeppol() ? 'peppol' : null;
});

namespace App\EInvoicing;

use Vimatech\EInvoicing\Contracts\EInvoiceNetwork;
use Vimatech\EInvoicing\Dtos\{CanonicalInvoice, DispatchResult, GeneratedDocument, NetworkCapabilities};
use Vimatech\EInvoicing\Enums\{Format, LifecycleStatus};

final class AcmeDriver implements EInvoiceNetwork
{
    public function __construct(private array $config, private string $key) {}

    public function key(): string { return $this->key; }

    public function send(GeneratedDocument $document, CanonicalInvoice $invoice): DispatchResult
    {
        // ... call your partner, then normalise the response ...
        return new DispatchResult(LifecycleStatus::Submitted, $this->key, messageId: '...');
    }

    public function fetchStatus(string $messageId): DispatchResult { /* ... */ }
    public function receive(): array { return []; }
    public function capabilities(): NetworkCapabilities
    {
        return new NetworkCapabilities($this->key, formats: [Format::Ubl]);
    }
}

'networks' => [
    'acme' => ['driver' => App\EInvoicing\AcmeDriver::class, /* ... */],
],

'networks' => [
    'acme' => ['driver' => 'acme', 'base_url' => env('ACME_BASE_URL')],
],

app(\Vimatech\EInvoicing\Networks\NetworkManager::class)
    ->extend('acme', fn (array $config, string $key) => new App\EInvoicing\AcmeDriver($config, $key));

use Vimatech\EInvoicing\Facades\EInvoice;
use Vimatech\EInvoicing\Enums\LifecycleStatus;

it('sends the invoice to Peppol', function () {
    $fake = EInvoice::fake('peppol');

    EInvoice::send($invoice);

    $fake->assertSent(fn ($invoice) => $invoice->number === 'INV-2024-0001');
    $fake->assertSentCount(1);
    expect($fake->lastSent()->number)->toBe('INV-2024-0001');
});

it('handles a rejection', function () {
    EInvoice::fake('peppol')->alwaysReturn(LifecycleStatus::Rejected);

    expect(EInvoice::send($invoice)->rejected())->toBeTrue();
});
bash
php artisan vendor:publish --tag=einvoicing-config