PHP code example of estratos / finkok-bundle

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

    

estratos / finkok-bundle example snippets


return [
    // …
    Estratos\FinkokBundle\FinkokBundle::class => ['all' => true],
];

namespace App\Finkok;

use Estratos\FinkokBundle\Config\Credentials;
use Estratos\FinkokBundle\Config\CredentialsInterface;
use Estratos\FinkokBundle\Config\CredentialsProviderInterface;
use Estratos\FinkokBundle\Config\Environment;

final class TenantCredentialsProvider implements CredentialsProviderInterface
{
    public function __construct(private readonly TenantContext $tenant)
    {
    }

    public function get(?string $name = null): CredentialsInterface
    {
        $name ??= (string) $this->tenant->activeRfc();

        return new Credentials(
            name: $name,
            username: (string) $this->tenant->get('finkok_username'),
            password: (string) $this->tenant->get('finkok_password'),
            taxpayerId: $name,
            environment: $this->tenant->isProduction() ? Environment::Production : Environment::Demo,
        );
    }

    public function has(string $name): bool
    {
        return null !== $this->tenant->find($name);
    }

    public function default(): CredentialsInterface
    {
        return $this->get();
    }

    /**
     * @return list<string>
     */
    public function names(): array
    {
        return $this->tenant->allRfcs();
    }
}

use Estratos\FinkokBundle\Contract\CancelServiceInterface;
use Estratos\FinkokBundle\Contract\StampServiceInterface;

final class FacturacionService
{
    public function __construct(
        private readonly StampServiceInterface $finkokStamp,
        private readonly CancelServiceInterface $finkokCancel,
    ) {
    }
}

use Estratos\FinkokBundle\Xml\CfdiDocument;

$cfdi = CfdiDocument::fromFile('/ruta/factura.xml');  // o fromString($xml)

$receipt = $this->finkokStamp->stamp($cfdi);

if (!$receipt->isSuccess()) {
    // El mensaje incluye el código de Finkok y, en el log, la pista de solución.
    throw new \RuntimeException((string) $receipt->getErrorMessage());
}

$uuid = $receipt->uuid;                  // 7D162D12-F6B6-4BDE-BC8A-BABC4331919A
$xmlTimbrado = $receipt->getStampedXml(); // CFDI con el nodo tfd:TimbreFiscalDigital

$receipt = $this->finkokStamp->stamp($cfdi)->assertSuccess(); // lanza ApiException si falla

echo $this->finkokStamp->previewStampRequest($cfdi);

$receipt = $this->finkokStamp->stamp($cfdi);

if ($receipt->isPreviouslyStamped() && !$receipt->hasStampedXml()) {
    sleep(3);
    $receipt = $this->finkokStamp->stamped($cfdi); // método Stamped
}

$xmlTimbrado = $receipt->getStampedXml();

$receipt->uuid === $receipt->uuidFromXml();

use Estratos\FinkokBundle\Model\CancellationReason;
use Estratos\FinkokBundle\Model\CancellationUuid;

$receipt = $this->finkokCancel->cancel([
    new CancellationUuid($uuid, CancellationReason::ErrorsWithoutRelation),
]);

// Motivo 01 (con relación) exige el UUID que sustituye al cancelado:
// new CancellationUuid($uuid, CancellationReason::ErrorsWithRelation, $uuidSustituto)

$receipt->assertSuccess();

foreach ($receipt->folios as $folio) {
    $folio->uuid;                 // UUID procesado
    $folio->isCancelled();        // ¿el SAT aceptó? (códigos 201/202)
    $folio->isInProcess();        // ¿quedó en proceso? (204/205)
    $folio->getStatusDescription();
}

$this->finkokCancel->cancel($uuids, storePending: false);

$status = $this->finkokCancel->getSatStatus(
    uuid: $uuid,
    taxpayerId: 'EKU9003173C9',        // RFC emisor
    receiverTaxpayerId: 'MISC491214B86', // RFC receptor
    total: '1160.00',                  // ¡con los decimales exactos!
);

$status->isActive();       // Vigente
$status->isCancelled();    // Cancelado
$status->isCancellable();  // admite cancelación
$status->details?->

$status = $this->finkokCancel->getStatusOf(CfdiDocument::fromString($xmlTimbrado));

use Estratos\FinkokBundle\Model\AcceptRejectAnswer;

$result = $this->finkokCancel->acceptReject([
    'A1B2C3D4-1111-2222-3333-444455556666' => AcceptRejectAnswer::Accepted,
    'B2C3D4E5-1111-2222-3333-444455556666' => AcceptRejectAnswer::Rejected,
], receiverTaxpayerId: 'MISC491214B86');

$result->countAccepted();
$result->countRejected();
$result->accepted[0]->uuid;

use Estratos\FinkokBundle\Model\ReceiptType;

// Acuse de recepción (I) o de cancelación (C)
$acuse = $this->finkokCancel->getReceipt($uuid, ReceiptType::Cancellation);
$acuse->receipt;   // XML del acuse del SAT

// UUID con cancelación pendiente de un receptor
$pending = $this->finkokCancel->getPending('MISC491214B86');
$pending->uuids;
$pending->contains($uuid);

// Estado de un timbrado que quedó en la cola de Finkok
$queued = $this->finkokStamp->queryPending($uuid);
$queued->isStampedNotSent();  // "S": timbrado, aún no enviado al SAT
$queued->isFinished();        // "F": ya enviado al SAT
$queued->attempts;

use Estratos\FinkokBundle\Config\CredentialsProviderInterface;

final class FacturacionService
{
    public function __construct(
        private readonly StampServiceInterface $finkokStamp,
        private readonly CredentialsProviderInterface $finkokCredentials,
    ) {
    }

    public function timbrarPara(string $emisor, string $xml): string
    {
        $perfil = $this->finkokCredentials->get($emisor); // 'matriz' | 'sucursal'

        $receipt = $this->finkokStamp->stamp($xml, $perfil);

        return (string) $receipt->getStampedXml();
    }
}

$receipt->isSuccess();             // ¿surtió efecto la operación?
$receipt->getStatusCode();         // CodEstatus tal cual lo devolvió Finkok
$receipt->getErrorCodes();         // ['705']
$receipt->getErrorMessage();       // mensaje legible, o null
$receipt->hasErrorCode(ErrorCode::InvalidXmlStructure);
$receipt->getIncidences();         // colección tipada de incidencias
$receipt->isCredentialError();     // usuario/contraseña o ambiente equivocado
$receipt->isTransient();           // conviene reintentar
$receipt->

use Estratos\FinkokBundle\Model\ErrorCode;

$code = ErrorCode::tryFrom('307');

$code?->description();  // "El CFDI contiene un timbre previo."
$code?->hint();         // qué hacer exactamente para resolverlo
$code?->isTransient();
$code?->

use Estratos\FinkokBundle\Exception\FinkokExceptionInterface;
use Estratos\FinkokBundle\Exception\TransportException;
use Estratos\FinkokBundle\Exception\ApiException;

try {
    $receipt = $this->finkokStamp->stamp($cfdi)->assertSuccess();
} catch (TransportException $e) {
    if ($e->isRetryable()) {
        // reintentar más tarde (Messenger, cron, …)
    }
} catch (ApiException $e) {
    foreach ($e->getIncidences() as $incidencia) {
        $this->logger->error($incidencia->describe());
    }
} catch (FinkokExceptionInterface $e) {
    // cualquier otro fallo del bundle
}