Skip to content

Testing the package (sandbox test plan) ​

A step-by-step plan to try every feature against ZATCA's developer portal (sandbox). Nothing in the sandbox is legally reported. Work through it in order: later steps use what earlier steps created.

Each step lists what to run and what you should see. Tick it off when it matches; if it doesn't, the Troubleshooting page covers the usual causes.

Two terminals

Keep a worker running in a second terminal for the whole session:

bash
php artisan queue:work --queue=zatca-b2c-reporting,zatca-b2b-clearance,zatca-b2b-generation,zatca-b2c-retry,zatca-b2b-retry

PHP snippets below are meant for php artisan tinker (or a test route / controller in your app). Start each tinker session with use CodingTriplets\Zatca\Laravel\Facades\Zatca;.

0. Preparation ​

#DoExpect
0.1Install and configure as in Installation. .env: ZATCA_ENVIRONMENT=sandbox, ZATCA_ENCRYPTION_KEY=…, a queue connection other than sync—
0.2php artisan migrateAll zatca_* tables created, no errors
0.3Windows/WAMP only: ZATCA_CA_BUNDLE=C:/path/to/cacert.pemNo cURL error 60 later
0.4php artisan list zatca14 commands, including zatca:devices:import

1. Company, stores and devices from code ​

php
$company = Zatca::companies()->create([
    'external_ref' => 'C-100',
    'name' => 'Maximum Speed',
    'legal_name' => 'Maximum Speed Tech Supply LTD',
    'vat_number' => '399999999900003',
    'crn' => '1010010000',
    'address' => ['street' => 'Prince Sultan', 'building_number' => '2322', 'district' => 'Al-Murabba',
                  'city' => 'Riyadh', 'postal_code' => '23333'],
    'stores' => [
        ['code' => 'RYD', 'name' => 'Riyadh Branch', 'external_ref' => 'S-1'],
        ['code' => 'DMM', 'name' => 'Dammam Branch', 'external_ref' => 'S-2'],
    ],
]);
#DoExpect
1.1Run the snippetA Company with external_ref = C-100; 2 rows in zatca_branches
1.2Run it againSame company ID; still 1 company and 2 stores (idempotent)
1.3Zatca::companies()->createStore('C-100', ['code' => 'JED', 'name' => 'Jeddah', 'external_ref' => 'S-3'])A third store

2. Device import (CSV / Excel) ​

Download the sample file devices.csv and put it in storage/app/devices.csv. It references the company and stores above by your own IDs (C-100, S-1, S-2), and has no OTP column.

#DoExpect
2.1php artisan zatca:devices:import storage/app/devices.csv --validateAll rows valid except row 4 (failed: unknown store S-9). Nothing saved
2.2php artisan zatca:devices:import storage/app/devices.csv3 × created, 1 × failed; exit code 1 because of the failed row
2.3Run 2.2 again3 × existing (and the same failed row) — no duplicates
2.4php artisan zatca:devicesPOS-01, POS-02 (B2C only, 0100) and ERP-01 (B2B only, 1000) with status REGISTERED
2.5Optional, Excel: composer require openspout/openspout, open the CSV in Excel, save as .xlsx, import itSame result as 2.3
2.6From code: Zatca::devices()->import(storage_path('app/devices.csv'))->toArray()Same report as an array

3. Onboarding ​

The sandbox OTP is always 123345.

#DoExpect
3.1Zatca::devices()->onboardMany([['device' => 'POS-01', 'otp' => '123345'], ['device' => 'ERP-01', 'otp' => '123345']])->counts()['onboarded' => 2] (a few seconds per device)
3.2php artisan zatca:device:onboard <id of POS-02> and enter 123345Device ACTIVE
3.3Zatca::devices()->onboard('POS-01', '000000')Refused: the device is already active (use renewal instead)
3.4php artisan zatca:devicesAll three ACTIVE with a certificate expiry date
3.5Search zatca_device_onboardings and your storage/logs for 123345Not found — OTPs are never stored

Note the device IDs: below, $pos is the ID of POS-01 (B2C) and $erp the ID of ERP-01 (B2B).

4. B2C invoice ​

php
$r = Zatca::b2c()->issue([
    'invoice_number' => 'T-B2C-001',
    'lines' => [['name' => 'Coffee', 'quantity' => '2', 'unit_price' => '12.50', 'vat_category' => 'S', 'vat_rate' => '15']],
], ['device' => $pos])->toArray();
#DoExpect
4.1Run the snippetstatus: true, counter: 1, a qr, processing_status: QUEUED
4.2Wait for the worker, then php artisan zatca:invoice show <invoice_id>processing: REPORTED (sandbox warning certificate-issuer-name is normal)
4.3Run the snippet again (same number)Same invoice_id and counter — idempotent, nothing new issued
4.4Same number, different priceDuplicateInvoice exception
4.5Issue T-B2C-002counter: 2 (next ICV on the device)
4.6Zatca::b2c()->validate([...invalid payload...]) e.g. vat_rate => '0' without categoryErrors with field paths and rule IDs; nothing stored

