Payments and webhooks end to end

Advanced · 30 min

Add a paid plan with hosted checkout, then treat the provider webhook as the truth: verify the signature, store event ids and make handlers idempotent.

Before thisPerformance across the stackAuthorization in the API and the UIError handling across the stack

Stripe Developers · 30 min

Payments and webhooks end to end

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Stripe DevelopersReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Never mark an account as paid because the browser says checkout finished, since the redirect can be faked, skipped or lost; the provider's server-to-server webhook is the source of truth.
  • A webhook is an unauthenticated public POST, so verify the signature against the raw request body before trusting anything in it.
  • Providers deliver webhooks at least once and retry on failure, so handlers must be idempotent, and the simplest way is to record each event id with a primary key.
  • Do the event-id insert and the business update in one transaction so a crash between them cannot lose or double-apply the change.
  • Keep card data out of your system by using hosted checkout, and store only the provider's ids and the resulting plan.

Money makes the seams matter

Taskboard gets a paid Team plan. Until now every action began with the user clicking something and the server doing it. Payment adds a third party that acts on its own schedule: the user types a card into a page you do not host, the provider charges it, and then somehow your database must learn that a particular organisation is now on the Team plan.

The core problem is who tells your server the payment succeeded. The wrong answer is the browser. The right answer is the provider, talking to your server directly.

The flow

  1. The user clicks “Upgrade”. Your API creates a checkout session with the provider (stating the plan, your organisation id, and a success and cancel URL) and returns a URL.
  2. The browser goes to the provider’s hosted page and pays. Card numbers never touch your servers, which keeps most compliance work off your plate.
  3. The browser is redirected back to your success_url. This is for the user’s benefit: show “Thanks, we are confirming your payment”.
  4. Separately, the provider sends your server a webhook: an HTTP POST describing the event, such as checkout.session.completed.
  5. Your webhook handler verifies it and updates the organisation’s plan.

Steps 3 and 4 are two independent paths and you must not confuse them. A user can close the tab before the redirect and still have paid. A user can also type the success URL by hand without paying. The redirect is a UI nicety. The webhook is the record.

The details of Stripe’s API objects are in its documentation, and the embedded video is the provider’s own introduction to them. Your own side of the contract is what follows.

Verify the signature

A webhook endpoint is a public URL that changes your data when called. Anyone who learns it can POST {"type":"checkout.session.completed", ...} and give themselves a free plan unless you check who sent it. Providers sign each delivery, and you check the signature with a secret only you and the provider know.

The exact scheme belongs to the provider. Stripe’s, from its documentation, is an HMAC-SHA256 over the timestamp and the raw body, in a header of the form t=...,v1=..., and its libraries do the check for you. Here is a Stripe-style version I wrote with Node’s crypto module, so you can see what the library is doing for you:

app.post("/webhooks/billing", async (c) => {
  const raw = await c.req.text();                 // raw bytes, before JSON.parse
  const m = /t=(\d+),v1=([0-9a-f]+)/.exec(c.req.header("x-signature") ?? "");
  if (!m) return c.text("bad signature", 400);
  const t = Number(m[1]);
  const expected = Buffer.from(sign(t, raw), "hex");
  const got = Buffer.from(m[2], "hex");
  if (Math.abs(Date.now() / 1000 - t) > 300 ||
      got.length !== expected.length ||
      !crypto.timingSafeEqual(got, expected)) return c.text("bad signature", 400);
  // ...handle the event
});

Three details carry weight. Use the raw body. The signature covers the exact bytes sent, so if a body parser turns them into an object and you re-serialise, the check fails or, worse, you verify something other than what you act on. Compare in constant time with timingSafeEqual. Reject old timestamps, here after five minutes, so a captured request cannot be replayed next week.

I ran this against five calls. A correctly signed event returned 200. The same body with team changed to free returned 400. A missing header returned 400. A correct signature with a timestamp 1,000 seconds old returned 400. This is my own simplified scheme, not Stripe’s real one. For production use the provider’s library, which implements the real format and the tolerance for you. The deeper treatment is in receiving and verifying webhooks.

