Ordering backend project · Chapter 9 of 12
Orders and the payment webhook
By the end of this chapter you can turn a member's held place into a pending order at the menu's prices, check that a webhook really comes from the payment provider (an HMAC signature over the exact bytes, compared in constant time), and act on a payment exactly once, however many times the provider sends it. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: Taking orders
- 3 tasks
- Python
- In the all labs plan
The first 2 chapters of Ordering backend project are free. This one comes with the all labs plan.
Why you need this
Tara holds a place in the 12:30 Goregaon slot. Now she orders two Dal Tadka and four Roti: ₹340 of food and ₹30 for delivery, ₹370 in all. Advait orders the same for the same slot and pays ₹340, because his November subscription makes delivery free. DabbaDrop does not take card numbers itself. The app sends Tara to the payment provider's page; she pays there; and a few seconds later the provider's server calls DabbaDrop's server to say so. That call is a webhook: POST /webhooks/payments, from the provider, with no cookie and no logged-in member.
Two things go wrong with webhooks everywhere, and Rafiq has seen both on the sheet:
- Anyone can call the URL. A script that posts
{"type": "payment.captured", "data": {"order_id": 2, ...}}would get a free lunch if DabbaDrop believed it. - Providers send the same event more than once. When a delivery times out on their side, they send it again; sometimes two copies arrive together. Count a payment twice and Rafiq's books are wrong; act on it twice and the kitchen is told twice. Farah wants every order paid right.
The code so far keeps a place for ten minutes and nothing more: a hold has no dishes, no price and no payment.
What you build: 3 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
orders/service.py: turn a hold into an order
Write create_order(db, user_id, data) in app/modules/orders/service.py. data is an OrderIn (slot_id, items: a list of {dish_id, quantity}, each dish once). In one transaction: find the member's live hold on the slot (expires_at after now), locked with .with_for_update() so a double tap cannot turn one hold into two orders, or raise conflict("no_hold", ...) (409); find the slot and its zone's kitchen_id; find the dishes asked for that are that kitchen's and available, and raise unprocessable("bad_dishes", ...) (422) when any is missing; amount is each dish's price times its quantity, summed; delivery_fee is 0 when the member has a Subscription with starts_on <= the slot's day in Mumbai (mumbai_day) <= ends_on, else settings.delivery_fee (30). Add the Order (status pending) and flush, add an OrderItem per item with the dish's price, delete the hold, commit. On any error, roll back and raise it on.
Return order_out(order, items) (given) with items in the order asked, each {"dish_id", "name", "quantity", "price"}.
The Check orders without a hold (409), then 2 Dal Tadka and 4 Roti for Tara on slot 17 (340 and 30 delivery, total 370, the hold gone), Chole for Advait on Mon 2 Nov (delivery 0: he subscribes) and on 30 Nov (30: his plan ends on 27 Nov), tries an expired hold (409), Dadar Kitchen's Misal Pav for Goregaon and a dish that is not available (422 each, and Tara's hold stays), then sends POST /holds and POST /orders as Tara (201) and GET /orders/me (200).
- Task 2
signature.py: is this webhook really from the provider?
Write two functions in app/modules/payments/signature.py. sign_body(body, secret) returns "sha256=" followed by the hex of the HMAC-SHA256 of the body's exact bytes, with the secret (as bytes) as the key. verify_signature(body, header, secret) returns True when header is exactly sign_body(body, secret), compared with hmac.compare_digest, and False for anything else, never raising: a header that is None, empty or does not start with "sha256=".
The Check compares your signature with its own, checks that verify_signature uses hmac.compare_digest, tries another secret, a body changed after it was signed, no header, the hex without sha256= and an empty header, then sends POST /webhooks/payments with no signature (401, code bad_signature).
- Task 3 · interview question
Interview: payments/service.py, act on a payment once
Write handle_payment_event(db, event) in app/modules/payments/service.py. event is a PaymentEvent (id, type "payment.captured" or "payment.failed", data: order_id, payment_id, amount). Lock the order (db.get(Order, id, with_for_update=True)); no such order is not_found(...) (404). A capture whose amount is not the order's total (amount + delivery_fee) is unprocessable("wrong_amount", ...) (422), with nothing stored. Store the event in payments with insert(Payment).values(order_id, event_id, provider_payment_id, amount, status "captured" or "failed", payload event.model_dump()).on_conflict_do_nothing(index_elements=["event_id"]).returning(Payment.id); when no row comes back, the event was stored before: roll back and return {"duplicate": True, "order_id", "status": the order's status}. Otherwise a capture sets the order confirmed with confirmed_at now in Mumbai, a failure sets a pending order cancelled; commit and return {"duplicate": False, "order_id", "status": the new status}. On any error, roll back and raise it on.
The Check tries order 999 (404) and a capture of 300 for a 310 order (422, nothing stored), captures it (confirmed, one payments row), sends the same event again (duplicate true, still one row), fails another order (cancelled), delivers one event twice at once with another transaction holding the first copy open (the second must come back duplicate true, never an error), then sends a signed POST /webhooks/payments twice (200, then duplicate true).
Kunal will ask: the provider sent the same event twice because our first answer timed out. What would happen without the unique event_id, and why is 200 the right answer for the second delivery?
What you will learn
- An order from a hold: one transaction that checks the menu, prices the dishes, stores the order and its items, and deletes the hold.
- Webhooks: how a payment provider tells your server about a payment.
- HMAC signatures: proof that a body came from someone who knows the secret, and why the bytes must be exact.
- Constant-time comparison with hmac.compare_digest.
- Idempotency: one event, one effect, from a unique event id and insert ... on conflict do nothing.
- Locking the order while an event changes it.
More in Taking orders
Build "Orders and the payment webhook" yourself
DabbaDrop delivers tiffins across Mumbai. You build its ordering API, one module a chapter, and take the whole codebase home. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
The first 2 chapters of Ordering backend project are free. This one comes with the all labs plan.