PHP code example of trevol / trevol-php

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

    

trevol / trevol-php example snippets


use Trevol\Exception\TrevolException;
use Trevol\Exception\ValidationException;
use Trevol\Trevol;

'

try {
    $factura = $trevol->invoices->createInvoice(
        invoice_input: [
            'external_id' => 'VENTA-2026-000123',
            'customer' => ['final_consumer' => true],
            'items' => [['description' => 'Café especial 500 g', 'quantity' => '1', 'unit_price' => '32000', 'taxes' => [['code' => '01', 'rate' => '19']]]],
            'payment' => ['form' => 'cash', 'methods' => [['code' => '10']]],
        ],
        idempotency_key: 'VENTA-2026-000123', // opcional: si falta, el SDK pone una y la repite en los reintentos
    );
    if ($factura->getStatus() === 'processing') {
        // 202: la DIAN no contestó; Trevol lo termina y avisa por webhook. NO crees otro documento para la misma venta.
    }
} catch (ValidationException $e) {
    foreach ($e->getErrors() as $x) {
        error_log($x['pointer'] . ' ' . $x['message']);
    }
} catch (TrevolException $e) {
    error_log($e->getTrevolCode() . ' ' . $e->getRequestId());
}

// Todas las páginas de un listado, perezosamente
foreach ($trevol->paginate(fn (?string $cursor) => $trevol->invoices->listInvoices(limit: 100, starting_after: $cursor)) as $f) {
    echo $f->getId(), ' ', $f->getStatus(), PHP_EOL;
}

// Los archivos llegan como \SplFileObject (un archivo temporal)
$pdf = $trevol->invoices->downloadInvoicePdf(id: 'inv_…');

use Trevol\Exception\WebhookVerificationException;
use Trevol\Webhook;

$wh = new Webhook(getenv('TREVOL_WEBHOOK_SECRET')); // whsec_…
try {
    $evento = $wh->verify(file_get_contents('php://input'), getallheaders()); // el cuerpo CRUDO (Laravel: $request->getContent() y $request->headers->all())
} catch (WebhookVerificationException $e) {
    http_response_code(400);
    exit;
}
// Deduplica por $evento->getId() (también llega en la cabecera webhook-id): la verificación no evita repeticiones.
$datos = $wh->eventData($evento); // el modelo según el type (p. ej. DocumentEventData); null si el tipo es nuevo
http_response_code(200);

new Trevol(
    apiKey: $llave,
    apiVersion: '2026-10-22',   // Trevol-Version en cada petición
    maxRetries: 2,              // 0 los apaga
    timeout: 65.0,              // segundos por intento
    maxRetryAfter: 60.0,        // segundos
    baseUrl: 'https://api.trevol.si/v1',
    environment: 'test',        // si la llave no coincide: ConfigurationException antes de llamar
    handler: null,              // un manejador de Guzzle propio (proxy, MockHandler…)
    proxy: null,                // p. ej. 'http://proxy.miempresa.co:3128'
);