Get a free website audit for your business — Talk to CloudTopia today

ZATCA Phase 2 for Developers: API Integration Checklist

A production-ready ZATCA integration onboards every EGS unit, obtains the correct CSID, generates compliant UBL XML, applies the required stamp and QR logic, clears standard B2B documents before sharing them, and reports simplified B2C documents within 24 hours. It also tests fai

MSBy Mohamad Shahm | محمد شـهم · September 12, 2026 · 9 min read
Developer reviewing ZATCA Phase 2 API integration code
Developer reviewing ZATCA Phase 2 API integration code

A production-ready ZATCA integration onboards every EGS unit, obtains the correct CSID, generates compliant UBL XML, applies the required stamp and QR logic, clears standard B2B documents before sharing them, and reports simplified B2C documents within 24 hours. It also tests failures in the sandbox and archives XML, responses and audit evidence intact.

1. Inventory every EGS unit and document type

Define the boundary of each Electronic Generation Solution unit before designing certificate storage. A unit may be a POS device, a branch service or a central invoice engine. Count operational issuers, not only branches or legal entities, because onboarding state, sequence controls and credentials are tied to the issuing architecture.

List standard tax invoices, simplified tax invoices, credit notes and debit notes. Document the business rule that selects each type. “Customer type” should be validated against buyer data and transaction context, not entered as an unchecked string by the cashier.

ZATCA's official e-invoicing overview says Phase 2 requires the electronic solution to integrate with the authority's systems and generate invoices in the required format. The authority notifies targeted taxpayers in waves, so keep eligibility dates and thresholds outside code and verify them on the official site.

2. Onboard each unit and protect the CSID

Developer reviewing ZATCA Phase 2 API integration code
Developer reviewing ZATCA Phase 2 API integration code

Generate the cryptographic key pair in a controlled environment, then create the CSR with the fields required by ZATCA's security specification. The taxpayer generates an OTP through the Fatoora portal for the onboarding process. Use it to obtain the Compliance CSID for conformance testing.

Run the prescribed compliance documents for the invoice and note types the unit supports. After successful checks, request the Production CSID. Store the private key, certificate and authentication secret in a managed secret store. Never commit them to source control, bake them into a container image or expose them in application logs.

Design renewal, revocation and device replacement before go-live. Maintain a register containing the unit, branch, environment, certificate fingerprint, activation state and operational owner. Do not copy one production identity across independent EGS units merely because they share a VAT registration number.

3. Generate UBL XML, not just valid XML

The invoice is based on UBL 2.1 plus EN 16931 rules and Saudi-specific business rules. A document can be well-formed XML and still fail. Validate its XSD, business rules, data dictionary and local constraints against the latest official Electronic Invoice XML Implementation Standard.

Generate the UUID, invoice sequence reference, issue date and time, currency, supplier, buyer, VAT categories, allowances, charges, totals and referenced documents consistently. Line totals, tax subtotals and payable amounts must reconcile under the required rounding rules. Do not copy display-layer calculations into XML without a deterministic monetary model.

Create golden-file tests for every document type and tax scenario. Run the SDK or validator in continuous integration. Keep the commercial invoice model separate from the UBL mapper so a specification update changes a bounded adapter rather than order, accounting and checkout code.

4. Implement hashes, stamps and sequence state

Developer reviewing ZATCA Phase 2 API integration code
Developer reviewing ZATCA Phase 2 API integration code

Phase 2 protects document integrity and sequence. Calculate the invoice hash using the specified canonicalisation and exclusions. Maintain the Invoice Counter Value and Previous Invoice Hash for each unit. A one-byte difference in canonicalisation, namespace handling or excluded nodes produces a different digest.

Simplified documents are stamped by the taxpayer's solution using the unit's production cryptographic identity before reporting. Standard documents follow the clearance flow; ZATCA validates and returns the cleared document with its stamp and QR data. Treat these as separate pipelines, even if they share the same UBL builder.

Protect the private key and system clock, and make sequence updates atomic. Two workers issuing from the same unit can corrupt ICV and PIH state if they race. Use a transaction, lock or single ordered stream that survives process restarts and supports reconciliation after an uncertain network response.

5. Build and verify the QR payload

The QR code is structured TLV data, not a decorative link to a PDF. Populate it from the same authoritative values used in XML. For simplified documents, the EGS produces the required stamp and QR before reporting. For standard documents, publish the version returned from the clearance service.

Test the QR on the human-readable Arabic and English layouts, thermal prints, screens and PDF/A-3 output. Image scaling and printer density must not make it unreadable. Decode the generated Base64 and TLV in automated tests, then compare each value with the XML and cryptographic output.

The ZATCA Security Features Implementation Standards define the signature and integrity requirements. Keep a release test that rebuilds the digest, verifies the signature chain and decodes the QR before a document can leave the issuing service.

Ask the CloudTopia team on WhatsApp to review your XML and stamping pipeline before production. A proposed readiness audit and sandbox proof starts at SAR 3,900, excluding third-party system fees and accounting or tax treatment decisions.

6. Route clearance and reporting correctly

Developer reviewing ZATCA Phase 2 API integration code
Developer reviewing ZATCA Phase 2 API integration code

The endpoints are not interchangeable. They differ in timing, who applies the final stamp, what can be delivered to the buyer and how failure affects the business transaction.

Item

Clearance — standard B2B documents

Reporting — simplified B2C documents

Submission time

Before the cleared invoice is shared with the buyer

After issuance and within 24 hours

Successful response

Cleared document with ZATCA stamp and QR, potentially with warnings

Accepted or accepted with warnings, plus validation details

