Booking backend project · Chapter 9 of 12

Bookings and the payment webhook

By the end of this chapter you can turn a member's held seats into a pending booking at the right price, 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: Selling seats
  • 3 tasks
  • TypeScript
  • In the all labs plan

The first 2 chapters of Booking backend project are free. This one comes with the all labs plan.

Why you need this

Neha holds E7 and E8 for the 9:30 pm Ghar Wapsi Express. Now she must pay ₹400: two Middle seats at ₹180 and Parda's fee of ₹20 a seat. Parda does not take card numbers itself. The React site sends Neha to the payment provider's page; she pays there; and some seconds later the provider's server calls Parda's server to say so. That call is a webhook: POST /webhooks/payments, from the provider, with no cookie and no logged-in user.

Two things go wrong with webhooks in every company that has them, and Datta has seen both on the old script:

  • Anyone can call the URL. A script that posts {"type": "payment.captured", "bookingId": 1} would get free tickets if Parda believed it.
  • Providers send the same event more than once. If a delivery times out on their side, they retry; sometimes two copies arrive together. The old script confirmed a booking once per delivery and sent two e-tickets; worse, it once counted the same ₹1,200 twice in a venue owner's payout. Sayali wants venue owners paid right.

What you build: 3 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    bookings.service.ts: turn holds into a booking

    Write createBooking(userId, showtimeId) in src/modules/bookings/bookings.service.ts, all in one transaction. No such showtime is an AppError 404. Read this member's holds on the showtime that have not expired (expires_at after now), with their seats, locked for update; none is a 409 with code no_holds. amount is the sum of each seat's price from the showtime's prices for the seat's class; fee is config.feePerSeat (20) times the number of seats. Insert the booking (its status starts as pending), one booking_seats row per seat with that seat's price, and delete those holds.

    Return { id, status, showtimeId, seats, amount, fee, total }: seats are the seat labels (E7) ordered by seat id, and total is amount plus fee.

    The Check gives Neha (user 2) live holds on E7 (Middle, ₹180) and P1 (Balcony, ₹240) of showtime 9, an expired hold on E9, and gives Pranav a hold on E8. createBooking(2, 9) must return seats ["E7", "P1"], amount 420, fee 40, total 460 and status pending, store the booking and its two booking_seats rows (prices 180 and 240), delete Neha's holds and keep Pranav's. A second call is the 409 no_holds; showtime 999 is the 404. Then POST /bookings as Neha after holding E10 must answer 201 with total 200, and as Asha, who holds nothing, 409 with the code no_holds. listMyBookings is given.

  2. Task 2

    signature.ts: is this webhook really from the provider?

    Write signBody(body, secret) and verifySignature(body, header, secret) in src/modules/payments/signature.ts. body is a string or a Buffer. signBody returns "sha256=" followed by the HMAC-SHA256 of the body's exact bytes with the secret, as 64 lower-case hex characters.

    verifySignature returns true only when header is exactly signBody(body, secret), and false, without throwing, for a missing header, a signature made with another secret, a body changed by one byte, a header of the wrong length, or the hex digest without "sha256=". Compare in constant time with timingSafeEqual from node:crypto, on two Buffers of the same length.

    The Check compares signBody with its own HMAC, for a string and for a Buffer, and tries each of those headers. Then POST /webhooks/payments with no signature, and signed with another secret, must answer 401, and a body signed with the app's secret must get past the signature.

  3. Task 3 · interview question

    Interview: payments.service.ts, act on a payment once

    Write handlePaymentEvent(event) in src/modules/payments/payments.service.ts, in one transaction. event is { id, type, data: { bookingId, paymentId, amount } } and type is payment.captured or payment.failed. Read the booking locked for update; none is an AppError 404. Store the event in payments (bookingId, eventId from the event's id, providerPaymentId from data.paymentId, amount, status captured or failed, and the whole event as payload) with an insert that does nothing on a conflict on event_id. If nothing was stored, the event came before: return { duplicate: true, bookingId, status } with the booking's status and change nothing. A booking that is not pending: return { duplicate: false, bookingId, status } and change nothing. payment.failed sets the booking cancelled and deletes its booking_seats rows. payment.captured needs data.amount to equal the booking's amount plus fee, else a 422 with code wrong_amount; then status confirmed and confirmedAt now. Return { duplicate: false, bookingId, status } with the new status.

    The Check confirms a ₹400 booking with evt_1, sends evt_1 again (duplicate true, confirmed_at unchanged, one payments row), sends ₹999 for another ₹400 booking (422, still pending, nothing stored), fails that booking (cancelled, its seats freed) and tries booking 999 (404). Then, through the app, it holds and books as Neha and sends the same signed webhook twice: 200 confirmed, then 200 with duplicate true, and GET /bookings/me shows the booking confirmed.

    Nikhil will ask: the provider sends payment.captured twice for one booking, both at once. Why does the unique event_id, and not a check before the insert, keep the booking from being acted on twice?

What you will learn

  • A booking from holds: one transaction that prices the seats, stores the order and deletes the holds.
  • Locking rows you read with for update, so the same request twice cannot book twice.
  • Webhooks: how a provider tells you 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 timingSafeEqual.
  • Idempotency: a unique event id, so an event is acted on once.

More in Selling seats

Build "Bookings and the payment webhook" yourself

Parda sells tickets for Pune's own cinemas and stages. You build its booking 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 Booking backend project are free. This one comes with the all labs plan.