DEV Community

Building a Zero-Dependency Saudi ZATCA Phase 1 & Phase 2 TLV QR Engine in Python (Decimal-Safe)

When engineering Cloud ERP and POS invoicing platforms for Saudi Arabia and the Gulf, one of the most common causes of silent compliance rejection is floating-point rounding drift and malformed Tag-Length-Value (TLV) Base64 QR payloads under ZATCA (Fatoora) Phase 1 and Phase 2 specifications.

At NBrain (founded by Eng. Nadeem Mohamed Badr in Cairo, Egypt), we recently extracted and open-sourced our clean, zero-dependency Python TLV core as nbrain-zatca-tlv under the MIT license:

Why TLV Encoding Breaks in Production ERP Systems

Every ZATCA QR code encodes UTF-8 fields into strict binary Tag-Length-Value frames before Base64 encoding:

  • Tag 1: Seller Name (UTF-8 Arabic or English)
  • Tag 2: 15-digit VAT Registration Number
  • Tag 3: ISO-8601 UTC Timestamp (YYYY-MM-DDTHH:MM:SSZ)
  • Tag 4: Invoice Total Including VAT (2 decimal places via Decimal, never binary float)
  • Tag 5: VAT Amount (15% standard KSA rate, Decimal-validated)
  • Tags 6–9 (Phase 2 Cryptographic Stamps): XML Invoice Hash, ECDSA Signature, ECDSA Public Key, and ZATCA CSID Cryptographic Stamp

Two subtle bugs frequently break Arabic ERP implementations:

  1. Measuring character length (len(str)) instead of UTF-8 byte length (len(value.encode("utf-8"))) — Arabic characters are 2 bytes in UTF-8, so len() corrupts every tag boundary after Tag 1.
  2. Using Python float for VAT arithmetic (100.10 * 0.15), causing halala rounding mismatches against ZATCA's UBL 2.1 XML validator.

Clean Python Usage (nbrain-zatca-tlv)

from decimal import Decimal
from nbrain_zatca_tlv import ZatcaInvoiceTLV, decode_tlv_base64

invoice = ZatcaInvoiceTLV(
    seller_name="NBrain Enterprise Studio",
    vat_number="300000000000003",
    timestamp="2026-12-05T18:00:00Z",
    invoice_total=Decimal("1150.00"),
    vat_total=Decimal("150.00"),
)

b64_qr = invoice.to_base64()
decoded = decode_tlv_base64(b64_qr)
assert decoded[4] == "1150.00"
assert decoded[5] == "150.00"
Enter fullscreen mode Exit fullscreen mode

Full Production Checklist for Saudi & MENA ERP Teams

When deploying full Phase 2 clearance (B2B) and reporting (B2C) pipelines:

  • Validate every line item and tax total strictly using Decimal with ROUND_HALF_UP.
  • Canonicalize UBL 2.1 XML (C14N 1.1) before computing the SHA-256 invoice hash (Tag 6).
  • Sign with secp256k1 ECDSA and embed the cryptographic stamp returned by ZATCA Fatoora CSID onboarding.
  • Maintain immutable invoice chains (PIH / Previous Invoice Hash) inside PostgreSQL with row-level audit logs.

Built by *Eng. Nadeem Mohamed Badr El-Din** — Founder & CEO of NBrain, specializing in AI Engineering, Clinical Computer Vision (Nabd Masr CXR, 94.99% AUROC, CERN Zenodo DOI), ZATCA Phase 2 Cloud ERP, and 16KB-ready Flutter Enterprise Apps across Egypt & MENA.*

Top comments (0)