Sign ZATCA invoice XML¶
Sign an invoice using a certificate and its matching private key, then save the
result as signed.xml. Signing generates signature material; run validation
separately to check the invoice's local rule and integrity results.
Need an invoice first? Create one from application data,
then use its invoice.xml with the signing code below.
Prepare the inputs¶
For a local practice run, save these files in one folder:
- invoice.xml, an unsigned simplified invoice.
- certificate.pem, a demonstration certificate.
- private-key.pem, its matching demonstration key.
These are public test fixtures, suitable only for local examples. For your integration, use your own invoice and the certificate issued for the private key created during CSR generation. See API onboarding for the next steps. Do not pair a newly generated key with an unrelated certificate.
The examples write signed.xml in your working folder, replacing that file if it exists.
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
Save the code below as src/main.rs. Put the input files in the project root and run:
cargo run
use fatoora_core::invoice::sign::InvoiceSigner;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let xml = std::fs::read_to_string("invoice.xml")?;
let certificate = std::fs::read_to_string("certificate.pem")?;
let key = std::fs::read_to_string("private-key.pem")?;
let signer = InvoiceSigner::from_pem(&certificate, &key)?;
std::fs::write("signed.xml", signer.sign_xml(&xml)?)?;
println!("Saved signed.xml");
Ok(())
}
Install the package in your Python environment:
pip install fatoority
Save the code as signing.py beside the input files, then run:
python signing.py
Download this example. See Python setup for package details.
from pathlib import Path
from fatoora import InvoiceSigner
xml = Path("invoice.xml").read_text(encoding="utf-8")
certificate = Path("certificate.pem").read_text(encoding="utf-8")
key = Path("private-key.pem").read_text(encoding="utf-8")
with InvoiceSigner.from_pem(certificate, key) as signer:
signed_xml = signer.sign_xml(xml)
Path("signed.xml").write_text(signed_xml, encoding="utf-8")
print("Saved signed.xml")
Use Node.js 22 or later. In a new working folder, install the package:
npm install fatoority
Save the code as signing.mjs beside the input files, then run:
node signing.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, writeFileSync } from 'node:fs';
import { InvoiceSigner } from 'fatoority';
const signer = InvoiceSigner.fromPem(
readFileSync('certificate.pem', 'utf8'), readFileSync('private-key.pem', 'utf8'),
);
writeFileSync('signed.xml', signer.signXml(readFileSync('invoice.xml', 'utf8')));
console.log('Saved signed.xml');
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 var signer = InvoiceSigner.FromPem(File.ReadAllText("certificate.pem"), File.ReadAllText("private-key.pem"));
using var invoice = FinalizedInvoice.FromXml(File.ReadAllText("invoice.xml"));
using var signed = signer.Sign(invoice); // Consumes the invoice's inner state.
File.WriteAllText("signed.xml", signed.IntoXml());
Console.WriteLine("Saved signed.xml");
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
fun main(args: Array<String>) {
InvoiceSigner.fromPem(File("certificate.pem").readText(), File("private-key.pem").readText()).use { signer ->
FinalizedInvoice.fromXml(File("invoice.xml").readText()).use { invoice ->
signer.sign(invoice).use { signed -> File("signed.xml").writeText(signed.intoXml()) }
}
}
println("Saved signed.xml")
}
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);
}
static void write(String path, String text) throws java.io.IOException {
Files.write(Paths.get(path), text.getBytes(StandardCharsets.UTF_8));
}
public static void main(String[] args) throws Exception {
try (InvoiceSigner signer = InvoiceSigner.fromPem(read("certificate.pem"), read("private-key.pem"));
FinalizedInvoice invoice = FinalizedInvoice.fromXml(read("invoice.xml"));
SignedInvoice signed = signer.sign(invoice)) {
write("signed.xml", signed.intoXml());
}
System.out.println("Saved signed.xml");
}
}
Download and extract the fatoora-ffi-* archive for your platform from
GitHub Releases.
Save the example as signing.c in the extracted folder, beside the input files.
On Linux, compile the example and the supplied adapter, then run:
cc -std=c11 -Iinclude signing.c src/fatoora.c -L. -lfatoora_ffi -Wl,-rpath,'$ORIGIN' -o signing
./signing invoice.xml certificate.pem private-key.pem > signed.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>
/* Read a PEM file into a NUL-terminated string. */
static char *read_pem(const char *path) {
FILE *file = fopen(path, "rb");
if (!file) return NULL;
char *data = NULL;
if (fseek(file, 0, SEEK_END)) goto done;
long size = ftell(file);
if (size <= 0 || size > 1024 * 1024) goto done;
rewind(file);
data = malloc((size_t)size + 1);
if (!data) goto done;
if (fread(data, 1, (size_t)size, file) != (size_t)size) {
free(data);
data = NULL;
} else {
data[size] = '\0';
}
done:
fclose(file);
return data;
}
int main(int argc, char **argv) {
if (argc != 4) {
fprintf(stderr, "Usage: %s invoice.xml certificate.pem private-key.pem\n", argv[0]);
return 1;
}
char *cert = read_pem(argv[2]);
char *key = read_pem(argv[3]);
if (!cert || !key) {
fputs("Unable to read certificate or private key PEM.\n", stderr);
free(cert);
free(key);
return 1;
}
FatooraInvoiceSigner *signer = NULL;
FatooraFinalizedInvoice *invoice = NULL;
FatooraSignedInvoice *signed_invoice = NULL;
FatooraError *error = NULL;
char *xml = NULL;
FatooraStatus status = FATOORA_OK;
int exit_code = 1;
#define TRY(call) do { status = (call); if (status != FATOORA_OK) goto cleanup; } while (0)
TRY(fatoora_invoice_signer_from_pem(cert, key, &signer, &error));
TRY(fatoora_finalized_invoice_from_file(argv[1], &invoice, &error));
/* Signing consumes invoice's inner state; its outer handle still needs free. */
TRY(fatoora_invoice_signer_sign(signer, invoice, &signed_invoice, &error));
TRY(fatoora_signed_invoice_into_xml(signed_invoice, &xml, &error));
puts(xml);
exit_code = 0;
cleanup:
if (exit_code) fprintf(stderr, "Error %d: %s\n", (int)status, fatoora_error_message(error));
fatoora_string_free(xml);
fatoora_signed_invoice_free(signed_invoice);
fatoora_finalized_invoice_free(invoice);
fatoora_invoice_signer_free(signer);
fatoora_error_free(error);
free(cert);
free(key);
return exit_code;
}
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 sign --invoice invoice.xml --cert certificate.pem --key private-key.pem --signed-invoice signed.xml
Check the result¶
Open signed.xml. It should contain invoice XML with signature material and QR data.
The examples save the full XML rather than just a hash or signature string.
Keep the resulting document intact when storing or submitting it.
Signing alone does not establish business-rule compliance or gateway acceptance. Next, validate the original signed XML before reporting or clearance.
If something goes wrong¶
| Symptom | What to check |
|---|---|
| Certificate/key parsing fails | Match the input format shown in the selected example; PEM and DER are different representations. |
| Certificate/key mismatch | Use the private key corresponding to the certificate, not a key from a later CSR attempt. |
| XML cannot be parsed | Check that you supplied a supported invoice document, with its required fields and amounts. |
| Signed XML fails local validation | Inspect individual findings; adding a signature does not repair invoice data. |
See the signing reference for signature metadata, formats, and lower-level operations.