Matheel API docs

One endpoint: you send the invoice with your certificate, and you get back ZATCA's answer and the document to keep. Matheel stores nothing, so everything it needs comes in the same request.

Quickstart

Copy the command and run it now. No key, no signup, no certificate. On the sandbox, Matheel signs the invoice and files it on ZATCA's developer portal as our shared test taxpayer. The answer is ZATCA's real answer, and a ready PDF invoice comes with it.

curl https://matheel.app/api/v1/invoices \
  -H "Content-Type: application/json" \
  -d '{ "environment": "sandbox", "pdf": true,
        "invoice": { "type": "simplified",
                     "line_items": [{ "name": "Coffee", "quantity": 2, "price": "50.00" }] } }' \
  | jq -r .pdf | base64 -d > invoice.pdf

Open invoice.pdf: an Arabic and English invoice with a QR code and the legal XML embedded in it. If you get 200 with status reported or cleared, the integration works.

Without a key the limit is 30 invoices an hour. A free trial key raises it to 100. When you are ready for production, register your device once (device tokens) and every invoice after that is one line. If you have an app or website that takes card payments, go straight to invoice after payment.

Invoice after payment: mobile app or website

If your customer pays in your app or on your website (Telr, Moyasar, HyperPay, Tap, Stripe, any gateway), the whole integration is one function on your server that runs after the gateway confirms the payment:

  1. The gateway tells your server the payment succeeded (webhook or return page), and you verify it as you always do.
  2. Your server sends one request to Matheel with device_token, the line items and "pdf": true.
  3. You get back ZATCA's answer, the legal XML, the QR and the PDF invoice. Save them with the order, and the app shows the invoice.

Or use the official libraries (with the safe fileWithStore that retries on 409, QR decoding, and Telr and activation-callback verification):

npm i matheel                          # Node.js · npmjs.com/package/matheel
composer require matheel/matheel-php   # PHP · packagist.org/packages/matheel/matheel-php
pip install matheel-zatca              # Python · pypi.org/project/matheel-zatca
flutter pub add matheel_zatca          # Flutter: show the invoice and QR in the app

PHP with payments and refunds? PdoQueue in the PHP library (from 0.2.0) does it all with one table: one invoice per payment even when the gateway notifies twice, a credit note for a full or partial refund linked to the original invoice, automatic retries in order when ZATCA or Matheel is down, and the XML and PDF archived on your server. See the library README.

Three rules that prevent any duplicate or lost invoice: (1) a fixed uuid per payment, saved before sending and sent unchanged on every attempt; (2) one invoice per payment reference (a unique column), because gateways notify twice; (3) on any answer but 200, change nothing and send the same request later, and on a 409 carrying latest_device_token, save it and continue with it. The examples below do this, and Matheel's libraries do it for you.

Create a table with one row for the device: CREATE TABLE matheel_device (id INT PRIMARY KEY, token TEXT NOT NULL); and put in it the device_token you got from registering the device. Then copy the function in your language:

