Skip to content

Validate ZATCA invoice XML

Check an invoice before submission and inspect the results to decide what needs fixing. Choose a schema check for XML structure, or the local ZATCA profile for business rules and applicable integrity checks.

Check What it tells you
UBL schema Whether the XML conforms to the bundled invoice schema
Local ZATCA profile Business-rule findings, applicable signature/QR checks, and which stages were covered

Neither check establishes ZATCA gateway acceptance or certificate issuer trust. Building, parsing, or signing an invoice does not automatically run the full local profile.

Prepare the inputs

Save invoice.xml in your working folder. For the local ZATCA check, also save previous-hash.txt. This file supplies the known predecessor context for this demonstration invoice. For real invoices, use the previous invoice's hash from your trusted invoice history; do not copy the current document's claimed predecessor value as independent evidence.

Validate the original XML. Parsing and reserializing it first can change the document being checked. All schemas are bundled; the check does not contact a gateway.

The sample is unsigned: it is useful for a successful schema check and for exploring ZATCA findings. Do not expect its full local report to pass signature checks.

Run the example

Choose your language, then follow its setup and run instructions.

Install Rust and Cargo, then create a project:

cargo new fatoority-guide
cd fatoority-guide
cargo add fatoora-core

Also add the JSON serializer used to print the report:

cargo add serde_json

Save the code below as src/main.rs. Put the input files in the project root and run:

cargo run

Download this example.

use fatoora_core::invoice::validation::{Validator, ZatcaValidationOptions};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let validator = Validator::new();
    let xml = std::fs::read_to_string("invoice.xml")?;
    if std::env::args().any(|arg| arg == "--zatca") {
        let options = ZatcaValidationOptions {
            previous_invoice_hash: Some(std::fs::read_to_string("previous-hash.txt")?.parse()?),
            ..Default::default()
        };
        let report = validator.validate_zatca(&xml, &options)?;
        println!("{}", serde_json::to_string_pretty(&report)?);
        if !report.is_valid() { std::process::exit(1); }
    } else {
        validator.validate_xml(&xml)?;
        println!("XSD valid");
    }
    Ok(())
}

Run the local ZATCA checks

cargo run -- --zatca

The example prints the JSON report and exits nonzero when is_valid is false. Inspect stages for the findings rather than treating all failures as execution errors.

Install the package in your Python environment:

pip install fatoority

Save the code as validation.py beside the input files, then run:

python validation.py

Download this example. See Python setup for package details.

from pathlib import Path
import sys
from fatoora import validate_xml, validate_zatca

xml = Path("invoice.xml").read_text(encoding="utf-8")
if "--zatca" in sys.argv:
    report = validate_zatca(
        xml, previous_invoice_hash=Path("previous-hash.txt").read_text().strip(),
    )
    for finding in report.findings:
        print(finding.severity.value, finding.code, finding.message)
    print(report.to_json())
    sys.exit(0 if report.is_valid else 1)
validate_xml(xml)
print("XSD valid")

Run the local ZATCA checks

python validation.py --zatca

The example prints each finding and the JSON report, and exits nonzero when report.is_valid is false. Inspect report.stages for the findings rather than treating all failures as execution errors.

Use Node.js 22 or later. In a new working folder, install the package:

npm install fatoority

Save the code as validation.mjs beside the input files, then run:

node validation.mjs

Download this example. These examples run in Node.js and can also be adapted to TypeScript. In a browser, replace filesystem reads with your application's file input and configure the WASM asset as described in the browser setup. Keep objects in the WASM instance that created them; do not pass them between workers.

import { readFileSync } from 'node:fs';
import { Xml } from 'fatoority';

const xml = readFileSync('invoice.xml', 'utf8');
if (process.argv.includes('--zatca')) {
  const report = Xml.validateZatca(xml, {
    previousInvoiceHash: readFileSync('previous-hash.txt', 'utf8').trim(),
  });
  console.log(JSON.stringify(report, null, 2));
  process.exitCode = report.isValid ? 0 : 1;
} else {
  Xml.validate(xml);
  console.log('XSD valid');
}

Run the local ZATCA checks

node validation.mjs --zatca

The example prints the JSON report and exits nonzero when is_valid is false. Inspect stages for the findings rather than treating all failures as execution errors.

Use the .NET 8 SDK or later. Create a console application:

dotnet new console -n FatoorityGuide
cd FatoorityGuide
dotnet add package Fatoority

Save the code as Program.cs. Put the input files beside the project file, then run:

dotnet run

Download this example. The using declarations release native objects. Check the supported .NET platforms before deployment.

using Fatoora;
using System.Text.Json;

