Skip to content

Connect to ZATCA APIs

Use the API client to submit invoices and inspect the gateway's response. This walkthrough reports a simplified invoice to the non-production environment and checks whether reporting was accepted. It requires network access and credentials.

For one runnable program covering creation through reporting, follow the sandbox walkthrough.

Choose the operation

Your task Operation Credentials
Test an invoice during onboarding Compliance check Compliance credentials
Submit a simplified invoice Reporting Production-type credentials for the selected environment
Submit a standard invoice Clearance Production-type credentials for the selected environment

A credential's type and its environment are separate. Production-type credentials can target non-production, simulation, or production; the client and credentials must agree. Every example below uses non-production. Changing only the client environment does not convert credentials issued for another environment.

Obtain credentials

  1. Generate a CSR and private key for the target environment.
  2. Obtain the onboarding one-time password (OTP) through the appropriate ZATCA flow, then submit the CSR to request compliance credentials.
  3. Use those credentials to complete the required invoice compliance checks.
  4. Request production-type credentials for that environment, then retain the returned token and secret for reporting or clearance.

See the credential endpoint reference and ZATCA developer portal for the request fields and environment-specific onboarding requirements. A successful compliance check alone is not reporting or clearance acceptance.

Renew credentials or use your own HTTP client

The client also supports production-credential renewal with an existing credential, a new CSR, and an OTP. See renewal inputs. Store the returned credentials for subsequent submissions.

For applications with an existing HTTP stack, prepared requests expose the method, URL, headers, and body without sending a request. Send them with your transport, then decode the actual response status and bytes. See custom transport for credential handling and redirect behavior.

Prepare the inputs

Use your own signed.xml: a simplified invoice signed with the certificate and key associated with your credentials. The offline guide's public test certificate is not a substitute for credentials issued to you.

Set ZATCA_TOKEN and ZATCA_SECRET in the environment of the process running the example. Do not paste credentials into source files. The example reads these names and fails before sending a request if either value is missing.

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

Add the async runtime:

cargo add tokio --features macros,rt-multi-thread

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

cargo run

Download this example.

Set ZATCA_TOKEN and ZATCA_SECRET in your process environment before running. The example makes a real request to the non-production gateway.

use fatoora_core::api::{ClearanceMode, CsidCredentials, Production, ZatcaClient};
use fatoora_core::config::{Config, Environment};
use fatoora_core::invoice::xml::parse::parse_signed_invoice_xml;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let environment = Environment::NonProduction;
    let token = std::env::var("ZATCA_TOKEN")?;
    let secret = std::env::var("ZATCA_SECRET")?;
    let client = ZatcaClient::new(Config::new(environment))?;
    let credentials = CsidCredentials::<Production>::new(environment, None, token, secret);
    let xml = std::fs::read_to_string("signed.xml")?;
    let invoice = parse_signed_invoice_xml(&xml)?;
    let response = client.report_simplified_invoice(&invoice, &credentials, ClearanceMode::Disabled, Some("en")).await?;
    response.ensure_accepted()?;
    println!("Invoice reporting accepted");
    Ok(())
}

Install the package in your Python environment:

pip install fatoority

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

python api.py

Download this example. See Python setup for package details.

Set ZATCA_TOKEN and ZATCA_SECRET in your process environment before running. The example makes a real request to the non-production gateway.

This example uses a blocking request; run it away from your application's UI thread. In asyncio code, use AsyncZatcaClient from the fatoority[async] extra instead (download the async example).

import os
from fatoora import ClearanceMode, Config, Environment, ProductionCsid, SignedInvoice, ZatcaClient

# Use credentials issued for this same environment.
environment = Environment.NON_PRODUCTION
token = os.environ["ZATCA_TOKEN"]
secret = os.environ["ZATCA_SECRET"]
with Config(environment) as config, ZatcaClient(config) as client:
    with ProductionCsid(environment, token=token, secret=secret) as credentials:
        with SignedInvoice.from_file("signed.xml") as invoice:
            with client.report_simplified_invoice(
                invoice, credentials, clearance=ClearanceMode.DISABLED, accept_language="en"
            ) as response:
                response.ensure_accepted()
                print("Invoice reporting accepted:", response.reporting_status)

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