PHP
<?php
// CREATE TABLE matheel_invoices (payment_ref VARCHAR(64) PRIMARY KEY, uuid CHAR(36) NOT NULL, response MEDIUMTEXT);
// Call after the payment gateway confirms a payment. One invoice per payment, safe to call again for the same one.
function matheel_invoice(PDO $db, string $paymentRef, array $items): array {
    $db->beginTransaction();
    try {
        // Row lock: payments file one after the other, never two on the same token.
        $token = $db->query("SELECT token FROM matheel_device WHERE id = 1 FOR UPDATE")->fetchColumn();
        $q = $db->prepare("SELECT uuid, response FROM matheel_invoices WHERE payment_ref = ?");
        $q->execute([$paymentRef]);
        $row = $q->fetch(PDO::FETCH_ASSOC);
        if ($row && $row["response"]) { $db->commit(); return json_decode($row["response"], true); } // notified twice
        if (!$row) { // a fixed uuid per payment, saved before sending: every retry sends the same document
            $b = random_bytes(16); $b[6] = chr(ord($b[6]) & 0x0f | 0x40); $b[8] = chr(ord($b[8]) & 0x3f | 0x80);
            $row = ["uuid" => vsprintf("%s%s-%s-%s-%s-%s%s%s", str_split(bin2hex($b), 4))];
            $db->prepare("INSERT INTO matheel_invoices (payment_ref, uuid) VALUES (?, ?)")->execute([$paymentRef, $row["uuid"]]);
        }
        for ($try = 0; $try < 3; $try++) {
            $ch = curl_init("https://matheel.app/api/v1/invoices");
            curl_setopt_array($ch, [
                CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 60,
                CURLOPT_HTTPHEADER => ["Content-Type: application/json", "Authorization: Bearer " . getenv("MATHEEL_KEY")],
                CURLOPT_POSTFIELDS => json_encode(["device_token" => $token, "pdf" => true,
                    "invoice" => ["type" => "simplified", "uuid" => $row["uuid"], "line_items" => $items]]),
            ]);
            $res = json_decode((string) curl_exec($ch), true) ?: [];
            $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            if ($status !== 409 || empty($res["error"]["latest_device_token"])) break;
            $token = $res["error"]["latest_device_token"]; // an old token: continue with the latest one
        }
        $db->prepare("UPDATE matheel_device SET token = ? WHERE id = 1")->execute([$res["device_token"] ?? $token]);
        if ($status === 200) {
            $db->prepare("UPDATE matheel_invoices SET response = ? WHERE payment_ref = ?")->execute([json_encode($res), $paymentRef]);
        }
        $db->commit();
        // Not 200: nothing was filed twice. 504/503/0: call again later for this payment. 422 zatca_rejected: fix it.
        if ($status !== 200) throw new RuntimeException("Matheel $status: " . json_encode($res["error"] ?? $res));
        return $res;
    } catch (Throwable $e) {
        if ($db->inTransaction()) $db->rollBack();
        throw $e;
    }
}

// Example: after Telr confirms the payment (its tran_ref is the payment reference).
$res = matheel_invoice($db, $tranRef, [["name" => "تجديد إقامة", "quantity" => 1, "price" => "130.43"]]);
file_put_contents("invoices/{$orderId}.pdf", base64_decode($res["pdf"]));
file_put_contents("invoices/{$orderId}.xml", base64_decode($res["invoice_xml"]));
Node.js
// pg (node-postgres). Same flow in any DB: lock the device row, file, save the new token, commit.
// uuid: crypto.randomUUID() saved with the payment, the same on every retry of it.
export async function matheelInvoice(pool, uuid, items) {
  const db = await pool.connect();
  try {
    await db.query("BEGIN");
    const { rows } = await db.query("SELECT token FROM matheel_device WHERE id = 1 FOR UPDATE");
    const r = await fetch("https://matheel.app/api/v1/invoices", {
      method: "POST",
      signal: AbortSignal.timeout(60_000), // never hold the row lock on a hung connection
      headers: { "Content-Type": "application/json", Authorization: `Bearer ${process.env.MATHEEL_KEY}` },
      body: JSON.stringify({ device_token: rows[0].token, pdf: true, invoice: { type: "simplified", uuid, line_items: items } }),
    });
    const res = await r.json();
    if (r.status !== 200) throw new Error(JSON.stringify(res));
    await db.query("UPDATE matheel_device SET token = $1 WHERE id = 1", [res.device_token]);
    await db.query("COMMIT");
    return res; // Buffer.from(res.pdf, "base64") is the PDF
  } catch (e) { await db.query("ROLLBACK"); throw e; } finally { db.release(); }
}
Python
# psycopg + requests. `with conn:` commits on success and rolls back on any exception.
import os, requests

