Skip to content
Tutorials Center
My learning

Topics

Lesson 124 of 133 ยท Projects

Project: Payment Integration with Webhooks

Build a payment flow in Node.js with a stand-in provider. Checkout sessions, signed webhooks verified against the raw body, replay protection, retries and idempotent order updates.

Taking money online looks simple from the outside: the customer clicks "Pay" and your order turns green. Inside, it is a conversation between your server and a payment provider (Stripe, Paddle, PayPal, Adyen and others), and the conversation has to survive failures: a customer who closes the tab after paying, a provider that delivers the same notification three times, a network that drops your answer, or an attacker who sends you a fake "payment succeeded" message.

The standard pattern is:

  1. Your server creates a checkout session at the provider and redirects the customer there. The provider shows the payment form (so card numbers never touch your server).
  2. When something happens (payment succeeded, failed, refunded), the provider calls your webhook: an HTTP POST to a URL you registered, carrying an event.
  3. Your webhook handler verifies that the event really comes from the provider, applies it to your order exactly once, and answers 2xx. If you answer anything else, the provider retries later.

Our sandbox has no internet and no real provider, so we write a small stand-in provider that behaves like the real ones: it creates sessions, remembers idempotency keys, signs its webhooks with a shared secret and retries failed deliveries. Everything you build on the merchant side (signature check, idempotency, state rules) is exactly what real integrations need; only the URLs and field names change. Real provider SDKs are shown read-only where it matters.

Never put real API keys or webhook secrets in code, in a lesson or in a repository. The secret below is a throwaway demo value. In a real project it comes from the environment (Secrets and Config), and you test against the provider's test mode first.

Stage 1: signing and verifying webhooks

Your webhook URL is public, so anyone can POST to it. The provider proves a request is genuine by adding a signature: an HMAC (a keyed hash) of the request body, made with a secret that only the provider and you know. You recompute it and compare. Three details separate a safe implementation from a vulnerable one:

  • Sign the raw bytes. If you parse the JSON first and serialize it again, spaces and key order can change, and the signature no longer matches. Verify against the exact body the server sent, so your handler must read the body as a Buffer or string before parsing (request bodies).
  • Compare in constant time with crypto.timingSafeEqual, never with ===, so an attacker cannot learn the signature one character at a time from response times.
  • Include a timestamp in the signed text and reject old ones. Otherwise someone who captured a real webhook could replay it next week. The format below, t=<seconds>,v1=<hex>, is modelled on the scheme several providers use: sign "<t>.<body>".
Node.js Sign, verify, and reject forged or replayed webhooks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice the fourth line: the same data printed with indentation fails, because the signature covers bytes, not meaning. That is why web frameworks that parse JSON before your handler runs cause trouble for webhooks. In Express you register express.raw({ type: 'application/json' }) (or keep the raw buffer with the verify option of express.json) for the webhook route only. And note the replay check: a valid signature is accepted only within five minutes of its timestamp.

Stage 2: apply events exactly once

Providers promise at-least-once delivery: every event arrives, but some arrive twice, and with retries they may arrive out of order. So the handler has to be idempotent: processing the same event twice must leave the same result as processing it once. Two tools do the job:

  1. An event log. Store each event id you have handled (a table with a UNIQUE event id in a real database). A duplicate is acknowledged with 200 but not applied again.
  2. A state machine for orders. An order moves forward only: pending -> paid -> refunded (or pending -> failed). An event that would move it backwards or sideways is ignored. This protects you when payment.failed for an old attempt arrives after payment.succeeded.

Order of the checks matters too: record the event id and update the order in one transaction, so a crash cannot leave the event marked "handled" with the order untouched.

Node.js Idempotent order updates with a state machine

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Every line of output is a design decision. The duplicate is acknowledged but harmless; the late payment.failed cannot undo a paid order; the wrong amount is rejected (and in production would raise an alert); an unknown event type is ignored instead of crashing, so the provider can add event types without breaking you. The ok, duplicate and ignored results should all lead to a 2xx response: the event was received, and answering with an error would only make the provider retry something that can never succeed.