npm install fatoority

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

node api.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.

Set ZATCA_TOKEN and ZATCA_SECRET in your process environment before running. The example makes a real request to the non-production gateway.

Browser requests also depend on gateway CORS. Keep private credentials on a trusted server.

import { readFileSync } from 'node:fs';
import { ClearanceMode, Config, ProductionCsid, Environment, SignedInvoice, ZatcaClient } from 'fatoority';

const environment = Environment.NonProduction; // Credentials must match.
const token = process.env.ZATCA_TOKEN;
const secret = process.env.ZATCA_SECRET;
if (!token || !secret) throw new Error('Set ZATCA_TOKEN and ZATCA_SECRET first');
const client = new ZatcaClient(Config.create(environment));
const credentials = ProductionCsid.create(environment, null, token, secret);
const invoice = SignedInvoice.fromXml(readFileSync('signed.xml', 'utf8'));
const response = await client.reportSimplifiedInvoice(invoice, credentials, ClearanceMode.Disabled, 'en');
response.ensureAccepted();
console.log('Invoice reporting accepted');

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.

Set ZATCA_TOKEN and ZATCA_SECRET in your process environment before running. The example makes a real request to the non-production gateway.

This example uses a blocking request; run it away from your application's UI thread.

using Fatoora;

const ZatcaEnvironment environment = ZatcaEnvironment.NonProduction; // Credentials must match.
string token = Environment.GetEnvironmentVariable("ZATCA_TOKEN")
    ?? throw new InvalidOperationException("Set ZATCA_TOKEN first");
string secret = Environment.GetEnvironmentVariable("ZATCA_SECRET")
    ?? throw new InvalidOperationException("Set ZATCA_SECRET first");
using var config = Config.Create(environment);
using var client = ZatcaClient.Create(config);
using var credentials = ProductionCsid.Create(environment, null, token, secret);
using var invoice = SignedInvoice.FromXml(File.ReadAllText("signed.xml"));
using var response = client.ReportSimplifiedInvoice(invoice, credentials, ClearanceMode.Disabled, "en");
response.EnsureAccepted();
Console.WriteLine("Invoice reporting accepted");

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.

Set ZATCA_TOKEN and ZATCA_SECRET in your process environment before running. The example makes a real request to the non-production gateway.

This example uses a blocking request; run it away from your application's UI thread. The binding also provides reportSimplifiedInvoiceAsync for coroutine callers.

import com.fatoora.*
import java.io.File

fun main(args: Array<String>) {
    val environment = Environment.NonProduction // Credentials must match.
    val token = requireNotNull(System.getenv("ZATCA_TOKEN")) { "Set ZATCA_TOKEN first" }
    val secret = requireNotNull(System.getenv("ZATCA_SECRET")) { "Set ZATCA_SECRET first" }
    Config.create(environment).use { config ->
        ZatcaClient.create(config).use { client ->
            ProductionCsid.create(environment, null, token, secret).use { credentials ->
                SignedInvoice.fromXml(File("signed.xml").readText()).use { invoice ->
                    client.reportSimplifiedInvoice(invoice, credentials, ClearanceMode.Disabled, "en").use { response ->
                        response.ensureAccepted()
                        println("Invoice reporting accepted")
                    }
                }
            }
        }
    }
}

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.

Set ZATCA_TOKEN and ZATCA_SECRET in your process environment before running. The example makes a real request to the non-production gateway.

This example uses a blocking request; run it away from your application's UI thread.

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 {
        Environment environment = Environment.NonProduction; // Credentials must match.
        String token = java.util.Objects.requireNonNull(System.getenv("ZATCA_TOKEN"), "Set ZATCA_TOKEN first");
        String secret = java.util.Objects.requireNonNull(System.getenv("ZATCA_SECRET"), "Set ZATCA_SECRET first");
        try (Config config = Config.create(environment);
             ZatcaClient client = ZatcaClient.create(config);
             ProductionCsid credentials = ProductionCsid.create(environment, null, token, secret);
             SignedInvoice invoice = SignedInvoice.fromXml(read("signed.xml"));
             ValidationResponse response = client.reportSimplifiedInvoice(invoice, credentials, ClearanceMode.Disabled, "en")) {
            response.ensureAccepted();
            System.out.println("Invoice reporting accepted");
        }
    }
}

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

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

