PHP code example of nosh / omnitax

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

    

nosh / omnitax example snippets


use Nosh\OmniTax\Facades\OmniTax;

$response = OmniTax::authority('srb')->submit($invoice);   // uses the configured mode

if ($response->isValid()) {
    $srbNumber = $response->invoiceNumber();   // e.g. "33126066A22" — print on the receipt
    $qr        = $response->qr();               // encodes the SRB verification URL (not the number)
}

$response = OmniTax::authority('pra')->submit($invoice);

if ($response->isValid()) {
    $praNumber = $response->invoiceNumber();   // e.g. "9000052011142444901"
    $qr        = $response->qr();               // encodes PRA's verification URL
}

use Nosh\OmniTax\Facades\OmniTax;

$response = OmniTax::authority('kpra')->submit($invoice);

if ($response->isValid()) {
    $kpraId = $response->invoiceNumber();   // KPRA's transaction id, e.g. "8843481"
    $qr     = $response->qr();               // encodes …/api/?pos_id=<posId>&invoice_no=<invoiceNo>
}

return [

    // Default authority when a business hasn't specified one.
    'default' => env('FISCAL_AUTHORITY', 'fbr'),

    // Global sandbox switch (per‑tenant overrides are possible — see §13).
    'sandbox' => env('FISCAL_SANDBOX', true),

    // Transport: 'http' = real HTTPS to the authority; 'mock' = in‑package fake
    // authority (spec‑shaped responses, no token/network) for local dev & tests.
    'transport' => env('FISCAL_TRANSPORT', 'http'),

    // The "seller" identity for single‑business installs (see §6a).
    'seller' => [
        'ntncnic'  => env('FISCAL_SELLER_NTNCNIC'),
        'name'     => env('FISCAL_SELLER_NAME'),
        'province' => env('FISCAL_SELLER_PROVINCE'),
        'address'  => env('FISCAL_SELLER_ADDRESS'),
    ],

    // How per‑business credentials are resolved (§13).
    // 'env'      → use the .env values above (single business)
    // 'database' → look them up per tenant from the fiscal_credentials table
    // 'callback' → resolve from your own store via OmniTax::resolveCredentialsUsing()
    'credentials' => [
        'driver' => env('FISCAL_CREDENTIALS_DRIVER', 'env'),
        'encrypt' => true, // tokens are encrypted at rest
    ],

    // Reliability & QR
    'timeout'        => env('FISCAL_TIMEOUT', 30),
    'retry_attempts' => env('FISCAL_RETRY_ATTEMPTS', 3),
    'queue'          => env('FISCAL_QUEUE', 'fiscal-invoices'),

    'qr_code' => [
        'version'    => '2.0',
        'size'       => '25x25',
        'dimensions' => '1.0x1.0 Inch',
        'render'     => true, // let the package produce a PNG/SVG for you
    ],

    'logging' => [
        'enabled' => env('FISCAL_LOGGING_ENABLED', true),
        'channel' => env('FISCAL_LOG_CHANNEL', 'daily'),
        'level'   => env('FISCAL_LOG_LEVEL', 'info'),
    ],

    // One block per authority. Endpoints are pre‑filled from each authority's
    // official spec; you normally only supply the token (via env or database).
    'authorities' => [

        'fbr' => [
            'label' => 'FBR (Federal / PRAL)',
            'token' => env('FISCAL_TOKEN'),
            'urls'  => [
                // Same host for sandbox & production — routing is by token.
                'submit'    => 'https://gw.fbr.gov.pk/di_data/v1/di/postinvoicedata',
                'submit_sb' => 'https://gw.fbr.gov.pk/di_data/v1/di/postinvoicedata_sb',
                'validate'    => 'https://gw.fbr.gov.pk/di_data/v1/di/validateinvoicedata',
                'validate_sb' => 'https://gw.fbr.gov.pk/di_data/v1/di/validateinvoicedata_sb',
                'reference' => 'https://gw.fbr.gov.pk/pdi/v1/',
                'statl'     => 'https://gw.fbr.gov.pk/dist/v1/',
            ],
        ],

        // Provincial authorities share the same driver contract; their
        // endpoints are filled in as each one is enabled.
        'pra'  => ['label' => 'Punjab Revenue Authority',        'token' => env('FISCAL_PRA_TOKEN')],
        'srb'  => ['label' => 'Sindh Revenue Board',             'token' => env('FISCAL_SRB_TOKEN')],
        'kpra' => ['label' => 'KP Revenue Authority',            'token' => env('FISCAL_KPRA_TOKEN')],
        'bra'  => ['label' => 'Balochistan Revenue Authority',   'token' => env('FISCAL_BRA_TOKEN')],
    ],
];