def matheel_invoice(conn, items):
    with conn, conn.cursor() as cur:
        cur.execute("SELECT token FROM matheel_device WHERE id = 1 FOR UPDATE")
        token = cur.fetchone()[0]
        r = requests.post("https://matheel.app/api/v1/invoices", timeout=60,
            headers={"Authorization": f"Bearer {os.environ['MATHEEL_KEY']}"},
            json={"device_token": token, "pdf": True, "invoice": {"type": "simplified", "line_items": items}})
        res = r.json()
        if r.status_code != 200:
            raise RuntimeError(res)
        cur.execute("UPDATE matheel_device SET token = %s WHERE id = 1", (res["device_token"],))
        return res  # base64.b64decode(res["pdf"]) is the PDF
Java / Kotlin (JVM)
// JDBC + java.net.http. Jackson (or any JSON library) for the body.
public Map<String, Object> matheelInvoice(Connection db, List<Map<String, Object>> items) throws Exception {
  db.setAutoCommit(false);
  try {
    ResultSet rs = db.createStatement().executeQuery("SELECT token FROM matheel_device WHERE id = 1 FOR UPDATE");
    rs.next();
    String body = json.writeValueAsString(Map.of("device_token", rs.getString(1), "pdf", true,
        "invoice", Map.of("type", "simplified", "line_items", items)));
    HttpResponse<String> r = http.send(HttpRequest.newBuilder(URI.create("https://matheel.app/api/v1/invoices")).timeout(java.time.Duration.ofSeconds(60))
        .header("Content-Type", "application/json").header("Authorization", "Bearer " + System.getenv("MATHEEL_KEY"))
        .POST(HttpRequest.BodyPublishers.ofString(body)).build(), HttpResponse.BodyHandlers.ofString());
    Map<String, Object> res = json.readValue(r.body(), Map.class);
    if (r.statusCode() != 200) throw new IllegalStateException(r.body());
    PreparedStatement up = db.prepareStatement("UPDATE matheel_device SET token = ? WHERE id = 1");
    up.setString(1, (String) res.get("device_token")); up.executeUpdate();
    db.commit();
    return res;
  } catch (Exception e) { db.rollback(); throw e; }
}
C# (.NET)
// Npgsql + HttpClient. Same flow on SQL Server: SELECT … WITH (UPDLOCK, ROWLOCK).
public async Task<JsonElement> MatheelInvoice(NpgsqlConnection db, object[] items) {
    await using var tx = await db.BeginTransactionAsync();
    var token = (string)await new NpgsqlCommand("SELECT token FROM matheel_device WHERE id = 1 FOR UPDATE", db, tx).ExecuteScalarAsync();
    http.DefaultRequestHeaders.Authorization = new("Bearer", Environment.GetEnvironmentVariable("MATHEEL_KEY"));
    var r = await http.PostAsJsonAsync("https://matheel.app/api/v1/invoices",
        new { device_token = token, pdf = true, invoice = new { type = "simplified", line_items = items } });
    var res = await r.Content.ReadFromJsonAsync<JsonElement>();
    if (!r.IsSuccessStatusCode) throw new Exception(res.ToString()); // tx rolls back on dispose
    var up = new NpgsqlCommand("UPDATE matheel_device SET token = @t WHERE id = 1", db, tx);
    up.Parameters.AddWithValue("t", res.GetProperty("device_token").GetString());
    await up.ExecuteNonQueryAsync();
    await tx.CommitAsync();
    return res; // Convert.FromBase64String(res.GetProperty("pdf").GetString()) is the PDF
}
Go
// database/sql + net/http.
// uuid: a UUID saved with the payment, the same on every retry of it.
func MatheelInvoice(db *sql.DB, uuid string, items []map[string]any) (map[string]any, error) {
	tx, err := db.Begin()
	if err != nil { return nil, err }
	defer tx.Rollback() // no-op after Commit
	var token string
	if err := tx.QueryRow("SELECT token FROM matheel_device WHERE id = 1 FOR UPDATE").Scan(&token); err != nil { return nil, err }
	body, _ := json.Marshal(map[string]any{"device_token": token, "pdf": true,
		"invoice": map[string]any{"type": "simplified", "uuid": uuid, "line_items": items}})
	req, _ := http.NewRequest("POST", "https://matheel.app/api/v1/invoices", bytes.NewReader(body))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Bearer "+os.Getenv("MATHEEL_KEY"))
	r, err := (&http.Client{Timeout: 60 * time.Second}).Do(req) // never hold the row lock on a hung connection
	if err != nil { return nil, err }
	defer r.Body.Close()
	var res map[string]any
	json.NewDecoder(r.Body).Decode(&res)
	if r.StatusCode != 200 { return nil, fmt.Errorf("matheel %d: %v", r.StatusCode, res) }
	if _, err := tx.Exec("UPDATE matheel_device SET token = $1 WHERE id = 1", res["device_token"]); err != nil { return nil, err }
	return res, tx.Commit()
}
Ruby (Rails)
# ActiveRecord: `lock` is SELECT … FOR UPDATE; any exception rolls the transaction back.
def matheel_invoice(items)
  MatheelDevice.transaction do
    device = MatheelDevice.lock.find(1)
    r = Net::HTTP.post(URI("https://matheel.app/api/v1/invoices"),
      { device_token: device.token, pdf: true, invoice: { type: "simplified", line_items: items } }.to_json,
      "Content-Type" => "application/json", "Authorization" => "Bearer #{ENV.fetch("MATHEEL_KEY")}")
    res = JSON.parse(r.body)
    raise "matheel #{r.code}: #{res}" unless r.code == "200"
    device.update!(token: res["device_token"])
    res # Base64.decode64(res["pdf"]) is the PDF
  end