Stamp owner

ZATCA after validation

Taxpayer's EGS before reporting

Failure route

Do not treat the draft as cleared; correct errors and resubmit before delivery

Preserve the issued document and sequence, correct the cause and report under the official procedure

Connectivity impact

Hold final delivery or apply the officially approved contingency

Queue durably and transmit when connectivity returns within the reporting deadline

Do not map HTTP 200 directly to “compliant.” Parse the response body, validation status, warnings, request identifier and returned payload. Retry temporary failures with bounded exponential backoff. Before retrying an uncertain request, check the stored state so a successful document is not processed as a new invoice.

7. Engineer for rejected and uncertain requests

Classify failures as business validation, XML/schema, authentication/certificate, connectivity, throttling or platform availability. Each class needs different action. A schema error needs corrected generation; an authentication error needs credential inspection; a timeout needs safe retry and reconciliation, not modified invoice values.

Use one operational pattern:

  1. Record the response code and trace identifier without logging secrets.
  2. Classify the result as permanent, temporary or uncertain.
  3. Prevent duplication with a stable internal document identity and state machine.
  4. Retry temporary errors under a bounded policy with jitter.
  5. Escalate before a reporting deadline or after repeated rejection.
  6. Archive the final response beside the sent and returned XML.

Never let an operator delete a rejected invoice to clean a dashboard. Accounting may require a corrected document or a linked note, and the authorised process should decide the next action while retaining the audit record.

8. Treat the sandbox as an executable contract

The sandbox should prove more than reachability. Test onboarding, renewal, every supported invoice and note, accepted-with-warning responses, hard rejection, expired credentials, disconnects, duplicate calls and PIH sequence recovery. Validate locally with the SDK before calling the API so content and transport failures remain distinguishable.

Use synthetic Saudi business data, not copied customer records. Separate sandbox URLs, CSIDs and secrets from production through protected configuration. Block a build that points production traffic at test credentials or uses a production private key in a developer workstation.

ZATCA's Developer Portal User Manual documents the SDK, web validator, Integration Sandbox and test APIs for onboarding, renewal, reporting and clearance. Make both successful and failed test assertions part of release acceptance.

9. Archive the document and the evidence

Store the original XML, cleared XML where applicable, safe request metadata, API response, validation result, trace identifiers and timestamps. A PDF/A-3 representation may embed the XML for human use, but a visual PDF alone does not replace the structured document used for validation and integration.

Use storage that ordinary users cannot silently alter, encryption in transit and at rest, controlled access, backups and tested restoration. Index records by VAT number, invoice number, UUID, document type, EGS unit, branch and final state. Exclude authentication secrets and private keys from application and archive logs.

Link credit and debit notes to the original invoice and retain the event sequence. Confirm the applicable retention policy with legal and tax specialists under current Saudi requirements; do not hard-code a retention period copied from an article without validating the rule for the records concerned.

10. Monitor production as a compliance system

Track accepted, accepted-with-warning and rejected counts; response latency; reporting queue depth; age of the oldest unreported document; clearance availability; and CSID expiry. An alert should identify the unit, class and trace reference without including unnecessary personal or invoice data.

Version the UBL mapper, validation rules and published specification used for each release. Monitor ZATCA's developer pages for changes, then rerun the golden suite before deployment. Convert persistent warnings into engineering work rather than dashboard noise; a future rules update can turn a tolerated warning into rejection.

The checklist is complete only when a sale can be traced from the source event to the archived response. Your team should be able to show which unit issued the invoice, which CSID applied, what XML was sent, what the platform returned and what the customer received.

Message the CloudTopia team on WhatsApp for implementation from sandbox to production. The team works from Arabic and English ZATCA documentation, quotes in SAR and transfers the integration source code to the client under contract with a defined test scope.

Frequently asked questions

What is a CSID?

A Cryptographic Stamp Identifier links an invoicing-solution unit to the taxpayer through a trusted certificate. Developers first use a Compliance CSID for required conformance tests, then obtain the Production CSID for live work. Protect the related private key, monitor renewal and revocation, and do not casually share one identity across independent units.

What is the difference between clearance and reporting?

Clearance normally applies to standard B2B tax invoices: ZATCA must validate and return the cleared document before it is shared with the buyer. Reporting applies to simplified B2C invoices stamped by the taxpayer's solution and submitted within 24 hours. They use different API routes, timing rules, stamp responsibilities and failure handling.

Can I integrate ZATCA myself or do I need a vendor?

You can build the integration internally if your team can own UBL XML, cryptography, certificate lifecycle, tax-document rules, resilient queues, monitoring and evidence retention. ZATCA says taxpayers may use a compliant provider even if it is not on the indicative list. The taxpayer remains responsible for compliance, so independent review is prudent.

What format do ZATCA invoices use?

ZATCA electronic invoices use structured XML based on UBL 2.1, with EN 16931 rules and Saudi-specific requirements published by the authority. A PDF/A-3 representation can embed the XML for human reading when needed. A plain PDF or image is insufficient because validation, stamping and API exchange depend on structured XML fields.

Read also

Build with CloudTopia

Need a CRM, ERP, or dashboard built around your workflow?

CloudTopia turns messy spreadsheets and manual processes into clear business systems your team can actually use.

Share this article

محمد شهم - mohamad shahm

Written by

Mohamad Shahm | محمد شـهم

Founder & Lead Engineer

Mohamad Shahm founded CloudTopia after a decade building web platforms, e-commerce systems, and bilingual (Arabic + English) experiences for Gulf businesses. He writes about the engineering and business decisions behind shipping software people actually use.

Keep exploring

Related articles