Be careful with the amount check. Money is stored as an integer in the smallest unit (cents) and the currency is part of the payment too. Compare both. Never compute a price from data sent by the browser: the server decides what an order costs.

Stage 3: the whole flow with a stand-in provider

Now we connect the pieces. The program starts two servers on loopback:

  • The provider: POST /v1/sessions creates a checkout session (supporting an Idempotency-Key header, so a retried request does not create two sessions), and POST /v1/sessions/:id/pay plays the role of the customer completing payment. When a session is paid, the provider sends a signed payment.succeeded webhook to the merchant, and retries with a delay if the merchant does not answer 2xx. To test duplicates, the provider can send the same event twice.
  • The merchant: POST /checkout creates an order and a session, and POST /webhooks/pay verifies the signature on the raw body and applies the event with the logic from stage 2.

To keep the lesson readable, the stage 1 and 2 code is repeated in compact form.

Node.js Orders, checkout sessions and signed, retried webhooks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the delivery log. The provider's first attempt received 500, so it retried and the second attempt got 200; then it deliberately sent the same event again, and the merchant answered 200 with duplicate: true without touching the order. Meanwhile the order moved from pending to paid exactly once. The forged request failed with 400 before any database work. Also notice that the merchant answered the browser and the provider quickly: the webhook handler does little work. If a handler needs slow work (sending email, generating an invoice), record the event, answer 200, and do the slow part in a background job (Project: Background Job Queue); providers treat slow answers as failures and retry.

What real providers add

  • A hosted payment page and redirects. After payment the browser returns to your success_url. Do not mark an order paid because the customer landed on that page: they can open the URL by hand. Only the webhook (or a server-to-server lookup of the session) is proof.
  • Webhook management. Dashboards show delivery attempts and let you resend events. Retries last hours or days with growing delays; endpoints that fail for too long can be disabled.
  • API versions and event shapes differ per provider. Official SDKs (for example the stripe package's webhooks.constructEvent(rawBody, signatureHeader, secret)) wrap the stage 1 verification; use them, but understand what they do.
  • Reconciliation. A nightly job lists recent payments from the provider's API and compares them with your orders, so a webhook lost for good does not leave a paid customer waiting.
  • Taxes, invoices and refunds are separate flows with their own events, and often legal requirements. Keep an audit trail: never delete payment events.
  • Compliance. Using a hosted payment page keeps card data away from your servers, which keeps your PCI scope small. Never log card numbers or full webhook bodies containing personal data.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why must webhook signature verification use the raw request body?

    The provider signed exact bytes. Any change, even harmless formatting, produces a different HMAC, so verify the original text and parse only afterwards.
  2. 2. What does the timestamp inside the signed text protect against?

    A valid old webhook still has a valid signature. Rejecting timestamps older than a few minutes means a stolen request cannot be reused later.
  3. 3. The provider delivers the same event twice. What should the merchant respond to the second delivery?

    The event was received, so a 2xx answer stops retries. Idempotency means the repeated event changes nothing.
  4. 4. A customer is redirected to your success page after paying. Is that enough to mark the order as paid?

    Browser redirects are controlled by the user. Payment status comes from the provider through an authenticated channel.
  5. 5. Why does the Idempotency-Key header exist on the create-session request?

    If your request times out you do not know whether it worked. Sending it again with the same key returns the original result instead of repeating the action.

Summary

  • A payment integration is a conversation: create a checkout session, send the customer to the provider, and learn the result through signed webhooks.
  • Verify every webhook against the raw body with HMAC, constant-time comparison and a timestamp tolerance.
  • Delivery is at least once and may be out of order: record event ids, apply changes inside one transaction and let orders move only forward.
  • Answer 2xx quickly for anything you received, including duplicates and unknown types; do slow work in the background.
  • Decide prices on the server, check amounts and currency, use idempotency keys for requests that create things, and reconcile with the provider regularly.

Next: Project: Email and Notification Service