end
Laravel
// DB::transaction rolls back on any exception; lockForUpdate() is SELECT … FOR UPDATE; throw() fails on non-2xx.
use Illuminate\Support\Facades\{DB, Http};

function matheel_invoice(array $items): array {
    return DB::transaction(function () use ($items) {
        $device = DB::table('matheel_device')->where('id', 1)->lockForUpdate()->first();
        $res = Http::withToken(env('MATHEEL_KEY'))->timeout(60)
            ->post('https://matheel.app/api/v1/invoices', ['device_token' => $device->token, 'pdf' => true,
                'invoice' => ['type' => 'simplified', 'line_items' => $items]])
            ->throw()->json();
        DB::table('matheel_device')->where('id', 1)->update(['token' => $res['device_token']]);
        return $res; // base64_decode($res['pdf']) is the PDF
    });
}
Elixir
# Ecto (import Ecto.Query) + Req. A non-200 fails the match and raises, so the transaction rolls back and the old token stays.
def matheel_invoice(items) do
  Repo.transaction(fn ->
    device = Repo.one!(from d in MatheelDevice, where: d.id == 1, lock: "FOR UPDATE")

    %{status: 200, body: res} =
      Req.post!("https://matheel.app/api/v1/invoices",
        auth: {:bearer, System.fetch_env!("MATHEEL_KEY")},
        receive_timeout: 60_000,
        retry: false,
        json: %{device_token: device.token, pdf: true, invoice: %{type: "simplified", line_items: items}}
      )

    device |> Ecto.Changeset.change(token: res["device_token"]) |> Repo.update!()
    res # Base.decode64!(res["pdf"]) is the PDF
  end)
end
Rust
// sqlx (Postgres) + reqwest (json) + serde_json + anyhow. Dropping `tx` without commit rolls back.
pub async fn matheel_invoice(pool: &sqlx::PgPool, items: serde_json::Value) -> anyhow::Result<serde_json::Value> {
    let mut tx = pool.begin().await?;
    let token: String = sqlx::query_scalar("SELECT token FROM matheel_device WHERE id = 1 FOR UPDATE")
        .fetch_one(&mut *tx).await?;
    let r = reqwest::Client::new()
        .post("https://matheel.app/api/v1/invoices")
        .bearer_auth(std::env::var("MATHEEL_KEY")?)
        .json(&serde_json::json!({ "device_token": token, "pdf": true,
            "invoice": { "type": "simplified", "line_items": items } }))
        .send().await?;
    let status = r.status();
    let res: serde_json::Value = r.json().await?;
    anyhow::ensure!(status == 200, "matheel {status}: {res}");
    sqlx::query("UPDATE matheel_device SET token = $1 WHERE id = 1")
        .bind(res["device_token"].as_str()).execute(&mut *tx).await?;
    tx.commit().await?;
    Ok(res) // base64-decode res["pdf"] for the PDF
}