string xml = File.ReadAllText("invoice.xml");
if (args.Contains("--zatca"))
{
    string options = JsonSerializer.Serialize(new {
        previous_invoice_hash = File.ReadAllText("previous-hash.txt").Trim()
    });
    using var report = Xml.ValidateZatca(xml, options);
    Console.WriteLine(report.ToJson());
    Environment.ExitCode = report.IsValid ? 0 : 1;
}
else
{
    Xml.Validate(xml);
    Console.WriteLine("XSD valid");
}

Run the local ZATCA checks

dotnet run -- --zatca

The example prints the JSON report and exits nonzero when is_valid is false. Inspect stages for the findings rather than treating all failures as execution errors.

For this desktop example, use JDK 17+ and Gradle 8. Create an empty project folder and download build.gradle.kts and settings.gradle.kts into it. The build uses Maven Central and includes the JSON library needed by the validation example.

Save the code as src/main/kotlin/Main.kt (create the folders first). Put the input files in the project root and run:

gradle run

Download this example. use releases each native object. For an existing project, or Android's separate artifact and file handling, follow Kotlin setup. The binding also supports Maven; its dependency coordinates are listed there.

import com.fatoora.*
import java.io.File
import kotlinx.serialization.json.*

fun main(args: Array<String>) {
    val xml = File("invoice.xml").readText()
    if (args.contains("--zatca")) {
        val hash = File("previous-hash.txt").readText().trim()
        val options = buildJsonObject { put("previous_invoice_hash", JsonPrimitive(hash)) }.toString()
        Xml.validateZatca(xml, options).use { report ->
            println(report.toJson())
            if (!report.isValid) kotlin.system.exitProcess(1)
        }
    } else {
        Xml.validate(xml)
        println("XSD valid")
    }
}

Run the local ZATCA checks

gradle run --args="--zatca"

The example prints the JSON report and exits nonzero when is_valid is false. Inspect stages for the findings rather than treating all failures as execution errors.

Use JDK 17+ and Maven for this walkthrough. In an empty project folder, save this pom.xml. It includes the library, a JSON parser for the validation example, and the plugin used by the run command.

Save the code as src/main/java/Guide.java (create the folders first). Put the input files beside pom.xml, then run:

mvn compile exec:java

Download this example. Try-with-resources releases native objects. The library itself supports Java 8+; see Java setup for platform prerequisites, Gradle installation, and Android configuration.

import com.fatoora.*;
import java.nio.file.*;
import java.nio.charset.StandardCharsets;

public class Guide {
    static String read(String path) throws java.io.IOException {
        return new String(Files.readAllBytes(Paths.get(path)), StandardCharsets.UTF_8);
    }
    public static void main(String[] args) throws Exception {
        String xml = read("invoice.xml");
        if (java.util.Arrays.asList(args).contains("--zatca")) {
            com.google.gson.JsonObject options = new com.google.gson.JsonObject();
            options.addProperty("previous_invoice_hash", read("previous-hash.txt").trim());
            try (ZatcaValidationReport report = Xml.validateZatca(xml, options.toString())) {
                System.out.println(report.toJson());
                if (!report.isValid()) System.exit(1);
            }
        } else {
            Xml.validate(xml);
            System.out.println("XSD valid");
        }
    }
}

Run the local ZATCA checks

mvn compile exec:java -Dexec.args="--zatca"

The example prints the JSON report and exits nonzero when is_valid is false. Inspect stages for the findings rather than treating all failures as execution errors.

Download and extract the fatoora-ffi-* archive for your platform from GitHub Releases. Save the example as validation.c in the extracted folder, beside the input files.

On Linux, compile the example and the supplied adapter, then run:

cc -std=c11 -Iinclude validation.c src/fatoora.c -L. -lfatoora_ffi -Wl,-rpath,'$ORIGIN' -o validation
./validation invoice.xml

Download this example. For other platforms, follow the C installation and linking reference. The cleanup section releases handles and returned strings, including on failure.

#include "fatoora.h"
#include <stdio.h>
#include <stdlib.h>

static char *read_xml(const char *path) {
    FILE *file = fopen(path, "rb");
    if (!file) return NULL;
    char *xml = NULL;
    if (fseek(file, 0, SEEK_END)) goto done;
    long size = ftell(file);
    if (size < 0 || size > 1024 * 1024) goto done;
    rewind(file);
    xml = malloc((size_t)size + 1);
    if (!xml) goto done;
    if (fread(xml, 1, (size_t)size, file) != (size_t)size) {
        free(xml);
        xml = NULL;
    } else {
        xml[size] = '\0';
    }
done:
    fclose(file);
    return xml;
}