5. Discounts ​

Issue each as a new B2C invoice (new number each time) and wait for REPORTED.

#Payload partExpect
5.1Line: 'discount' => '1.00' (per unit) on 2 × 12.50Line net 23.00
5.2Line: 'discounts' => [['amount' => '5.00', 'reason' => 'Promotion']] on 3 × 100Line net 295.00, VAT 44.25
5.3Line: 'discounts' => [['percent' => '10', 'reason' => 'Member']] on 3 × 100Line net 270.00
5.4Header: 'allowances' => [['percent' => '5', 'reason' => 'Loyalty', 'vat_category' => 'S', 'vat_rate' => '15']]Allowance 5 % of the S-group net
5.5Two lines, one S 15 % and one Z (exemption_reason_code => 'VATEX-SA-35'), header ['amount' => '33.33', 'reason' => 'Voucher', 'distribute' => true]Two allowances in the XML, totalling 33.33
5.6Line discount larger than the lineValidation error BR-27, nothing issued

See Discounts for the rules.

#DoExpect
6.1Invoice::where('public_id', $id)->first()->lines (model CodingTriplets\Zatca\Laravel\Database\Models\Invoice) for 5.3One line: line_discount 30.00, net_amount 270.00, vat_amount 40.50
6.2->vatBreakdownOne row per VAT category/rate
6.3Add use HasZatcaInvoices; to your own order model; issue with ['device' => $pos, 'source' => $order]$order->zatcaInvoice returns the invoice
6.4Listen to InvoiceAccepted and log $e->sourceType, $e->sourceIdYour model class and ID

7. B2B invoice ​

php
$r = Zatca::b2b()->issue([
    'invoice_number' => 'T-B2B-001',
    'supply_date' => now()->toDateString(),
    'buyer' => ['name' => 'Fatoora Samples LTD', 'vat_number' => '399999999800003',
                'address' => ['street' => 'Salah Al-Din', 'building_number' => '1111', 'district' => 'Al-Murooj',
                              'city' => 'Riyadh', 'postal_code' => '12222', 'country' => 'SA']],
    'lines' => [['name' => 'Consulting', 'quantity' => '10', 'unit_code' => 'HUR', 'unit_price' => '500', 'vat_category' => 'S', 'vat_rate' => '15']],
], ['device' => $erp])->toArray();
#DoExpect
7.1Run the snippet, wait for the workerprocessing: CLEARED
7.2Get the cleared XML as in B2B › Getting the cleared invoiceXML signed by ZATCA
7.3Same payload without buyer.vat_number and without other buyer IDValidation error (buyer identification)
7.4Zatca::b2c()->issue(<any payload>, ['device' => $erp])DeviceUnavailable: ERP-01 is registered for B2B only

8. Credit and debit notes, cancellation ​

#DoExpect
8.1Zatca::invoices()->creditNote(<id of T-B2C-001>, ['invoice_number' => 'T-CN-1', 'lines' => [['name' => 'Coffee', 'quantity' => '1', 'unit_price' => '12.50', 'vat_category' => 'S', 'vat_rate' => '15']]], 'Returned')Credit note reported; original credited_amount 14.38
8.2A second credit note for 2 × 12.50 on the same invoiceOperationNotAllowed: exceeds the amount that can still be credited
8.3Zatca::invoices()->debitNote(...) for 5.00 + VATDebit note reported; creditableAmount() goes up by 5.75
8.4php artisan zatca:invoice cancel <id of T-B2C-002> --reason="Order cancelled"Prints the credit note T-B2C-002-CN; original cancellation_invoice_id set
8.5Cancel it againRefused: already cancelled
8.6Stop the worker; Zatca::b2b()->submit(<B2B payload with a new number>, ['device' => $erp]); then php artisan zatca:invoice discard <id> --reason="Entered twice"; start the workerStatus CANCELLED; no counter used on ERP-01
8.7Cancel a B2B invoice (7.1)A B2B credit note, CLEARED

9. Rejections, retry and correction ​

The sandbox rejects real rule violations only, and the package already blocks most of them locally, so a rejection is not easy to provoke on purpose ⚠. If you get one (or after a network failure), test:

#DoExpect
9.1php artisan zatca:invoice show <id>REJECTED, last error with ZATCA's code
9.2php artisan zatca:invoice correct <id> --file=fixed.json --reason="…"New issuance (new UUID, next counter); after the worker: REPORTED/CLEARED
9.3php artisan zatca:invoice abandon <id> --reason="…" instead of 9.2ABANDONED ⚠ (see Cancelling invoices)
9.4Disconnect the network, issue a B2C invoice, reconnect, waitRETRY_PENDING then REPORTED on its own
9.5php artisan zatca:invoice retry <id> --now on a FAILED invoiceSubmitted again with the identical document