Make the handler idempotent

Providers promise delivery at least once. If your endpoint is slow, returns a 500, or the connection drops after you processed the event but before the provider heard “200”, it sends the event again. Sometimes it sends the same event twice for no reason you can see. Your handler must therefore produce the same result whether an event arrives once or five times.

The simplest design: keep a table of event ids you have handled, with the id as the primary key, and let the database refuse the duplicate:

await pg.transaction(async (tx) => {
  const r = await tx.query(
    "insert into processed_events(id) values ($1) on conflict do nothing returning id",
    [ev.id]);
  if (r.rows.length === 0) return;               // already handled
  if (ev.type === "checkout.session.completed")
    await tx.query("update orgs set plan = $2 where id = $1", [ev.data.orgId, ev.data.plan]);
});

I sent the same signed event twice. Both returned 200 (you must acknowledge a duplicate, or the provider keeps retrying), processed_events held one row, and the organisation ended on the team plan. Without the table, a handler that does something non-repeatable, such as sending a welcome email or adding credit, does it twice.

The insert and the update are in one transaction. If the process crashes between two separate statements, you end up with an event marked handled and a plan never changed, or the other way round, and no retry can fix the first case. In one transaction both happen or neither does. See idempotency keys in practice for the broader pattern, which also applies to your own endpoints, and transactions and isolation levels.

Respond fast, work later

Providers wait only a few seconds for your answer. If handling an event means sending email, generating an invoice PDF and calling other services, do the minimum inside the request (verify, record, update the plan) and queue the rest. That is the topic of the next lesson, background work and email from a feature.

What the UI should show

Between the redirect and the webhook there is a gap, usually seconds. The success page should say “confirming” and poll your API for the organisation’s plan, or listen for it over a live connection (see real-time updates end to end). The reverse also happens: a webhook arrives for an organisation whose user never returned. That is fine, because the plan is already correct when they next sign in.

Authorization applies here too. Whether a feature is available should be decided by the plan stored on your side, checked in the API (see authorization in the API and the UI), not by a flag the client sends.

Testing it

Payments are exactly where the earlier testing strategy says to mock what you do not own. Do not call the provider in your test suite. Test your handler by posting signed fake events to it, as I did above, including the replay, tampered and stale cases. Provider tools can forward real test-mode events to your local server for a final manual check, which is in their documentation and which I did not run. Always use test-mode keys outside production, and keep live keys only in the production environment (see environments, domains and TLS).

What the video covers

“Stripe integrations deconstructed: Core API concepts” is from Stripe’s own developer channel, about 30 minutes, and about a year old. By its title it explains the main objects and flow of a Stripe integration, which supports steps 1 to 5 above. I could not read a transcript, so I am not claiming it covers signature verification or idempotent handlers in detail, and those are the parts the sections above and the Hidden in the Code video (about ten minutes, Node-specific) are for. Provider APIs change, so check object names in the current docs.

Where this fits

The webhook handler showed the pattern for any slow or external work: acknowledge quickly, finish later. The next lesson makes “later” real with a job queue and uses it to send email: background work and email from a feature.

Check yourself

  1. 01Why can't the success page after checkout be what upgrades the account?

    It is a browser redirect the user controls and can fail to load, so it cannot prove payment. The provider's signed webhook reaches your server directly and is the reliable record.

  2. 02Why does signature verification need the raw body?

    The signature is computed over the exact bytes the provider sent. Parsing and re-serialising the JSON can change whitespace or key order and make a genuine event fail verification.

  3. 03How does insert into processed_events ... on conflict do nothing make the handler idempotent?

    The first delivery inserts the event id and returns a row, so the update runs. A repeat delivery conflicts, returns no row, and the handler skips the update.

  4. 04What can go wrong if the id insert and the plan update are separate statements?

    A crash between them leaves the event marked handled but the plan unchanged, or the reverse, so the account never upgrades or upgrades twice.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark