E-invoicingNo. 09
The ZATCA error that only shows up after you pass compliance
ZATCA Phase 2 in plain C#: the hash Fatoora recomputes, the ECDSA stamp, nine QR tags, offline hash chains, and the traps that pass compliance and fail when you report.


In this article
Six sample documents went to ZATCA, and six came back accepted. The till traded its compliance certificate for a production one, and its counter went back to zero. The next call was routine: report a simplified invoice to the sandbox.
It came back refused, with one code: signed-properties-hashing.
The same signing code had just passed six times. It passed because the compliance certificate never checks that digest. The production certificate does, and ZATCA computes it from text that appears nowhere in your invoice.
I built ZATCA Phase 2 into FinyX-ERP as a small library: about 1,700 lines of C#, .NET's own cryptography, no third-party signing package. By the end of this article you will know every byte ZATCA recomputes, the only order you can produce them in, and the traps that look right on your machine and fail at Fatoora. The code is shortened from the library, ready to lift.
In short
- ZATCA discards your hash and recomputes it from the XML you send. Write the invoice in one exact form, then hash the final text yourself before anything leaves the till.
- Two digests use ZATCA's own format: SHA-256 as lowercase hex, then Base64. One of them is computed over text ZATCA rebuilds, and only a production certificate checks it.
- QR tag 3 is the invoice's own Saudi date and time, with no
Z. The signing time is UTC, with aZ. One document carries two clocks.
Fatoora does all your work again
The invoice is UBL 2.1 XML. The till hashes it, signs the hash with a key whose certificate ZATCA issued to that till alone, links it to the invoice before it, and sends it to Fatoora.
Then Fatoora repeats the work. It strips your signature, recomputes the hash, verifies your signature over it, and reads your QR back against the invoice. Your bytes have to survive someone else's code.
Who buys decides how the invoice travels:
| Simplified (B2C) | Standard (B2B) | |
|---|---|---|
InvoiceTypeCode name |
0200000 |
0100000 |
| Who signs | the till | the till, then ZATCA clears it |
| When ZATCA sees it | reported within 24 hours | cleared before the buyer gets it |
| QR the customer gets | the till's own | the one in ZATCA's cleared XML |
| QR tag 9 | yes | no |
| Endpoint | invoices/reporting/single |
invoices/clearance/single |
FinyX-ERP picks the kind from the customer: a tax profile means a standard invoice, anyone else gets a simplified one. A sales return becomes a credit note, type 381, naming the original invoice and the reason. A signed invoice is final. The app refuses to edit or delete one, and the only correction is a return with its own signed credit note.
9
QR tags on a simplified invoice
6
sample documents before a production certificate
255
bytes, the most one QR tag can hold
0.01 SAR
enough of a difference for a rejection
Three blocks that are never hashed
A hash cannot cover the signature made from it. So ZATCA removes three blocks before it hashes: ext:UBLExtensions, cac:Signature, and the AdditionalDocumentReference whose ID is QR. It canonicalises what is left and takes SHA-256. Your code must do exactly the same:
public static byte[] Canonicalize(string invoiceXml)
{
// PreserveWhitespace on, DTDs prohibited, no external resolver.
var document = ZatcaXmlReader.Load(invoiceXml);
var ns = ZatcaXmlReader.Namespaces(document);
foreach (var path in new[]
{
"/inv:Invoice/ext:UBLExtensions",
"/inv:Invoice/cac:Signature",
"/inv:Invoice/cac:AdditionalDocumentReference[cbc:ID='QR']",
})
foreach (var node in document.SelectNodes(path, ns)!.Cast<XmlNode>().ToList())
node.ParentNode!.RemoveChild(node);
var c14n = new XmlDsigC14NTransform(includeComments: false);
c14n.LoadInput(document);
using var output = (Stream)c14n.GetOutput(typeof(Stream));
using var buffer = new MemoryStream();
output.CopyTo(buffer);
return buffer.ToArray();
}
// invoice hash = Base64(SHA-256(Canonicalize(xml)))Your hash matches ZATCA's on one condition: once those blocks are cut out, your XML must read the same to both of you. Three rules in the writer guarantee it.
No whitespace between elements. When ZATCA removes the signature block, the indentation around it stays behind, inside what gets hashed, and your hash now depends on how ZATCA's tool cuts. With no whitespace there is nothing to disagree about. The writer runs with Indent = false, and a test fails if the hashed form contains a single line break.
Schema order. UBL is a strict sequence, and one element out of place fails schema validation before any business rule runs. A test signs all six document types (standard and simplified, each as invoice, credit note and debit note) and checks the root's children against the sequence.
Invariant numbers. Amounts always carry two decimals in the invariant culture. A till set to a locale with a decimal comma would otherwise write 15,00.
Two shapes are easy to get wrong. The invoice counter lives inside an element called UUID, and the previous invoice's hash travels as an attachment. Indented here for reading only:
<cac:AdditionalDocumentReference>
<cbc:ID>ICV</cbc:ID>
<cbc:UUID>7</cbc:UUID>
</cac:AdditionalDocumentReference>
<cac:AdditionalDocumentReference>
<cbc:ID>PIH</cbc:ID>
<cac:Attachment>
<cbc:EmbeddedDocumentBinaryObject mimeCode="text/plain">NWZlY2ViNjZm…</cbc:EmbeddedDocumentBinaryObject>
</cac:Attachment>
</cac:AdditionalDocumentReference>The tax total appears twice as well, once with the amount alone and once with the breakdown per category. The standard asks for both.
So far, this is careful formatting. In the next part, the order is forced on you.
Seven steps, one possible order
The hash needs the invoice without its signature. The signature needs the hash. The QR needs both. The signature block needs all three.
- Write the UBLwithout the signature block, the signature element and the QR
- CanonicaliseC14N of exactly what ZATCA will hash
- HashSHA-256 in Base64, also the next invoice's PIH
- SignECDSA on secp256k1, DER-encoded
- Build the QRtags 1 to 9
- Hash the signed propertiessigning time, certificate digest, issuer
- Write the final XMLhash it again and stop if it moved
var unsigned = ZatcaXmlWriter.Write(invoice, totals, signature: null);
var hashBytes = ZatcaHasher.HashBytes(unsigned);
var hash = Convert.ToBase64String(hashBytes);
// SHA256withECDSA over the hash bytes: the hash is hashed again inside the signature.
var signatureValue = Convert.ToBase64String(
privateKey.SignData(hashBytes, HashAlgorithmName.SHA256, DSASignatureFormat.Rfc3279DerSequence));
var qr = ZatcaQr.Build(invoice, totals, hash, signatureValue, certificate);
var extensions = UblExtensions(hash, signedPropertiesHash, signatureValue, certificate, signedProperties);
var signed = ZatcaXmlWriter.Write(invoice, totals, new SignatureParts(extensions, qr));
// Hash the final text the way ZATCA will. If it moved, nothing is sent.
if (ZatcaHasher.Hash(signed) != hash)
throw new InvalidOperationException("The signed invoice's hash differs from what was signed.");The key is on secp256k1, the curve ZATCA issues its certificates on, and it comes from .NET's own ECDsa. The only package I added is Microsoft's System.Security.Cryptography.Xml, for canonicalisation.
That last check earns its four lines: an assembly mistake surfaces on the cashier's screen, before ZATCA can reject an invoice the customer has already taken home.
It still could not have caught the refusal at the top of this article. That digest is computed from text your file does not contain.
The digest compliance never checks
Two digests in the signature use a format of ZATCA's own: SHA-256, written as lowercase hex, then that hex text in Base64. Base64 of the raw digest looks perfectly plausible, and fails.
public static string HexThenBase64(byte[] data) =>
Convert.ToBase64String(Encoding.UTF8.GetBytes(Convert.ToHexStringLower(SHA256.HashData(data))));The first is the certificate digest, and its input hides a second trap. It is computed over the certificate's Base64 text, the exact characters inside ds:X509Certificate. Hash the DER bytes and you get a different value.
The second is the digest of xades:SignedProperties, the block holding the signing time, the certificate digest, the issuer and the serial number. This is the one that refused me.
ZATCA does not hash that element as it sits in your invoice. It reads the element out and serialises it alone, which adds an xmlns:xades declaration to the element and an xmlns:ds declaration to every ds child, since their real declarations sit on ancestors outside it. Empty elements close as />, with no space.
So the library writes the element as a string, in two copies from one source:
// forHashing: the text ZATCA rebuilds and hashes. Otherwise: the text embedded in the invoice.
var xades = forHashing ? " xmlns:xades=\"http://uri.etsi.org/01903/v1.3.2#\"" : "";
var ds = forHashing ? " xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\"" : "";
return $"<xades:SignedProperties{xades} Id=\"xadesSignedProperties\">"
+ "<xades:SignedSignatureProperties>"
+ $"<xades:SigningTime>{time}</xades:SigningTime>"
+ "<xades:SigningCertificate><xades:Cert><xades:CertDigest>"
+ $"<ds:DigestMethod{ds} Algorithm=\"http://www.w3.org/2001/04/xmlenc#sha256\"/>"
+ $"<ds:DigestValue{ds}>{certificate.Hash}</ds:DigestValue>"
+ "</xades:CertDigest><xades:IssuerSerial>"
+ $"<ds:X509IssuerName{ds}>{issuer}</ds:X509IssuerName>"
+ $"<ds:X509SerialNumber{ds}>{serial}</ds:X509SerialNumber>"
+ "</xades:IssuerSerial></xades:Cert></xades:SigningCertificate>"
+ "</xades:SignedSignatureProperties></xades:SignedProperties>";The embedded copy carries no xmlns attributes. The hashed copy carries them first, ahead of every other attribute. When my embedded copy declared the namespaces itself, ZATCA's rebuilt text stopped matching what I had hashed, and reporting failed.
Watch out
Build this element with XmlWriter and you will typically get <ds:DigestMethod Algorithm="…" xmlns:ds="…" />: the declaration after the attribute, and a space before />. Both differ from the text ZATCA hashes. My library has a test that rebuilds the element the way ZATCA does and compares the digests, so this mistake cannot come back quietly.
Compliance accepts all six samples with this digest wrong. You find out on the first report signed with a production certificate, so send one to the sandbox before you trust anything.
The next trap was a single letter.
Nine tags and one letter
The QR is TLV: one byte for the tag number, one for the length, then the value. The tags are concatenated, and the whole run is encoded in Base64.
| Tag | Value |
|---|---|
| 1 | Seller's registered name |
| 2 | Seller's VAT number |
| 3 | Issue date and time |
| 4 | Total including VAT |
| 5 | VAT total |
| 6 | Invoice hash, as its Base64 text |
| 7 | Signature value, as its Base64 text |
| 8 | Public key, as DER SubjectPublicKeyInfo bytes |
| 9 | ZATCA's signature on the certificate (simplified only) |
Tags 6 and 7 hold the Base64 characters themselves, as UTF-8, never the bytes they decode to.
internal static byte[] Encode(IReadOnlyList<byte[]> values)
{
using var output = new MemoryStream();
for (var index = 0; index < values.Count; index++)
{
var value = values[index];
if (value.Length > byte.MaxValue)
throw new ZatcaValidationException($"QR tag {index + 1} is {value.Length} bytes; the limit is 255.");
output.WriteByte((byte)(index + 1));
output.WriteByte((byte)value.Length);
output.Write(value);
}
return output.ToArray();
}A one-byte length caps every value at 255 bytes. An Arabic letter takes two bytes in UTF-8, so a long Arabic registered name gets there sooner than you would expect, and the library refuses it on the till before it can print a code no scanner can parse. The whole QR is capped at 700 characters.
Now the letter. The invoice's IssueDate and IssueTime are Saudi time, and tag 3 must say exactly the same. Append a Z and you declare that time UTC, which moves it three hours. ZATCA flagged mine with invoiceTimeStamp_QRCODE_INVALID. Tag 3 is now yyyy-MM-dd'T'HH:mm:ss, with no zone at all.
The signing time goes the other way: UTC, ending in Z. My tests pin both clocks for one instant:
The Saudi clock comes from the time zone database. A fixed offset is a safe fallback, because the kingdom has no daylight saving:
static TimeZoneInfo SaudiTime()
{
try { return TimeZoneInfo.FindSystemTimeZoneById("Asia/Riyadh"); }
catch (Exception e) when (e is TimeZoneNotFoundException or InvalidTimeZoneException)
{
return TimeZoneInfo.CreateCustomTimeZone("KSA", TimeSpan.FromHours(3), "KSA", "KSA");
}
}On a standard invoice, the QR on paper is not even yours: ZATCA returns the cleared XML with its own stamp and QR, and FinyX-ERP stores that XML and prints the QR inside it.
That covers the bytes. The next trap is arithmetic, and your accountant will take the other side.
The halala your ledger will defend
ZATCA computes VAT per category, on the summed net of that category, rounding half up. A ledger that rounds VAT on every line and adds the results will disagree.
Three lines of 0.10 SAR at 15% carry 0.015 each, which rounds to 0.02 per line and 0.06 in total. The document's VAT is 0.30 × 15% = 0.045, which rounds to 0.05. One halala apart, and one halala is enough for a rejection. A test holds exactly those numbers.
// Half up, two places. Math.Round's default for decimal is banker's rounding.
public static decimal Round(decimal value) => Math.Round(value, 2, MidpointRounding.AwayFromZero);
// Per category: sum the nets, take off any discount on that category, round once.
var taxable = Round(lines.Sum(line => line.Net) - discountOnThisCategory);
var vat = Round(taxable * rate / 100m);A document discount comes off its own category's base before tax: 100 SAR less 10 is 90 taxable, 13.50 VAT, 103.50 in total. After signing, FinyX-ERP compares ZATCA's totals with what the sale posted, and a one-halala difference refuses the sale and points the owner at the VAT rate setting.
ZATCA answers with BR-KSA codes in English, which a cashier cannot act on, so a validator lists every data problem before signing, at once, in Arabic. A VAT number is 15 digits that start and end with 3 (^3[0-9]{13}3$, BR-KSA-39). A Saudi address needs a four-digit building number and a five-digit postal code. A standard invoice needs the buyer's name and address. A credit or debit note needs the original invoice number and a reason, which goes in PaymentMeans/InstructionNote. The business profile cannot be saved until a sample invoice built from it passes.
Totals must be in riyals. Another currency needs an exchange rate in the XML, which I have not built, so the till refuses it and says so.
Clean data, exact bytes. One thing is still missing: a certificate to sign with.
From a one-time code to a production certificate
The key never leaves the till. Everything else is four calls to ZATCA, on one screen in FinyX-ERP:
- Key and CSRon the till: a secp256k1 key and a request carrying the unit's details
- Compliance certificatethe CSR and a one-time code from the Fatoora portal, sent to compliance
- Six sample documentsstandard and simplified, each as invoice, credit note and debit note, sent to compliance/invoices
- Production certificateproduction/csids with the compliance request ID: the unit is active, its counter at 0
The CSR must match what ZATCA's published OpenSSL configuration produces. The subject holds the unit name, the branch, the business and C=SA. An extension with OID 1.3.6.1.4.1.311.20.2 names the environment: TSTZATCA-Code-Signing for the developer portal, PREZATCA-Code-Signing for simulation, ZATCA-Code-Signing for production. The rest goes into the subject alternative name:
var key = ECDsa.Create(ECCurve.CreateFromValue("1.3.132.0.10")); // secp256k1
csr.CertificateExtensions.Add(new X509Extension(
"2.5.29.17", // subject alternative name
DirectoryName(
("2.5.4.4", request.EgsSerialNumber), // "1-FinyX|2-<version>|3-<unit id>"
("0.9.2342.19200300.100.1.1", request.VatNumber),
("2.5.4.12", request.InvoiceTypes), // "1100": standard and simplified
("2.5.4.26", request.Location),
("2.5.4.15", request.Industry)),
critical: false));Note
ZATCA's configuration labels the serial number SN. To OpenSSL, SN is the short name for surname, OID 2.5.4.4, and serialNumber is a different attribute. The request has to carry what OpenSSL actually writes, so mine uses 2.5.4.4.
Three encodings on the wire are easy to get backwards:
- The CSR goes as Base64 of the whole PEM text, header lines included.
- The
binarySecurityTokenthat comes back is Base64 of the certificate's Base64 body. Decode it once to get the text you embed inX509Certificateand hash for the certificate digest. - Every later call uses HTTP Basic: the token as it arrived for the user name, the secret for the password, plus
Accept-Version: V2.
The private key and the secret are stored encrypted with Windows DPAPI, so a copy of the database on another computer cannot sign as this till. If a sample fails, the next attempt resumes from the compliance certificate without a second one-time code. When the production certificate arrives, the counter returns to zero and the chain is cleared, because the samples were never real invoices.
Which leaves one question: what is a chain, and why does every till need its own?
One chain per till
Every cashier device is its own e-invoicing unit (EGS), with its own key, counter and hash chain. A till has to keep selling when the internet drops, so it can never wait on another device to learn its next number.
Two references form the chain. ICV is the unit's counter, starting at 1. PIH is the previous document's hash. The first document has no predecessor, so the standard defines one: SHA-256 of the text 0, in the hex-then-Base64 format. Hard-code it, and test it:
public const string FirstPreviousHash =
"NWZlY2ViNjZmZmM4NmYzOGQ5NTI3ODZjNmQ2OTZjNzljMmRiYzIzOWRkNGU5MWI0NjcyOWQ3M2EyN2ZiNTdlOQ==";
// The check: HexThenBase64(Encoding.UTF8.GetBytes("0")) == FirstPreviousHash- Invoice 1ICV 1, PIH = hash of "0"
- Invoice 2ICV 2, PIH = hash of invoice 1
- Invoice 3ICV 3, PIH = hash of invoice 2
Signing happens inside the sale's own database transaction, so the XML, hash and QR exist the moment the receipt prints. A unique index on unit and counter, plus a concurrency token on the unit, stops two simultaneous sales on one till from taking the same number.
Sending happens later, from a queue that runs every two minutes while the app is open:
private static readonly TimeSpan[] RetryDelays =
[
TimeSpan.FromMinutes(1),
TimeSpan.FromMinutes(5),
TimeSpan.FromMinutes(15),
TimeSpan.FromHours(1),
TimeSpan.FromHours(3), // and every 3 hours after that
];It reads ZATCA's answers by what they mean. A network error, a 5xx or an empty body says nothing about the invoice: wait and retry. A 401 or 403 waits too, with a reason telling the owner to onboard the till again. A 200 or 202 with no errors is an acceptance; warnings are stored, never blocking. A rejection with reasons is final, because the same signed XML would get the same verdict, so the document is marked rejected and corrected with a credit note.
ZATCA reads a unit's chain in order. Before a standard invoice is cleared for printing, every earlier pending document from that till goes first. Printing waits up to 20 seconds; after that, the receipt prints as an internal copy marked as awaiting clearance and not for the buyer, and the queue finishes the job.
One lock covers both paths. The queue and the clearance at print time never send the same document at once, because ZATCA refuses a duplicate, and an invoice it had just cleared would then be recorded as rejected.
Reporting also ignores the FinyX-ERP licence. A business that stops reporting invoices it has already issued is the one that gets fined, so an expired licence never blocks it.
The list I keep next to the code
- Onboard a unit in the sandbox in week one. My ten offline checks need no network, but ZATCA's recomputation is the only judge that counts.
- Report with a production certificate before you trust anything.
- One XML form: no whitespace, schema order, invariant numbers. Hash the final text and stop if it moved.
SignedPropertiesas a string, twice: noxmlnsin the invoice, declarations first in the hashed copy,/>with no space.- Digests as SHA-256, lowercase hex, then Base64; the certificate's over its Base64 text.
- Tag 3 in Saudi time with no
Z, signing time in UTC with one, tags 6 and 7 as Base64 text. - Half-up rounding, VAT per category from the summed net.
- One unit per device, one sender at a time, earlier documents first.
- Samples calling
gw-apic-gov.gazt.gov.saare stale: that gateway closed in September 2025, and the current one isgw-fatoora.zatca.gov.sa.
The cryptography in Phase 2 is textbook. Everything that refused me, or would have, was formatting and arithmetic: a namespace in the wrong place, one letter after a time, a halala rounded the other way. Get those bytes exact, every time, on a till that may be offline when the customer pays. That is the whole job.
To check tag 3 on your own receipts, paste a QR's text into the ZATCA QR tool, which decodes every tag from 1 to 9; if you would rather have all of this built into your system, that is my ZATCA e-invoicing service.
Share







