A product of NPOST, open to everyone DevelopersGuidesHelp Shqip English Srpski

Developers

NPORTAL connector

How NPORTAL fiscalises its shipments through FISKALIX as a platform integration: set-up, the call for each step of a shipment, a reference PHP client and a test plan.

What the connector does

NPORTAL connects to FISKALIX as a platform integration: one key that acts for every merchant linked to it. When a shipment is paid, for example cash on delivery at the door, NPORTAL asks FISKALIX to fiscalise the sale for the merchant who sold the goods. The receipt carries the merchant's NUI and belongs to the merchant, not to NPOST. NPORTAL stores the receipt id and verification number on the shipment, so a fiscal receipt can be traced from a courier code.

This page describes the integration and gives a reference PHP client. The client is not shipped inside NPORTAL: it is a starting point for the NPORTAL developers, tested against the FISKALIX API shape described in the API reference.

Set-up, step by step

#WhoWhat
1FISKALIX administratorOn Integrations, creates the integration NPORTAL of kind Platform.
2Each merchantHas a FISKALIX account and a point of sale: a test one on the sandbox, and after verification a production one on live.
3FISKALIX administratorLinks the merchants to the NPORTAL integration. A platform key can reach only linked merchants.
4FISKALIX administratorIssues a fx_test_ key for the sandbox and, later, a fx_live_ key for live. Each is shown once. NPORTAL keeps them in its secret store, one per environment, never in the code or logs.
5NPORTALCalls GET /merchants to confirm which merchants and points of sale the key reaches, and registers a webhook endpoint.

Every call names the merchant: "merchant": "<NUI>". A merchant that is not linked, or that does not exist, answers the same 403, so NPORTAL cannot probe which businesses exist.

From shipment to fiscal receipt

In NPORTALCall to FISKALIXKeep on the shipment
Parcel handed over and paid (cash or card at the door, or prepaid)POST /receipts with reference: "NP-<shipment id>"id, verification_no, links.public, status
Courier learns the buyer's number or e-mailPOST /receipts/{id}/deliveries (sms or email), reference NP-<id>-smsThe delivery id
Buyer refuses before handoverNothing: no sale happened, so no receipt is issued.
A handed-over parcel is taken back in fullPOST /receipts/{id}/cancel. The sale must be accepted first; on 422 wait for receipt.accepted and retry.The cancel receipt id
Buyer returns some items later (RMA)POST /receipts/{id}/return with the line numbers and quantitiesThe return receipt id
ATK's answerWebhook receipt.accepted or receipt.rejectedUpdate status; alert on rejected
E-mail or SMS did not arriveWebhook delivery.failedOffer another channel
End of dayGET /reports/summary?merchant=<NUI>&from=&to=Compare with NPORTAL's cash-on-delivery totals
Merchant's balance runs lowWebhook wallet.low_balance; GET /wallet?merchant=Tell the merchant

Field mapping

NPORTALFISKALIX fieldNotes
Merchant's NUImerchantRequired with a platform key.
Shipment idreferenceStable per shipment: it makes retries safe. Use a different one for each cancel, return and delivery.
Courier codeoperatorUp to 50 characters.
Parcel contentsitems[]unit_price includes VAT. Each item needs a VAT class: A, C, D or E.
Delivery feean extra itemIf the buyer pays a fee, send it as its own item with its VAT class, so the total matches what was paid.
Amount collectedpayments[]cash or card. The payments must add up to the total of the items, or the call answers 422.
Buyer phone / e-mailnotifyOptional on the sale, or later through /deliveries.

Reference client (PHP 7.4+)

One file, no dependencies besides curl and json. It throws FiskalixException with the HTTP status and, for a 422, the field errors; retryable() says when sending the same call again is safe.

PHP
<?php
/**
 * Minimal FISKALIX client for NPORTAL. PHP 7.4+, needs ext-curl and ext-json.
 * A reference implementation: copy it, adapt the naming to NPORTAL, keep the idempotent references.
 */
