ZATCA e-invoicing for Stripe
Stripe (payment gateway) 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
checkout.session.completed and checkout.session.async_payment_succeeded (Checkout / Payment Links); fulfill when payment_status != 'unpaid'
Registering it
Dashboard > Workbench > Webhooks > Create an event destination > Your account > choose events > Webhook endpoint > Endpoint URL; copy the whsec_ signing secret. Or API POST /v2/core/event_destinations. Local test: stripe listen --forward-to localhost:4242/webhook
Checking it came from Stripe
Header Stripe-Signature (t=timestamp, v1=HMAC-SHA256 of 't.raw_body' with the whsec_ secret). Verify with Stripe::Webhook.construct_event on the raw body; default tolerance 5 minutes
Amount and lines
- Amount:
session.amount_total, session.total_details.amount_tax; line item amount_subtotal, amount_discount, amount_tax, amount_total (all integers in the smallest currency unit) - Lines:
Retrieve the session with expand: ['line_items'] (or list line items): line_items.data[].description, line_items.data[].quantity - Customer email:
session.customer_details.email
Payment gateways send no order lines: the code loads them from your own order by its reference (load_order_items is your function, not Matheel’s).
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.
require 'sinatra'
require 'stripe'
client = Stripe::StripeClient.new(ENV.fetch('STRIPE_API_KEY'))
endpoint_secret = ENV.fetch('STRIPE_WEBHOOK_SECRET') # whsec_...
post '/webhook' do
payload = request.body.read
begin
event = Stripe::Webhook.construct_event(payload, request.env['HTTP_STRIPE_SIGNATURE'], endpoint_secret)
rescue JSON::ParserError, Stripe::SignatureVerificationError
halt 400
end
if %w[checkout.session.completed checkout.session.async_payment_succeeded].include?(event['type'])
session = client.v1.checkout.sessions.retrieve(event['data']['object']['id'], {expand: ['line_items']})
if session.payment_status != 'unpaid'
items = session.line_items.data.map do |li|
net = (li.amount_total - li.amount_tax) / 100.0 / li.quantity # halalas -> SAR, tax removed
{ name: li.description, quantity: li.quantity.to_s, price: format('%.2f', net) }
end
matheel_invoice(items)
end
end
status 200
end
Notes
amount_tax is only non-zero when Stripe computes tax. If the merchant's Stripe prices already include VAT and Stripe Tax is off, divide by 1.15 as well. expand returns only 'the first handful' of line items: for long carts, use the line-items list endpoint with auto-pagination. Stripe says fulfillment may run more than once, even concurrently, for the same session, so key the filing on the session id. Return 2xx quickly. Stripe's own sample hard-codes the whsec_ secret; this one reads it from the environment.
FAQ
Does Stripe file invoices with ZATCA by itself?
Stripe is a payment gateway. 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.