ZATCA e-invoicing in Node.js
One HTTP request from Node.js (fetch + pg): Matheel builds the invoice, signs it, files it with ZATCA and returns ZATCA's answer, the legal XML and the PDF with the QR.
1. Try it now (no key)
// npm i matheel
import { Matheel } from "matheel";
const matheel = new Matheel(process.env.MATHEEL_KEY); // the sandbox needs no key
const res = await matheel.fileInvoice({ environment: "sandbox", pdf: true,
invoice: { type: "simplified", line_items: [{ name: "قهوة", quantity: 2, price: "50.00" }] } });
console.log(res.status); // "reported", plus res.qr, res.pdf, res.invoice_xml
// After a payment: matheel.fileWithStore(store, invoice) keeps the device chain for you
2. The ready function, after payment
It locks the device row (so two payments at once never fork the chain), files the invoice with "pdf": true and saves the new device_token. Any non-200 rolls the transaction back and the old token stays valid.
// pg (node-postgres). Same flow in any DB: lock the device row, file, save the new token, commit.
export async function matheelInvoice(pool, 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",
headers: { "Content-Type": "application/json", Authorization: `Bearer ${process.env.MATHEEL_KEY}` },
body: JSON.stringify({ device_token: rows[0].token, pdf: true, invoice: { type: "simplified", 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(); }
}
Or with the official Matheel library: npm i matheel; fileWithStore does the same: reads and saves the token through your store and retries on a 409 by itself.
3. For production
- Register your device once (device token or an activation link) and put its
device_tokenin thematheel_devicetable. - If your amount includes VAT, send
"prices_include_vat": true. - Keep
invoice_xml(the legal copy) andpdfwith the order; your app shows the PDF from your server.
FAQ
Do I need a ZATCA library for Node.js?
No. Matheel is a plain JSON API: one HTTP request. Signing, the XML, the certificate and filing with ZATCA all happen at Matheel. An official library exists if you want one: npm i matheel
Where do I keep the device token?
One row in your database (a matheel_device table). After every 200, save the new device_token in the same transaction.
Can I try before subscribing?
Yes, on the developer sandbox without a key: the request below returns ZATCA's real answer and the PDF.