final class FiskalixException extends RuntimeException
{
    /** @var int HTTP status, 0 when no answer came */
    public $status;
    /** @var array field => messages, from a 422 */
    public $errors;

    public function __construct(string $message, int $status, array $errors = [])
    {
        parent::__construct($message, $status);
        $this->status = $status;
        $this->errors = $errors;
    }

    /** True when sending the same call again, with the same reference, is safe and may help. */
    public function retryable(): bool
    {
        return $this->status === 0 || $this->status >= 500 || $this->status === 429;
    }
}

final class FiskalixClient
{
    private $base;
    private $key;

    public function __construct(string $baseUrl, string $apiKey)
    {
        $this->base = rtrim($baseUrl, '/') . '/api/v1';
        $this->key = $apiKey;
    }

    /** The merchants this key may act for, with their points of sale. */
    public function merchants(): array
    {
        return $this->call('GET', '/merchants');
    }

    /**
     * Fiscalise a sale. $reference must be the same for the same shipment every time you retry.
     * Prices are VAT inclusive, as decimal text: "19.95".
     */
    public function sale(string $nui, string $reference, string $operator, array $items, array $payments, ?array $notify = null): array
    {
        $body = [
            'merchant' => $nui,
            'reference' => $reference,
            'operator' => $operator,
            'items' => $items,
            'payments' => $payments,
        ];
        if ($notify !== null) {
            $body['notify'] = $notify;
        }

        return $this->call('POST', '/receipts', $body);
    }

    public function receipt(int $id): array
    {
        return $this->call('GET', '/receipts/' . $id);
    }

    public function cancel(int $id, string $operator, ?string $reference = null): array
    {
        return $this->call('POST', '/receipts/' . $id . '/cancel', array_filter(['operator' => $operator, 'reference' => $reference]));
    }

    /** $lines: [['line' => 1, 'quantity' => '1']]; an empty list returns everything that is left. */
    public function returnItems(int $id, string $operator, array $lines = [], ?string $reference = null): array
    {
        $body = array_filter(['operator' => $operator, 'reference' => $reference]);
        if ($lines) {
            $body['items'] = $lines;
        }

        return $this->call('POST', '/receipts/' . $id . '/return', $body);
    }

    /** Send an existing receipt by 'email' or 'sms', for example once the courier knows the number. */
    public function sendReceipt(int $id, string $channel, string $recipient, string $reference): array
    {
        return $this->call('POST', '/receipts/' . $id . '/deliveries', ['channel' => $channel, 'recipient' => $recipient, 'reference' => $reference]);
    }

    public function summary(string $nui, string $from, string $to): array
    {
        return $this->call('GET', '/reports/summary', null, ['merchant' => $nui, 'from' => $from, 'to' => $to]);
    }

    private function call(string $method, string $path, ?array $body = null, array $query = []): array
    {
        $url = $this->base . $path . ($query ? '?' . http_build_query($query) : '');
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_CUSTOMREQUEST => $method,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 20,
            CURLOPT_HTTPHEADER => [
                'Authorization: Bearer ' . $this->key,
                'Accept: application/json',
                'Content-Type: application/json',
            ],
        ]);
        if ($body !== null) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body, JSON_UNESCAPED_UNICODE));
        }
        $raw = curl_exec($ch);
        $status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
        $error = curl_error($ch);
        if (PHP_VERSION_ID < 80000) {
            curl_close($ch);
        }

        if ($raw === false) {
            throw new FiskalixException('No answer from FISKALIX: ' . $error, 0);
        }
        $data = json_decode($raw, true);
        if ($status >= 400) {
            throw new FiskalixException((string) ($data['message'] ?? 'HTTP ' . $status), $status, $data['errors'] ?? []);
        }

        return is_array($data) ? $data : [];
    }
}

Cash on delivery with the client