All these paths are also covered by the package's automated tests (composer test).

10. HTTP API (optional) ​

#DoExpect
10.1.env: ZATCA_API_ENABLED=true; add your auth middleware to zatca.api.middlewareRoutes under /api/zatca
10.2POST /api/zatca/b2c/invoices with the 4.1 payload (new number) and header X-Zatca-Device: <id>, see HTTP API201 and the same JSON as toArray()
10.3GET /api/zatca/invoices/{invoice_id}Current statuses

11. Integrity and maintenance commands ​

#DoExpect
11.1php artisan zatca:chain:verifyEvery device chain intact (ICV gap-free, PIH links valid)
11.2php artisan zatca:audit:verifyAudit hash chain intact
11.3php artisan zatca:deadlines:checkNo breaches (all B2C reported)
11.4php artisan zatca:reconcileNothing to re-queue
11.5php artisan zatca:devices:check-expiryNo expiring certificates (sandbox certificates are new)
11.6php artisan schedule:listzatca:outbox:relay, outbox:prune, chain:verify, deadlines:check, reconcile, devices:check-expiry

12. Dashboard ​

Log in to your app as a user with the dashboard permissions (in APP_ENV=local every logged-in user has them, see Dashboard).

#DoExpect
12.1Open /admin/zatcaOverview with the B2B and B2C panels and the numbers of the invoices you created
12.2B2C list → tab Reported, search T-B2COnly matching invoices
12.3Open an invoice, go through every tabLines with discounts (step 5), JSON, issuance with UUID/ICV/hash, submissions, history
12.4Issuances → Download signed XMLAn .xml file
12.5On a reported invoice: Cancel (credit note) with a reasonGreen message; Summary links to the credit note
12.6php artisan zatca:audit:verifyIntact; the cancel appears in zatca_audit_logs with your user ID
12.7Log in as a user without permissions (with APP_ENV=production and a Zatca::auth() callback that returns false)403
12.8View the page sourceNo keys, secrets or OTPs
12.9Companies & stores → add a company and a storeGreen message; the store appears under the company
12.10Devices → Register device for that storeDevice page with status REGISTERED and an OTP form
12.11Enter a wrong OTP (12ab)"The OTP has 6 digits."; the field is empty again
12.12Enter OTP 123345 → OnboardDevice becomes ACTIVE; a compliance certificate and a production certificate are listed
12.13Devices → Import from file, upload devices.csv with Check only ticked (adjust company/store IDs to yours)Report: valid rows and the failing row with its reason; no device created
12.14Upload it again without Check onlyReport created / failed; the new devices are in the list. Upload once more → existing
12.15Errors & warnings (after step 10 there are rejections)The ZATCA errors, linked to their invoices; Groups shows them counted once
12.16Mark as resolved with a noteError disappears from Open; the invoice's unresolved count drops
12.17Queue monitor with the workers stopped, then issue a B2C invoicePending goes up; start the workers, reload → back to 0
12.18Audit history → Verify tamper chain"Audit chain intact"; your onboarding, cancel and resolve actions are listed with your user ID
12.19SettingsYour configuration; no encryption key or credential anywhere
12.20Open a rejected invoice (step 10) → Correct JSON → change the cause → Check only"The corrected JSON is valid. Nothing was saved yet."
12.21Save correction and send with a reasonJSON versions shows v2 with your reason; Issuances shows a second document with a new UUID and the next counter
12.22On a reported invoice → Credit note, change a quantity, issueA 381 document linked to the invoice; Credited on the invoice summary
12.23Credit note with more than the remaining amountRefused ("exceeds the amount that can still be credited"); nothing issued
12.24Debit note with one extra lineA 383 document linked to the invoice
12.25Reports (last 30 days)Daily bars for B2B and B2C; VAT summary net = invoices + debit − credit
12.26Download VAT summary and Download all documents; open in ExcelArabic text readable; one row per document
12.27B2C list → tab Rejected → Export this listOnly the rejected documents

13. Security checks ​

#CheckExpect
13.1zatca_device_keys.encrypted_private_keyEncrypted text, not a PEM key
13.2zatca_certificates.encrypted_secretEncrypted
13.3grep -ri "PRIVATE KEY|123345" storage/logsNothing
13.4Signed XML files on the storage diskNot under public/; no public URL
13.5Invoice events (dump one in a listener)No keys, secrets or OTPs

Run the package's own tests ​

The repository has 160+ automated tests (unit, integration, a fake ZATCA server, golden files compared with the ZATCA SDK):

bash
git clone https://github.com/mranonyms022/laravel-zetca.git && cd laravel-zetca
composer install
composer test                                   # SQLite
ZATCA_TEST_DB=mysql DB_PORT=3306 composer test  # MySQL/MariaDB (database zatca_test)

Not affiliated with or endorsed by ZATCA. Verify regulatory requirements with ZATCA and your tax advisor.