Showing the invoice in the app

Save the PDF on your server or storage, and give the app its link (a signed URL, or one behind login). Each platform opens a PDF in one line:

PlatformLine
FlutterThe matheel_zatca package: ZatcaInvoiceCard(qr: qr, onOpenPdf: …) (guide), an invoice card with the ZATCA QR, the totals and a PDF button. Or launchUrl(Uri.parse(pdfUrl))
React NativeLinking.openURL(pdfUrl), or <Pdf source={{ uri: pdfUrl }} /> (react-native-pdf)
iOS (Swift)PDFView with PDFDocument(url: pdfURL), or SFSafariViewController(url: pdfURL)
Android (Kotlin)startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(pdfUrl)))
Website<a href="/orders/42/invoice.pdf" target="_blank">Invoice</a>

The PDF is the readable copy. The XML (invoice_xml) is the legal invoice, and it is embedded inside the PDF as PDF/A-3. Save both with the order, because Matheel stores nothing.

No code

No developer? There are ready options, and they start the same way: we send you an activation link, you open it on your phone, type your business details and an OTP from the Fatoora portal, and you get a device_token once. Copy it and keep it safe.

1. Google Sheets: a new row = an invoice

For service offices and shops that invoice by hand. Each row you type becomes an invoice filed with ZATCA. The PDF is saved to Google Drive and its link is written back into the same row.

  1. Create a sheet named Invoices with headers in the first row: item name, quantity, unit price before VAT, status, PDF, error.
  2. From the menu: Extensions → Apps Script, and paste this file.
  3. Project Settings → Script properties: add DEVICE_TOKEN (the text you got) and MATHEEL_KEY (your key).
  4. Reload the sheet. A menu named “ماثل” (Matheel) appears → “أصدر الفواتير الجديدة” (file new invoices). To run it automatically: Triggers → fileNewRows → every minute.

Telr → automatic invoice (n8n)

Every successful Telr payment becomes a ZATCA invoice, with no code. It runs on n8n (n8n cloud or your server), and we tested it: a signed payment files an accepted invoice, a forged one is refused, and three payments at the same moment get consecutive counters.

  1. In n8n: Import from file → the Matheel + Telr template.
  2. Create a Data table named matheel_device with a token column and one row holding your device_token.
  3. Open the "Verify Telr" node and edit its first three lines: your Matheel key, the Telr secret, the item name.
  4. Activate the workflow; in Telr → Transaction advice, paste the Webhook node's Production URL and tick "Only include authorised transactions".
  5. Optional: replace the "Invoice ready" node with Gmail or SMTP to email the PDF to the customer.

WooCommerce: a ready plugin

Every paid order in your shop becomes a ZATCA invoice automatically, and the customer gets the bilingual PDF with the completed-order email and on their order page.

  1. Download the plugin. In WordPress: Plugins → Add New → Upload → Activate.
  2. WooCommerce → Matheel ZATCA: paste your key (leave it empty and pick sandbox to try) and press "Connect your device".
  3. The activation link opens: enter your business details and the OTP from the Fatoora portal, then come back. The plugin receives the device token by itself.

If your prices include VAT (WooCommerce taxes off), the invoice total stays equal to what the customer paid. Invoices are filed in the background one after another, so checkout never waits and the invoice chain never breaks.

Odoo: a free module

