PHP code example of mantix / eboekhouden-rest-api

1. Go to this page and download the library: Download mantix/eboekhouden-rest-api 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/ */

    

mantix / eboekhouden-rest-api example snippets


use Mantix\EBoekhoudenRestApi\Client;

// Initialiseer de client
$client = new Client(
    'JE_API_TOKEN', 
    'JouwApp'    // Source identifier, max 10 karakters
);

// Automatisch wordt er een sessie aangemaakt wanneer nodig

// Haal relaties op
$relations = $client->getRelations();

// Beëindig de sessie als je klaar bent
$client->endSession();

use Mantix\EBoekhoudenRestApi\Filter;

// Zoek relaties met "Bedrijf" in de naam
$relations = $client->getRelations([
    'name' => Filter::like('%Bedrijf%'),
]);

// Zoek facturen binnen een datumbereik
$invoices = $client->getInvoices([
    'date' => Filter::dateRange('2023-01-01', '2023-12-31'),
]);

$invoiceData = [
    'relationId' => 12345,                   // Verplicht: ID van de relatie
    'date' => date('Y-m-d'),                 // Factuur datum (standaard: vandaag)
    'termOfPayment' => 14,                   // Betalingstermijn in dagen
    'templateId' => 6789,                    // Verplicht: ID van het factuursjabloon
    'invoiceNumber' => 'F2023-001',          // Optioneel; indien leeg wordt automatisch gegenereerd
    'reference' => 'Bestelling #12345',      // Referentie op de factuur
    'items' => [                             // Verplicht: minimaal 1 item
        [
            'description' => 'Product 1',    // Verplicht: omschrijving
            'pricePerUnit' => 100.00,        // Verplicht: prijs per eenheid (excl. BTW)
            'quantity' => 2,                 // Aantal (standaard: 1)
            'vatCode' => 'HOOG_VERK_21',     // Verplicht: BTW-code
            'ledgerId' => 8000,              // Verplicht: ID van de grootboekrekening
            'costCenterId' => 123,           // Optioneel: kostenplaats ID
            'unitId' => 456,                 // Optioneel: eenheid ID (stuk, uur, etc.)
            'productId' => 789,              // Optioneel: product ID
            'discountPercentage' => 10,      // Optioneel: kortingspercentage
        ],
        [
            'description' => 'Product 2',
            'pricePerUnit' => 75.00,
            'quantity' => 1,
            'vatCode' => 'HOOG_VERK_21',
            'ledgerId' => 8000,
        ],
    ],
    'email' => [                             // Optioneel: verstuur factuur direct per e-mail
        'fromEmail' => '[email protected]',   // Optioneel: afzender e-mail
        'fromName' => 'Mijn Bedrijf',        // Optioneel: afzender naam
        'subject' => 'Uw factuur',           // Verplicht als email object aanwezig is
        'body' => 'Beste klant,<br><br>Hierbij ontvangt u uw factuur.<br><br>Met vriendelijke groet,', // Verplicht als email object aanwezig is
        'attachUbl' => true,                 // Voeg UBL-bestand toe
    ],
    'mutation' => [                          // Optioneel: verwerk factuur meteen als mutatie
        'description' => 'Factuur voor producten', // Omschrijving van de mutatie
        'ledgerId' => 1300,                  // Grootboekrekening voor de mutatie
        'checkPaymentReference' => true,     // Controleer of referentie uniek is
        'paymentReference' => 'REF12345',    // Unieke referentie voor de betaling
    ],
];

$invoice = $client->createInvoice($invoiceData);