int main(int argc, char **argv) {
    if (argc != 2 && argc != 3) {
        fprintf(stderr, "Usage: %s invoice.xml [validation-options.json]\n", argv[0]);
        return 1;
    }
    FatooraError *error = NULL;
    char *xml = read_xml(argv[1]);
    if (!xml) {
        fputs("Unable to read invoice XML.\n", stderr);
        return 1;
    }
    bool valid = false, complete = false;
    char *options = NULL, *json = NULL;
    FatooraZatcaValidationReport *report = NULL;
    FatooraStatus status = FATOORA_OK;
#define TRY(call) do { status = (call); if (status != FATOORA_OK) goto cleanup; } while (0)
    /* Validate original XML; parsing/reserializing would change the input. */
    if (argc == 3) {
        options = read_xml(argv[2]);
        if (!options) { fputs("Unable to read validation options.\n", stderr); goto cleanup; }
        TRY(fatoora_xml_validate_zatca(xml, options, &report, &error));
        TRY(fatoora_zatca_validation_report_is_valid(report, &valid, &error));
        TRY(fatoora_zatca_validation_report_is_complete(report, &complete, &error));
        TRY(fatoora_zatca_validation_report_to_json(report, &json, &error));
        puts(json);
        printf("valid: %s, complete: %s\n", valid ? "true" : "false", complete ? "true" : "false");
        /* Exit 0 means the report was produced, not that the invoice passed. */
        valid = true;
    } else {
        TRY(fatoora_xml_validate(xml, &valid, &error));
        printf("XSD valid: %s\n", valid ? "true" : "false");
    }
cleanup:
    if (status != FATOORA_OK)
        fprintf(stderr, "Error %d: %s\n", (int)status, fatoora_error_message(error));
    free(options);
    fatoora_string_free(json);
    fatoora_zatca_validation_report_free(report);
    free(xml);
    fatoora_error_free(error);
    return status == FATOORA_OK && valid ? 0 : 1;
}

Run the local ZATCA checks

Save validation-options.json beside the input. It contains predecessor context for the sample only.

./validation invoice.xml validation-options.json

The example prints the JSON report. Exit 0 here means a report was produced; parse is_valid and is_complete with your application's JSON parser before accepting the invoice.

Install the command-line tool with cargo install fatoora-cli, or extract a release binary and add it to your PATH. See the CLI guide for platform setup. Run beside your input files:

fatoora validate --invoice invoice.xml

For local ZATCA rules, use your shell to pass the predecessor hash. In a POSIX shell:

fatoora validate --invoice invoice.xml --profile zatca --format json \
  --previous-invoice-hash "$(cat previous-hash.txt)"

In PowerShell:

fatoora validate --invoice invoice.xml --profile zatca --format json `
  --previous-invoice-hash (Get-Content -Raw previous-hash.txt).Trim()

The schema command prints OK. The ZATCA command prints a report and returns 0 for valid, 2 for rejected, 3 for execution failure, or 4 for incomplete coverage.

Interpret the result

A successful schema check prints a success message. It says nothing about business rules or gateway acceptance. A local ZATCA check prints a structured report:

Result How to use it
is_valid: true The invoice passes the configured local profile with complete coverage. Keep any warnings.
is_valid: false, is_complete: true Inspect stage findings and correct the rejected invoice data.
is_complete: false Required context or a validation stage is missing. Resolve the gap before treating the invoice as checked.
Execution error The check could not finish normally. Inspect the error and any attached partial report.

Findings include a stage, code, and message. Warnings alone do not make an otherwise valid report fail. Do not discard them or reduce every failure to a generic “invalid invoice.”

Understand the coverage

The local profile implements the pinned SDK 238-R3.4.8 adaptations of CEN and Saudi rules: 105 CEN assertion sites and 152 Saudi sites. It runs without an external SDK runtime and uses the same profile in every API environment.

Under this profile, standard invoices skip signature and QR checks. Simplified invoices check the embedded certificate's key, reference digests, signature, and QR fields. These establish local integrity, not certificate issuer trust.

The default evaluation time is a single current UTC snapshot. For a reproducible historical test, supply an explicit evaluation time as documented in the validation options. A fixed demonstration clock should not become the default for your live integration.

If something goes wrong

Symptom What to check
Schema rejection Read the XML/schema error and correct the indicated structure or value.
Incomplete predecessor check Supply the trusted previous-invoice hash from your invoice history.
Signature/QR findings on the sample The downloaded invoice.xml is unsigned. To examine signed input, replace it with your signed XML and its matching predecessor context.
Different results after editing XML Run checks on the exact document you plan to submit; edits can invalidate signature material.

Next, submit the invoice and check gateway acceptance. The validation reference covers report fields and error contracts; SDK compatibility records differences from the SDK.