use Nosh\OmniTax\Facades\OmniTax;
use Nosh\OmniTax\Builders\InvoiceBuilder;
use Nosh\OmniTax\Builders\LineItemBuilder;

// 1. Build the two things the customer ordered.
$karahi = (new LineItemBuilder())
    ->description('Chicken Karahi (Full)')
    ->quantity(1)
    ->unitPrice(1800.00)      // price excluding tax
    ->taxRate('16%')          // provincial services rate (example)
    ->saleType('Services')
    ->build();

$naan = (new LineItemBuilder())
    ->description('Garlic Naan')
    ->quantity(4)
    ->unitPrice(80.00)
    ->taxRate('16%')
    ->saleType('Services')
    ->build();

// 2. Build the invoice for this table.
$invoice = (new InvoiceBuilder())
    ->type('Sale Invoice')
    ->date(now())
    // Seller can be omitted if set in config (§6a); shown here for clarity.
    ->seller('0786909', 'Karachi Grill House', 'Sindh', 'Karachi')
    // Walk‑in customer → unregistered buyer, no NTN needed.
    ->walkInCustomer()
    ->addItem($karahi)
    ->addItem($naan)
    ->build();

// 3. Submit to the authority in real time.
$response = OmniTax::submit($invoice);

if ($response->isValid()) {
    $fiscalNumber = $response->invoiceNumber();   // e.g. "7000007DI1747119701593"
    $qr           = $response->qr();              // ready to print (see §11)
    // → print the receipt with $fiscalNumber, $qr, and the authority logo
} else {
    foreach ($response->errors() as $error) {
        report("Fiscal rejection: {$error}");     // e.g. "0052 – Invalid HS Code"
    }
}

$check = OmniTax::validate($invoice);

if ($check->isValid()) {
    $response = OmniTax::submit($invoice);
}

$response = OmniTax::authority('pra')->submit($invoice);   // report to Punjab

$response->isValid();          // true when the authority accepted it
$response->invoiceNumber();    // the official fiscal number (null if rejected)
$response->dated();            // authority timestamp
$response->qr();               // QR payload / image (see §11)
$response->errors();           // array of human‑readable errors
$response->itemStatuses();     // per‑line accept/reject detail
$response->raw();              // the authority's raw JSON, for your audit log

// After a successful submit:
$qr = $response->qr();

$qr->payload();   // the string encoded in the QR (the fiscal invoice number)
$qr->png();       // binary PNG at the ng();

$record = OmniTax::for($branch)->report($invoice, reference: "bill:{$bill->id}");

match ($record->status) {
    FiscalInvoice::VALID   => print_fiscal($record->fiscalNumber(), $record->qr()), // accepted
    FiscalInvoice::PENDING => print_pending_note(),   // authority slow/down — queued, retried
    FiscalInvoice::FAILED  => alert($record->last_error), // rejected: fix data/credentials
};

use Nosh\OmniTax\Models\FiscalInvoice;
use Nosh\OmniTax\Jobs\SubmitFiscalInvoice;

// Save first (status: pending), then submit asynchronously.
$record = FiscalInvoice::fromInvoice($invoice);   // your canonical invoice
SubmitFiscalInvoice::dispatch($record);           // onto the 'fiscal-invoices' queue

// Later / elsewhere:
$record->refresh();
$record->status();          // pending | valid | failed
$record->fiscalNumber();    // once accepted
$record->qr();

use Nosh\OmniTax\Support\Feature;