$relationData = [
    'type' => 'B',                           // 'B' (zakelijk) of 'P' (particulier)
    'name' => 'Mijn Nieuwe Klant BV',        // Verplicht: (bedrijfs)naam
    'contact' => 'John Doe',                 // Contactpersoon
    'gender' => 'm',                         // 'm' (man), 'v' (vrouw) of 'a' (afdeling)
    'address' => 'Hoofdstraat 1',            // Adres
    'postalCode' => '1234 AB',               // Postcode
    'city' => 'Amsterdam',                   // Plaats
    'country' => 'Nederland',                // Land
    'phoneNumber' => '0201234567',           // Telefoonnummer
    'emailAddress' => '[email protected]',    // E-mailadres
    'vatNumber' => 'NL123456789B01',         // BTW-nummer
    'termOfPayment' => 14,                   // Betalingstermijn in dagen
    'ledgerId' => 1200,                      // Grootboekrekening
];

$relation = $client->createRelation($relationData);

$mutationData = [
    'type' => '2',                           // Verplicht: type mutatie (2 = Verkoopfactuur)
    'date' => date('Y-m-d'),                 // Verplicht: datum mutatie
    'ledgerId' => 1300,                      // Verplicht: grootboekrekening
    'invoiceNumber' => 'F2023-001',          // Factuurnummer (verplicht bij factuurmutaties)
    'description' => 'Factuur voor diensten', // Omschrijving
    'inExVat' => 'EX',                       // Verplicht: 'IN' (incl. BTW) of 'EX' (excl. BTW)
    'relationId' => 12345,                   // Relatie ID
    'rows' => [                              // Verplicht: minimaal 1 regel
        [
            'ledgerId' => 8000,              // Verplicht: grootboekrekening voor deze regel
            'vatCode' => 'HOOG_VERK_21',     // Verplicht: BTW-code
            'amount' => 150.00,              // Verplicht: bedrag
            'description' => 'Consultancy werkzaamheden', // Omschrijving
        ],
    ],
];

$mutation = $client->createMutation($mutationData);

// Eerste pagina (eerste 100 items)
$page1 = $client->getRelations([
    'limit' => 100,
    'offset' => 0,
]);

// Tweede pagina (volgende 100 items)
$page2 = $client->getRelations([
    'limit' => 100,
    'offset' => 100,
]);

use Mantix\EBoekhoudenRestApi\Client;
use Mantix\EBoekhoudenRestApi\EBoekhoudenException;

$client = new Client('JE_API_TOKEN', 'JouwApp');

try {
    $relations = $client->getRelations();
} catch (EBoekhoudenException $e) {
    echo "API fout: " . $e->getMessage();
    echo "API foutcode: " . $e->getErrorCode();
    print_r($e->getErrorResponse()); // Volledige foutrespons
} catch (\Exception $e) {
    echo "Algemene fout: " . $e->getMessage();
}

try {
    $result = $client->createInvoice($invoiceData);
} catch (EBoekhoudenException $e) {
    // Haal basis foutgegevens op
    $message = $e->getMessage();      // Bijv. "Relatie niet gevonden"
    $code = $e->getCode();            // HTTP status code (bijv. 400, 404)
    $errorCode = $e->getErrorCode();  // API foutcode (bijv. "FACT_002")
    
    // Haal volledige foutrespons op voor meer details
    $errorResponse = $e->getErrorResponse();
    /* 
    Array zoals:
    [
        'errors' => [...],            // Validatiefouten (indien aanwezig)
        'type' => 'validation',       // Type fout
        'propertyName' => 'relationId', // Veld dat de fout veroorzaakte
        'code' => 'FACT_002',         // Foutcode
        'title' => 'Relatie niet gevonden', // Korte foutbeschrijving
        'message' => '...',           // Uitgebreide foutinformatie (niet altijd aanwezig)
        'status' => 400,              // HTTP status
        'traceId' => 'ABCDEF-123456'  // Unieke trace voor foutopsporing
    ]
    */
    
    // Voorbeeld van hoe je specifieke foutafhandeling kunt implementeren
    switch ($errorCode) {
        case 'FACT_002':
            echo "De opgegeven relatie bestaat niet. Controleer het relationId.";
            break;
        case 'FACT_019':
            echo "Er zijn geen factuuritems opgegeven. Voeg minimaal één item toe.";
            break;
        default:
            echo "Er is een fout opgetreden: " . $message;
    }
}

