PHP code example of flavytech / laravel-etims

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

    

flavytech / laravel-etims example snippets


use Flavytech\Etims\Facades\Etims;
use Flavytech\Etims\DTOs\InvoiceDTO;
use Flavytech\Etims\DTOs\InvoiceLineDTO;

$invoice = InvoiceDTO::make([
    'invcNo'       => 'INV-2024-001',
    'tpin'         => config('etims.credentials.pin'),
    'custTpin'     => 'P000000000B',    // buyer's KRA PIN
    'custNm'       => 'Acme Ltd',
    'totAmt'       => 11600.00,
    'vatAmt'       => 1600.00,
    'taxblAmt'     => 10000.00,
    'salesDt'      => now()->toDateString(),
    'cfmDt'        => now()->toDateString(),
    'rcptTyCd'     => 'S',              // S = Sale
    'pmtTyCd'      => '01',
    'itemList'     => [
        InvoiceLineDTO::make([
            'itemSeq'    => 1,
            'itemCd'     => 'ITEM-001',
            'itemNm'     => 'Widget Pro',
            'qty'        => 2,
            'prc'        => 5000.00,
            'taxblAmt'   => 10000.00,
            'taxAmt'     => 1600.00,
            'totAmt'     => 11600.00,
            'taxTyCd'    => 'A',       // A = Standard 16% VAT
        ]),
    ],
]);

$response = Etims::submitInvoice($invoice);

if ($response->isSuccessful()) {
    // Print the KRA receipt number and QR code
    $receiptNumber = $response->receiptNumber;
    $qrCode        = $response->qrCode;
}

// Fire and forget — returns immediately
Etims::queueInvoice($invoice);

// Your application continues while KRA processes in the background.
// Listen to events to know the outcome:

protected $listen = [
    \Flavytech\Etims\Events\InvoiceSubmitted::class => [
        \App\Listeners\GenerateKraReceipt::class,    // generate receipt PDF
        \App\Listeners\UpdateOrderStatus::class,     // mark order as fiscalized
    ],
    \Flavytech\Etims\Events\InvoiceFailed::class => [
        \App\Listeners\AlertOperationsTeam::class,   // notify via Slack/email
        \App\Listeners\FlagOrderForReview::class,    // mark in your system
    ],
    \Flavytech\Etims\Events\InvoiceQueued::class => [
        \App\Listeners\ShowPendingStatus::class,     // update POS UI immediately
    ],
];

$result = Etims::validatePin('P000000000B');

if ($result->isValid()) {
    echo "Buyer: {$result->taxpayerName}";
} else {
    // PIN not found in KRA registry
    return back()->withError('Invalid buyer PIN. Please verify and try again.');
}

$status = Etims::getInvoiceStatus('INV-2024-001');

if ($status->isSuccessful()) {
    echo "Receipt: {$status->receiptNumber}";
} elseif ($status->isPending()) {
    echo "KRA is still processing this invoice.";
}

// Get all permanently failed invoices for review
$failedInvoices = Etims::failedInvoices();

foreach ($failedInvoices as $invoice) {
    echo "{$invoice->invoice_number}: {$invoice->failure_reason}";
}

// Re-queue a failed invoice after fixing the issue
Etims::retryFailedInvoice($invoice->id);

// config/etims.php
'multi_tenancy' => [
    'enabled'         => true,
    'tenant_resolver' => \App\Services\EtimsTenantResolver::class,
],

use Flavytech\Etims\Contracts\TenantResolverContract;

class EtimsTenantResolver implements TenantResolverContract
{
    public function resolve(): array
    {
        // Resolve from your tenancy system
        $tenant = app('currentTenant'); // e.g. spatie/laravel-multitenancy

        return [
            'pin'           => $tenant->kra_pin,
            'branch_id'     => $tenant->etims_branch_id,
            'device_serial' => $tenant->etims_device_serial,
            'secret'        => decrypt($tenant->etims_secret), // store encrypted!
            'mode'          => $tenant->etims_mode,            // per-tenant sandbox/prod
        ];
    }

    public function tenantId(): string|int
    {
        return app('currentTenant')->id;
    }
}

$this->app->bind(
    \Flavytech\Etims\Contracts\TenantResolverContract::class,
    \App\Services\EtimsTenantResolver::class
);

use Flavytech\Etims\Facades\Etims;

beforeEach(function () {
    Etims::fake();
});

it('fiscalizes an order on checkout', function () {
    $order = Order::factory()->create(['total' => 11600]);

    $this->post("/orders/{$order->id}/checkout");

    Etims::assertInvoiceSubmitted("INV-{$order->id}");
});

it('queues the invoice for background processing', function () {
    Queue::fake();

    Etims::queueInvoice(makeTestInvoice('INV-001'));

    Etims::assertInvoiceQueued('INV-001');
});

it('handles KRA downtime gracefully', function () {
    Etims::fake()->failWith(
        new \Flavytech\Etims\Exceptions\EtimsApiException('KRA is down', 503)
    );

    // Your app should still return 200 — it queues for retry
    $this->post('/checkout/1')->assertStatus(202);
});

it('validates correct invoice data', function () {
    $fake = Etims::fake();

    $this->post('/checkout/1');

    $fake->assertSubmittedMatching(
        fn($invoice) => $invoice->totalAmount === 11600.00
            && $invoice->invoiceType === 'S'
    );
});

it('rejects an invalid buyer PIN', function () {
    Etims::fake()->withInvalidPins(['P999999999Z']);

    $response = Etims::validatePin('P999999999Z');

    expect($response->isValid())->toBeFalse();
});

use Flavytech\Etims\DTOs\InvoiceResponseDTO;

$stubbedResponse = InvoiceResponseDTO::fromKraResponse([
    'resultCd' => '000',
    'resultMsg' => 'OK',
    'data' => [
        'rcptNo'    => 'RCPT-MY-TEST',
        'qrCodeUrl' => 'https://test.kra.go.ke/qr/test',
    ],
]);

Etims::fake()->respondTo('INV-SPECIFIC-001', $stubbedResponse);

$response = Etims::submitInvoice($invoice); // returns RCPT-MY-TEST
bash
php artisan vendor:publish --tag=etims-config
php artisan vendor:publish --tag=etims-migrations
php artisan migrate
bash
# Supervisor config for dedicated eTIMS worker
php artisan queue:work redis \
    --queue=etims \
    --tries=5 \
    --backoff=10,30,60,120,300 \
    --timeout=60 \
    --sleep=3