PHP code example of georgesks / facter-sdk-php

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

    

georgesks / facter-sdk-php example snippets



Facter\Sdk\Configuration;
use Facter\Sdk\Environment;
use Facter\Sdk\Api\CFDIsApi;
use Facter\Sdk\Model\StampRequest;
use Facter\Sdk\Idempotency;
use GuzzleHttp\Client;

// 1. Configura tu key y el ambiente (empieza en DEMO).
$config = Configuration::getDefaultConfiguration()
    ->setAccessToken(getenv('FACTER_API_KEY'))          // fct_live_xxx
    ->setHost(Environment::baseUrl(Environment::DEMO));

$cfdis = new CFDIsApi(new Client(), $config);

// 2. Arma el comprobante (JSON canónico CFDI 4.0).
$req = new StampRequest([
    'emisor_rfc'  => 'EKU9003173C9',
    'external_ref'=> 'FACTURA-2026-00042',   // tu folio interno (opcional)
    'cfdi'        => [ /* ...comprobante CFDI 4.0... */ ],
]);

// 3. Timbra. La clave de idempotencia evita doble cobro ante reintentos.
$idempotencyKey = Idempotency::newKey();

try {
    $resp = $cfdis->stampCfdi($idempotencyKey, $req);
    echo "Timbrado UUID: " . $resp->getData()->getUuid() . PHP_EOL;
} catch (\Facter\Sdk\ApiException $e) {
    $error = json_decode($e->getResponseBody(), true);
    fwrite(STDERR, "Error {$e->getCode()}: {$error['error']['code']}\n");
}

use Facter\Sdk\Idempotency;

$key = Idempotency::newKey();                          // UUID v4 aleatorio
$key = Idempotency::fromReference('FACTURA-2026-42');  // determinista por folio

use Facter\Sdk\Http\RetryMiddleware;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Client;

$stack = HandlerStack::create();
$stack->push(RetryMiddleware::create());          // 3 reintentos por default

$cfdis = new CFDIsApi(new Client(['handler' => $stack]), $config);

$resultado = $cfdis->validateCfdi($req);

use Facter\Sdk\Webhook;

$raw    = file_get_contents('php://input');
$sigHdr = $_SERVER['HTTP_X_FACTER_SIGNATURE'] ?? '';

if (!Webhook::verifySignature($raw, $sigHdr, getenv('FACTER_WEBHOOK_SECRET'))) {
    http_response_code(401);
    exit;
}

$evento = json_decode($raw, true);   // cfdi.timbrado, cfdi.cancelado, ...

try {
    $cfdis->stampCfdi($idempotencyKey, $req);
} catch (\Facter\Sdk\ApiException $e) {
    $body = json_decode($e->getResponseBody(), true);
    // $e->getCode()            → HTTP status (402, 422, 429, ...)
    // $body['error']['code']   → código de negocio (NO_STAMPS_AVAILABLE, ...)
    // $body['error']['docs']   → enlace a la doc del error
}
bash
composer