class ExtendedClient extends \Mantix\EBoekhoudenRestApi\Client {
    /**
     * Maximum aantal herverbindingspogingen
     */
    private int $maxRetries = 1;
    
    /**
     * Voer een API-verzoek uit met automatische herverbinding bij sessieverlies
     *
     * @param callable $apiCall Een functie die de API-aanroep uitvoert
     * @return mixed Het resultaat van de API-aanroep
     * @throws \Exception
     */
    public function executeWithRetry(callable $apiCall) {
        $retries = 0;
        
        while (true) {
            try {
                return $apiCall();
            } catch (\Mantix\EBoekhoudenRestApi\EBoekhoudenException $e) {
                // Controleer of de fout een verlopen sessie is
                if ($e->getErrorCode() === 'SECURITY_010' && $retries < $this->maxRetries) {
                    // Sessie is verlopen, maak een nieuwe sessie aan
                    $this->createSession();
                    $retries++;
                    continue;
                }
                
                // Andere fout of maximaal aantal pogingen bereikt
                throw $e;
            }
        }
    }
}

// Gebruik:
$client = new ExtendedClient('JE_API_TOKEN', 'JouwApp');

try {
    $result = $client->executeWithRetry(function() use ($client) {
        return $client->getRelations(['limit' => 100]);
    });
} catch (\Exception $e) {
    echo "Fout: " . $e->getMessage();
}

// Voorbeeld van een Invoice Builder class
class InvoiceBuilder {
    private array $data = [];
    private array $items = [];
    
    public function __construct(int $relationId, int $templateId) {
        $this->data['relationId'] = $relationId;
        $this->data['templateId'] = $templateId;
        $this->data['date'] = date('Y-m-d');
        $this->data['termOfPayment'] = 14; // Standaard betalingstermijn
    }
    
    public function setInvoiceNumber(string $number): self {
        $this->data['invoiceNumber'] = $number;
        return $this;
    }
    
    public function setDate(string $date): self {
        $this->data['date'] = $date;
        return $this;
    }
    
    public function addItem(string $description, float $pricePerUnit, int $ledgerId, string $vatCode, float $quantity = 1): self {
        $this->items[] = [
            'description' => $description,
            'pricePerUnit' => $pricePerUnit,
            'quantity' => $quantity,
            'vatCode' => $vatCode,
            'ledgerId' => $ledgerId
        ];
        return $this;
    }
    
    public function build(): array {
        $this->data['items'] = $this->items;
        return $this->data;
    }
}

// Gebruik:
$invoice = (new InvoiceBuilder(12345, 6789))
    ->setInvoiceNumber('F2023-001')
    ->addItem('Consultancy', 95.00, 8000, 'HOOG_VERK_21', 8)
    ->addItem('Training', 595.00, 8000, 'HOOG_VERK_21', 1)
    ->build();

$result = $client->createInvoice($invoice);

$invoice = $client->getInvoice(12345);
$pdfUrl = $invoice['urlPdfFile'];

// Download de PDF
if (!empty($pdfUrl)) {
    $pdfContent = file_get_contents($pdfUrl);
    file_put_contents('factuur.pdf', $pdfContent);
    echo "Factuur gedownload als 'factuur.pdf'";
} else {
    echo "Geen PDF-URL beschikbaar voor deze factuur";
}

$cache = new \Symfony\Component\Cache\Adapter\FilesystemAdapter();

// Haal grootboekrekeningen op met caching
$ledgers = $cache->get('ledgers', function() use ($client) {
    return $client->getLedgers(['limit' => 500]);
});

function processInBatches(array $items, int $batchSize = 25, callable $processor) {
    $batches = array_chunk($items, $batchSize);
    $results = [];
    
    foreach ($batches as $batch) {
        $batchResults = $processor($batch);
        $results = array_merge($results, $batchResults);
        
        // Optioneel: voeg een korte pauze toe om API overbelasting te voorkomen
        usleep(500000); // 500ms
    }
    
    return $results;
}