For Odoo 17 and 18 (Community and Enterprise): every invoice or credit note you post is filed with ZATCA automatically; ZATCA's XML and the bilingual PDF are attached to it, and the QR is printed on Odoo's own invoice.

  1. Get the module from GitHub (the branch for your Odoo version), put it in your addons path, install "ZATCA Phase 2 E-Invoicing (Matheel)".
  2. Fill the company's VAT number, CR, address and building number.
  3. Settings → Accounting → ZATCA e-invoicing (Matheel): leave the key empty and keep Sandbox to try it, or paste your key and the Fatoora portal OTP, then press "Register device".

Invoices are filed in posting order, one at a time, and retried by themselves when ZATCA is down. An accepted invoice can't go back to draft: corrections go through a credit note.

2. We set it up for you

We set up the integration in your system or in n8n, register the device, and test with you until the first real invoice goes out. Email us at hello@matheel.app.

With AI

Copy the prompt and paste it into Claude, Cursor or ChatGPT, and it writes the integration in your project. Tools that read docs on their own can use /llms.txt.

Integrate the Matheel API (https://matheel.app) into my app so it files Saudi ZATCA Phase 2 e-invoices.
Reference (read it first): https://matheel.app/llms.txt
Ask me which language/framework I use and where invoices are created, then add one small client module.
Use one device_token per device: lock its DB row, POST /api/v1/invoices with {device_token, invoice, "pdf": true},
save the new device_token + invoice_xml + pdf in the same transaction on 200, keep the old token on any other status.
Start with "environment": "sandbox" and no key. Payment apps: call it after the gateway confirms the payment.

Device tokens: the simple path

Register the device once, then send every invoice with one string called device_token. It carries the business details, the certificate and the invoice chain (the counter and the hash of the last invoice). It is encrypted so only Matheel can open it, and we store none of it. You never handle keys or compute a counter or a hash.

# 1) Register the device (once per device)
curl https://matheel.app/api/v1/onboarding -H "Authorization: Bearer $MATHEEL_KEY" -H "Content-Type: application/json" \
  -d '{"environment":"sandbox","seller":{…},"device":{"name":"Till 1","branch":"Olaya","invoice_types":["simplified"]}}'
# → {"device_token":"mdt1.…","device":{"serial":"1-Matheel|…","certificate_expires_at":"…"},"compliance_checks":3}

# 2) Every invoice
curl https://matheel.app/api/v1/invoices -H "Authorization: Bearer $MATHEEL_KEY" -H "Content-Type: application/json" \
  -d '{"device_token":"mdt1.…","pdf":true,"invoice":{"type":"simplified","line_items":[…]}}'
# → {"status":"reported","counter":1,"device_token":"mdt1.(new)",…}

Activation links: for merchants without a developer

If you make POS or accounting software and your customers are merchants, you do not need to build registration screens. Create a link per merchant. The merchant opens it on their phone, types their business details and an OTP, and their device is registered with ZATCA.

curl https://matheel.app/api/v1/onboarding/links -H "Authorization: Bearer $MATHEEL_KEY" -H "Content-Type: application/json" \
  -d '{"environment":"production","reference":"merchant-42","callback_url":"https://your-app.com/matheel/devices","max_devices":3}'
# → {"url":"https://matheel.app/activate#…","callback_secret":"…","expires_at":"…"}

Authentication

The sandbox (sandbox) needs no key at all. Try it right away: the limit is 30 invoices and 5 device registrations an hour per IP. A free trial key raises the limit. Simulation and production need a plan key in the header:

Authorization: Bearer <your Matheel license key>

You get the key when you subscribe, and you renew or upgrade from your account page. There is no auto-renewal, so there is nothing to cancel. A wrong or revoked key returns 401.

Environments

The environment field is required. It decides where ZATCA receives the invoice. The certificate must come from the same environment.

ValueZATCA environmentUse
sandboxDeveloper portalDevelopment and testing, free
simulationSimulationA final test with the business's own certificate before production
productionProductionReal invoices; needs a device plan

Request

POST /api/v1/invoices with a JSON body containing either device_token and invoice (the simple path, see device tokens), or environment, seller, csid and invoice. Optionally mode and pdf.

seller · the selling business

FieldRequiredDescription
vat_numberYesVAT number, 15 digits
legal_name_arYesRegistered legal name in Arabic
legal_name_enNoName in English
crnNoCommercial registration number
addressYesstreet, building_number (4 digits), district, city, postal_code (5 digits)

csid · the certificate

FieldDescription
private_keyThe private key in DER format, base64-encoded
binary_security_tokenThe certificate exactly as ZATCA returned it
secretThe secret returned with the certificate

All three are used only to sign and file within the same request, and we do not keep them.

invoice · the invoice

FieldRequiredDescription
typeYessimplified (B2C) or standard (B2B tax invoice)
document_typeNoinvoice (default), credit_note, debit_note
counterYes*Invoice counter (ICV): an integer that starts at 1 and goes up by one per invoice
uuidYes*A unique UUID for the invoice
numberYes*Your invoice number. *Not needed with a device_token (taken from it) or on the keyless sandbox (defaults to 1, a random UUID and INV-1)
previous_invoice_hashFrom the second invoiceHash of the previous invoice (PIH). The first invoice uses the default value
issued_atNoIssue time in ISO 8601 with the offset, e.g. 2026-10-24T18:00:00+03:00
currencyNoDefault SAR
line_itemsYesLines: name, quantity, price (unit price before VAT), and optionally tax_category (S, Z, E, O) and tax_exemption_reason_code
prices_include_vatNotrue when the prices you send are what the customer paid, VAT included. Matheel backs the 15% out
subtotal, vat_amount, totalNoAmounts as decimal strings, e.g. "115.00". If you leave them out, Matheel computes them from the lines
buyerFor standard invoicesname, vat_number, and the address with the same fields as the seller
original_invoice_numberFor notesNumber of the original invoice in a credit or debit note
noteNoReason for the note, or a remark

mode · how it is filed

Optional. If you leave it out, Matheel picks from the type: clear for standard invoices and report for simplified ones.

pdf · the PDF invoice

Optional. "pdf": true adds pdf to the response: an A4 Arabic and English invoice in PDF/A-3, with the QR code and the legal XML embedded. Its figures come from the same calculation that wrote the XML, so they never differ from it. No extra charge; it adds about one second to the request.

Response

{
  "status": "cleared",            // or "reported"
  "zatca_uuid": "…",
  "invoice_hash": "NWZlY2Vi…",     // send it as previous_invoice_hash next time
  "previous_invoice_hash": "…",
  "qr": "AQ1TaGFy…",               // TLV, base64: print it on the invoice
  "invoice_xml": "PD94bWwg…",      // base64 legal XML: archive it, hand it to the buyer
  "pdf": "JVBERi0xLjc…",           // only with "pdf": true: base64 PDF/A-3 for the customer
  "warnings": [],
  "errors": [],
  // with device_token only:
  "device_token": "mdt1.…",        // save it, send it with the next invoice
  "counter": 7,
  "device": { "name": "…", "serial": "…", "certificate_expires_at": "…" }
}

If rendering the PDF fails (rare), the invoice is still filed and accepted: you get "pdf": null, a warning in warnings, and status 200. With clearance, invoice_xml is the document stamped by ZATCA. With reporting, it is the signed XML that was sent. Either way, it is the document you keep.

Invoice chain

ZATCA links every invoice to the one before it: the counter (ICV) must go up by one, and the previous hash (PIH) must match. Matheel stores nothing, so it does not hold the chain. You do:

Errors

CodeMeaning
401 invalid_api_keyThe key is wrong or revoked
402 production_plan_requiredThe key has no device plan (e.g. a trial key). Subscribe to a plan to file in production
422 missing_fieldsA required field is missing; the response lists the field names
422 invalidA value is not accepted, such as a wrong invoice type or a date without an offset
422 validation_failedThe invoice failed the spec check before filing
422 with errorsZATCA rejected the invoice; its errors are in the response verbatim
422 zatca_rejectedZATCA rejected the invoice; its errors are in errors. Fix it and send it with the same device_token: nothing was filed. Do not resend it unchanged
504 filing_outcome_unknownZATCA may have received it and we got no answer. Send the same request again, same device_token and same uuid, until it answers: it is never filed twice
503 zatca_unavailableZATCA could not be reached and nothing was sent. Retry later with the same device_token
409 filing_in_progressThe device is filing right now. Repeat the same request in a few seconds (Retry-After)
409 previous_filing_unknownAn earlier invoice on this device (uuid in the reply) was sent with no answer yet. Send that invoice again first
401 invalid_csidZATCA refused the device's certificate: renew it with a new OTP
422 filing_failedAn unexpected error on our side. Retry shortly with the same request
409 device_token_reusedAn old token: another invoice was accepted with it. The reply carries latest_device_token: save it and send the invoice with it
422 invalid_device_tokenThe token is truncated, altered, or not from Matheel
429 sandbox_rate_limitedToo many test invoices outside production: 30 an hour per IP without a key, 100 an hour per key on sandbox and simulation (with your own certificate too). Wait for the next hour; production is not limited
503 billing_unavailableWe could not check the key right now. Send it again shortly with the same counter

Retries are always safe: if the connection drops or no answer arrives, send the same request with the same device_token and the same uuid. If the invoice was already accepted you get the same answer and the same next token back ("replayed": true) and nothing is filed again. For that we keep, per device, only the last answer, encrypted, for 7 days (privacy). Send a fixed uuid per invoice of yours.

Connection dropped before any answer (TLS)

If you see unexpected eof while reading or ECONNRESET before any response, the network between your server and ours is likely dropping the large post-quantum TLS ClientHello that OpenSSL 3.5 sends by default (Node 24, recent PHP and Python). The fix is one line: use a classic X25519 key share. Our official libraries do this from version 0.1.2.

curl --curves X25519 https://matheel.app/api/v1/invoices …                       # curl
https.request(url, { ecdhCurve: "X25519:P-256" }, …)                           // Node.js
ctx = ssl.create_default_context(); ctx.set_ecdh_curve("X25519")               # Python
curl_setopt($ch, CURLOPT_SSL_EC_CURVES, "X25519:P-256");                        // PHP 8.2+

CSID certificate

Matheel does every step for you in one request to POST /api/v1/onboarding: you send your business details and get back a device_token (see device tokens). If you want the certificate itself, add "include_credentials": true and you also get a csid to put in the invoice request. On the sandbox no OTP is needed. On simulation and production, send the OTP from the Fatoora portal.

curl https://matheel.app/api/v1/onboarding \
  -H "Authorization: Bearer $MATHEEL_KEY" -H "Content-Type: application/json" \
  -d '{ "environment": "sandbox",
        "seller": { "vat_number": "399999999900003", "legal_name_ar": "منشأتك", "legal_name_en": "Your Co",
                    "address": { "street": "King Fahd Rd", "building_number": "1234", "district": "Al Olaya",
                                 "city": "Riyadh", "postal_code": "12211" } } }'
# → { "device_token": "mdt1.…", "device": {…}, "compliance_checks": 6 }
#   with "include_credentials": true → also { "csid": { "private_key": "…", "binary_security_token": "…", "secret": "…" } }

The certificate and key are returned to you and we do not keep them. Store them safely on your side. Each device or branch has its own certificate. The limit is 10 registrations an hour per key.

These are the steps Matheel runs (if you want to do them yourself):

  1. Generate a CSR with a secp256k1 key that carries the business details.
  2. The business owner gets an OTP from their account on the Fatoora portal.
  3. Exchange the CSR and OTP for a compliance certificate, then pass the six compliance checks.
  4. Then get the production certificate. That is the one you send in csid.

On the developer portal the OTP is a fixed value published in the official docs, so you can run every step today. If you want help with your first integration, email us at hello@matheel.app.

Usage and limits