cc -std=c11 -Iinclude api.c src/fatoora.c -L. -lfatoora_ffi -Wl,-rpath,'$ORIGIN' -o api
./api 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.

Set ZATCA_TOKEN and ZATCA_SECRET in your process environment before running. The example makes a real request to the non-production gateway.

This example uses a blocking request; run it away from your application's UI thread.

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

int main(int argc, char **argv) {
    if (argc != 2) {
        fprintf(argc == 1 ? stdout : stderr,
            "Usage: %s signed-invoice.xml\n"
            "Submits a simplified invoice to the non-production gateway.\n", argv[0]);
        return argc == 1 ? 0 : 1;
    }
    const char *token = getenv("ZATCA_TOKEN"), *secret = getenv("ZATCA_SECRET");
    if (!token || !secret) { fputs("Set ZATCA_TOKEN and ZATCA_SECRET first.\n", stderr); return 1; }
    FatooraConfig *config = NULL;
    FatooraSignedInvoice *invoice = NULL;
    FatooraProductionCsid *credentials = NULL;
    FatooraZatcaClient *client = NULL;
    FatooraValidationResponse *response = NULL;
    FatooraError *error = 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_signed_invoice_from_file(argv[1], &invoice, &error));
    TRY(fatoora_config_new(FATOORA_NON_PRODUCTION, &config, &error));
    TRY(fatoora_zatca_client_new(config, &client, &error));
    TRY(fatoora_production_csid_new(FATOORA_NON_PRODUCTION, NULL,
        token, secret, &credentials, &error));
    TRY(fatoora_zatca_client_report_simplified_invoice(client, invoice,
        credentials, FATOORA_CLEARANCE_DISABLED, "en", &response, &error));
    /* Receiving a response does not establish acceptance. */
    TRY(fatoora_validation_response_ensure_accepted(response, &error));
    puts("Invoice reporting accepted.");
    exit_code = 0;
cleanup:
    if (exit_code) fprintf(stderr, "Error %d: %s\n%s\n", (int)status,
        fatoora_error_message(error), fatoora_error_details_json(error));
    fatoora_validation_response_free(response);
    fatoora_zatca_client_free(client);
    fatoora_production_csid_free(credentials);
    fatoora_signed_invoice_free(invoice);
    fatoora_config_free(config);
    fatoora_error_free(error);
    return exit_code;
}

Check the result

The example prints Invoice reporting accepted only after checking the reporting outcome. An HTTP 2xx response that decodes successfully does not by itself mean the invoice was accepted.

Outcome What to do
Accepted Record the response and retain warnings. For compliance, this means only that the compliance check passed.
Rejected Inspect validation messages and correct the invoice before another submission.
Unknown Inspect the original status fields; missing, unfamiliar, or contradictory evidence cannot establish acceptance.

Non-2xx responses are errors and retain HTTP status and response details when available. Avoid blind retries when the result of a submission is uncertain.

Use clearance for a standard invoice

Choose the clearance operation with a standard invoice and credentials for the same environment. Check the clearance outcome, then retrieve the returned cleared invoice if your workflow needs the gateway document. Save that XML directly.

Acceptance does not guarantee the optional cleared document is present or decodable. Decoding the field establishes UTF-8 text only; it does not parse XML or verify a signature. The clearance reference describes the operation and response accessors.

If something goes wrong

Symptom What to check
Missing credential variable Set both named environment variables in the process that runs the example.
Authentication or authorization error Check the token, secret, credential type, and environment together.
Invoice rejected Read the gateway's validation messages and compare them with local validation.
Network error or timeout Check connectivity and the selected endpoint; determine whether a request reached the gateway before retrying.
Accepted clearance without usable XML Handle the missing or invalid document explicitly; do not silently substitute the submitted XML.

See the API reference for onboarding, renewal, compliance, reporting, clearance, and complete response contracts.