ZATCA e-invoicing in Elixir / Phoenix
One HTTP request from Elixir / Phoenix (Req + Ecto): 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)
Mix.install([:req])
%{body: res} =
Req.post!("https://matheel.app/api/v1/invoices",
json: %{environment: "sandbox", pdf: true, invoice: %{
type: "simplified", line_items: [%{name: "قهوة", quantity: 2, price: "50.00"}]}})
IO.puts(res["status"]) # reported
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.
# 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
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 Elixir / Phoenix?
No. Matheel is a plain JSON API: one HTTP request. Signing, the XML, the certificate and filing with ZATCA all happen at 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.