PHP
<?php
$fx = new FiskalixClient('https://sandbox.fiskalix.com', getenv('FISKALIX_KEY'));

// Cash on delivery: the courier hands over the parcel and takes the money.
$receipt = $fx->sale(
    '811397703',                       // the NUI of the merchant who sold the goods
    'NP-' . $shipment['id'],           // one reference per shipment: a retry returns the same receipt
    'courier-' . $courier['code'],
    array_map(function ($line) {
        return ['name' => $line['title'], 'unit_price' => number_format($line['price'], 2, '.', ''),
                'quantity' => (string) $line['qty'], 'vat' => $line['vat_class']];
    }, $shipment['lines']),
    [['type' => 'cash', 'amount' => number_format($shipment['cod_total'], 2, '.', '')]]
);

// Keep what NPORTAL needs: the receipt id, its public page and the verification number.
$shipment['fiscal'] = [
    'receipt_id' => $receipt['id'],
    'verification_no' => $receipt['verification_no'],
    'page' => $receipt['links']['public'],
];

// The courier learns the buyer's number at the door:
$fx->sendReceipt($receipt['id'], 'sms', $buyerPhone, 'NP-' . $shipment['id'] . '-sms');

Failure handling

  • Never hold the parcel for ATK. A sale answers at once with a signed receipt and status: "queued". Show the buyer and the courier the receipt immediately; ATK's acceptance follows and arrives as a webhook. If ATK is unreachable the receipt is reported again for up to 48 hours.
  • Timeouts and 5xx: send the same call again with the same reference. It returns the same receipt and never issues a second one.
  • 422: fix the data, do not retry unchanged. The message names the problem: a total that does not match, an unknown payment type, a merchant without a point of sale.
  • 403: the merchant is not linked to NPORTAL, or is suspended. Do not retry.
  • 401: the key is wrong or was revoked. Alert the NPORTAL operators.
  • Rejected by ATK: the receipt keeps status: "rejected" and ATK's reason in atk.error. It is never edited; fix the cause and issue a new sale with a new reference.

Receiving webhooks in NPORTAL

Register one endpoint per environment with POST /webhooks for receipt.accepted, receipt.rejected, delivery.failed and wallet.low_balance. Verify the signature on the raw body before reading it (see Verify the signature), answer 200 quickly, and do the work afterwards. Use the receipt's reference (NP-…) to find the shipment, and the event id to ignore a repeated event. If NPORTAL's receiver is on a private network, ask for the allowed ranges or a WireGuard link on the integration's page.

Security checklist

  • One key per environment, in a secret store; rotate by issuing a new key and revoking the old one.
  • Never log a key or a webhook secret, and never expose them to the browser or to couriers' devices. Only NPORTAL's servers call FISKALIX.
  • Verify every webhook signature and reject old timestamps.
  • Show a verification number or link to a buyer only for the shipment they own.
  • Keep sandbox and live apart: a test key cannot reach live receipts, and sandbox sales are never real.

Test plan on the sandbox

  1. GET /merchants lists the test merchants and their points of sale.
  2. A cash-on-delivery sale with two VAT classes returns 201 and, within moments, accepted.
  3. Repeat the same call: 200 and the same receipt id.
  4. Send the receipt by SMS to a test contact; follow it with GET /deliveries/{id}.
  5. Cancel an accepted sale; try to cancel it again and read the 422.
  6. Return one item of a two-item sale, then the other; a further return of the same item must be refused.
  7. Register a webhook, call POST /webhooks/{id}/test, and check your signature code against the ping.
  8. Compare GET /reports/summary for the day with the receipts you issued.

Then ask a FISKALIX administrator for the live key, once the merchants are verified and linked.

Not part of the connector yet

The combined courier label with a fiscal QR, and the verification page where a courier shipping code leads to the fiscal receipt, are planned and not live. The receipt object already carries qr, verification_no and links.public, so NPORTAL can print or link them on its own labels today.