if (OmniTax::for($branch)->supports(Feature::CREDIT_NOTE)) {
    $creditNote = (new InvoiceBuilder())
        ->number("R-{$refund->id}")                                    // its own number
        ->creditNoteFor($bill->number, $original->fiscalNumber())       // your no. + the authority's
        ->addItem(/* the refunded lines */)
        ->build();

    OmniTax::for($branch)->report($creditNote, reference: "bill:{$bill->id}");
}

$check = OmniTax::for($branch)->check();

$check->ok();               // everything passed
$check->failure();          // the first problem, in plain words
$check->checks();           // credentials → seller → authority → validate, each with ok + message
$check->reachedAuthority(); // true only when the authority itself was asked (FBR validate);
                            // PRA/SRB publish no test endpoint, so their check is local

use Nosh\OmniTax\Models\FiscalCredential;

FiscalCredential::updateOrCreate(
    ['tenant_id' => $restaurant->id],
    [
        'authority'      => 'pra',              // Punjab restaurant
        'sandbox'        => false,
        'token'          => $restaurant->pra_token,   // encrypted automatically
        'seller_ntncnic' => $restaurant->ntn,
        'seller_name'    => $restaurant->legal_name,
        'seller_province'=> 'Punjab',
        'seller_address' => $restaurant->address,
    ],
);

$response = OmniTax::for($restaurant)->submit($invoice);

// In a service provider
OmniTax::resolveCredentialsUsing(function ($tenantId) {
    return MyBillingService::fiscalCredentialsFor($tenantId); // returns a FiscalCredential
});

// Your settings controller, on save:
FiscalCredential::updateOrCreate(
    ['tenant_id' => $merchant->auth_uuid, 'authority' => $request->authority],
    [
        'sandbox'         => $request->boolean('sandbox'),
        'token'           => $request->token,           // encrypted automatically
        'seller_ntncnic'  => $request->ntn,
        'seller_name'     => $request->business_name,
        'seller_province' => $request->province,
        'seller_address'  => $request->address,
    ],
);

OmniTax::provinces();     // [['code' => 7, 'name' => 'PUNJAB'], ['code' => 8, 'name' => 'SINDH'], …]
OmniTax::units();         // units of measure
OmniTax::hsCodes();       // harmonised system codes
OmniTax::taxRates();      // rate list
OmniTax::checkStatl($ntn, $date);   // is a party on the STATL blacklist?

use Nosh\OmniTax\Testing\Scenario;

// Build a ready‑made, valid sandbox invoice for a scenario:
$invoice = Scenario::make('SN019');       // a services (restaurant) sale
$response = OmniTax::sandbox()->submit($invoice);

// Discover which scenarios apply to a business type:
Scenario::forBusinessActivity('services');   // ['SN018', 'SN019', …]

use Nosh\OmniTax\Events\{InvoiceSubmitting, InvoiceAccepted, InvoiceRejected};

Event::listen(InvoiceAccepted::class, function (InvoiceAccepted $e) {
    // $e->invoice, $e->response->invoiceNumber() — e.g. email the customer, update the KDS
});

use Nosh\OmniTax\Exceptions\FiscalException;

try {
    $response = OmniTax::for($restaurant)->submit($invoice);
} catch (FiscalException $e) {
    // Transport/auth problems (network, 401, 500)
    Log::error("Fiscal transport error: {$e->getMessage()}", ['status' => $e->getCode()]);
}

// Business rejections don't throw — they come back on the response:
if (! $response->isValid()) {
    foreach ($response->errors() as $error) { /* show/fix */ }
}

interface FiscalAuthorityDriver
{
    public function validate(Invoice $invoice): FiscalResponse;
    public function submit(Invoice $invoice): FiscalResponse;
    public function reference(string $type): array;
}
bash
php artisan vendor:publish --provider="Nosh\OmniTax\OmniTaxServiceProvider" --tag="omnitax-config"
bash
php artisan vendor:publish --provider="Nosh\OmniTax\OmniTaxServiceProvider" --tag="omnitax-migrations"
php artisan migrate
bash
php artisan queue:work --queue=fiscal-invoices
bash
php artisan fiscal:sync                 # all reference data, default authority
php artisan fiscal:sync --type=provinces
php artisan fiscal:sync --authority=pra --force