Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 38 ยท Webhooks

Webhooks Basics

Learn what Stripe webhooks are, why polling is the wrong tool, how events are shaped, and how to build a fast endpoint that acknowledges every event with a 2xx response.

When a customer pays, a lot happens outside your server: a bank approves the card, a 3D Secure window closes, an invoice renews at 3 a.m., a dispute opens a month later. Your code did not make an API call for any of these, so how does it find out? The answer is a webhook: Stripe sends an HTTP POST request to a URL you own, carrying a JSON description of what just happened.

In this chapter you will build webhook handling the way production systems do it: verified, idempotent, fast and safe against retries. The sandbox on this site has no internet access, so every example talks to a small server on 127.0.0.1 that plays Stripe's role. Real Stripe SDK code is shown read-only and labelled. The ideas and the HTTP mechanics are identical.

Why not just poll?

You could ask Stripe "did this payment succeed?" every few seconds. That wastes API calls, hits rate limits, and still misses events that nobody asked about (renewals, disputes, payouts). Worse, relying on the browser to tell your server "payment done" is unsafe: the customer can close the tab or fake the request. The webhook is the source of truth for money events.

How a webhook travels

Something happens A payment succeeds
Stripe builds an event JSON with a type and data
POST to your URL Signed with a secret
You answer 2xx Fast, then work later
1 / 2

What an event looks like

Every webhook body is an Event object. The fields you use most are:

Field Meaning
id Unique event id such as evt_1Abc.... Your idempotency key.
type What happened, for example payment_intent.succeeded.
created Unix timestamp of when Stripe created the event.
data.object A snapshot of the affected object (a PaymentIntent, Invoice, Charge...).
livemode true for real money, false in test mode.

Event types follow the pattern resource.action: checkout.session.completed, invoice.paid, customer.subscription.deleted, charge.dispute.created. You choose which types an endpoint receives, so subscribe only to what you handle.

A minimal endpoint

An endpoint is an ordinary route that accepts POST, reads the raw body, and replies with a 2xx status. The next example starts a loopback server and sends it two fake events.

Node.js A webhook endpoint and two events

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.

Route by event type

Real endpoints receive many types. A common structure is a map from type to handler, with a safe default for types you do not know. Unknown types must still get a 2xx; otherwise Stripe keeps retrying events you intentionally ignore.

Node.js Routing events to handlers

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.

The real SDK (read-only)

With the official Node library, a route looks like this. It cannot run here because npm packages are not installed; the next lesson rebuilds the signature check by hand.

JavaScript
// Read-only: needs the "stripe" npm package and a real secret
import Stripe from 'stripe';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);

app.post('/webhooks/stripe', express.raw({ type: 'application/json' }), (req, res) => {
  let event;
  try {
    event = stripe.webhooks.constructEvent(req.body, req.headers['stripe-signature'], process.env.STRIPE_WEBHOOK_SECRET);
  } catch {
    return res.sendStatus(400);
  }
  // handle event.type ...
  res.sendStatus(200);
});

Answer quickly. Store the event, return 200, and do slow work (emails, fulfillment) in a background job. Stripe treats a slow or failing response as a failure and retries.

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. Why is a webhook the source of truth for a payment, rather than the browser redirect?

    A browser callback can be skipped or forged. A signed webhook comes directly from Stripe.
  2. 2. What should an endpoint return for an event type it does not handle?

    Any non-2xx result is treated as a failure and retried, so ignored events still need a success response.
  3. 3. Which field is best used to recognise an event you already processed?

    The event id is unique, so it works as an idempotency key.

Summary

  • Webhooks are HTTP POSTs from Stripe to your server describing events.
  • They are the reliable source of truth for payments, renewals and disputes.
  • An event has id, type, created, livemode and data.object.
  • Return 2xx quickly, even for types you ignore; do slow work later.

Next: Verifying Webhook Signatures