ZATCA e-invoicing in Python
One HTTP request from Python (requests + psycopg): 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)
# pip install matheel-zatca
import os
from matheel_zatca import Matheel
matheel = Matheel(os.environ.get("MATHEEL_KEY")) # the sandbox needs no key
res = matheel.file_invoice(
{"type": "simplified", "line_items": [{"name": "قهوة", "quantity": 2, "price": "50.00"}]},
environment="sandbox", pdf=True)
print(res["status"]) # reported, plus res["qr"], res["pdf"], res["invoice_xml"]
# After a payment: matheel.file_with_store(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.
# 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
Or with the official Matheel library: pip install matheel-zatca; file_with_store 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 Python?
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: pip install matheel-zatca
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.