ZATCA e-invoicing for ERPNext / Frappe
ERPNext / Frappe (ERP) tells you when an order is paid; Matheel turns that payment into a ZATCA invoice, filed and accepted, with a bilingual PDF and the QR.
The event to listen to
Frappe Webhook on DocType 'Sales Invoice', Doc Event on_submit (other events: after_insert, on_update, on_cancel, on_trash, on_update_after_submit, on_change, workflow_transition), with an optional condition
Registering it
Integrations > Webhook > Webhook: DocType, Doc Event, Conditions, Request URL, Request Method POST, Request Structure JSON (Jinja), Enable Security + Webhook Secret
Checking it came from ERPNext / Frappe
Header X-Frappe-Webhook-Signature = base64 HMAC-SHA256 of the JSON body, keyed with the Webhook Secret (frappe/integrations/doctype/webhook/webhook.py signs frappe.as_json(data), the same bytes it sends)
Amount and lines
- Amount:
Sales Invoice: net_total, total_taxes_and_charges, grand_total, outstanding_amount; Sales Invoice Item: rate, net_rate, amount, net_amount - Lines:
items[].item_name, items[].qty (send with {{ doc["items"] | tojson }}) - Customer email:
contact_email
If the amount includes VAT (it usually does), send it as is with "prices_include_vat": true.
The code
It receives the event, verifies it and calls matheel_invoice(items): the ready function that locks the device row, files the invoice and saves the new token.
import base64, hashlib, hmac, os
from flask import Flask, request, abort
app = Flask(__name__)
# Request Structure (JSON):
# {"name": "{{ doc.name }}", "outstanding_amount": {{ doc.outstanding_amount }}, "items": {{ doc["items"] | tojson }}}
@app.post("/erpnext/sales-invoice")
def sales_invoice():
mac = hmac.new(os.environ["FRAPPE_WEBHOOK_SECRET"].encode(), request.get_data(), hashlib.sha256)
if not hmac.compare_digest(base64.b64encode(mac.digest()).decode(),
request.headers.get("X-Frappe-Webhook-Signature", "")):
abort(401)
inv = request.get_json()
if inv["outstanding_amount"] > 0:
return "", 200 # not paid in full at submit
items = [{"name": i["item_name"], "quantity": str(i["qty"]), "price": f'{i["net_rate"]:.2f}'}
for i in inv["items"]]
matheel_invoice(items)
return "", 200
Notes
on_submit catches invoices paid at submit (POS, 'Include Payment'). Unknown: whether a later Payment Entry that sets the invoice status to Paid triggers a Sales Invoice webhook; if not, hook Payment Entry on_submit and read its references. That net_rate is the unit rate after discounts without tax is inferred from the field label 'Net Rate', not from a doc. The Frappe guide shows only on_update as an example; the event list comes from webhook.json. Sales Invoice status options include Paid, Partly Paid and Unpaid.
FAQ
Does ERPNext / Frappe file invoices with ZATCA by itself?
ERPNext / Frappe is a ERP. It reaches ZATCA through a service like Matheel: each successful payment becomes an invoice filed with ZATCA.
Do I have to change my prices for VAT?
No. Send the amount the customer paid with "prices_include_vat": true; Matheel backs the VAT out and keeps the amount due equal to what was paid.
What if two payments arrive in the same second?
A device's invoices go one after another. Lock the device row while filing (the ready function does), and Matheel refuses a stale device token with 409 so the chain never forks.