Stripe — Checkout, subscriptions, and webhooks that survive production
Wire an app to Stripe for one-time payments and subscriptions: a Checkout
Session to take money, a signature-verified webhook to learn the outcome, and
the billing portal so customers manage themselves. Targets stripe-node v22.x
(API version 2026-05-27.dahlia).
The one rule everything else hangs off:
- **Stripe is the source of truth; your DB is a cache kept current by verified
webhooks.** A subscription's real state lives in Stripe. You mirror it locally
only so you can render a paywall without a round-trip. The webhook is what
keeps the mirror honest — never the client redirect, never polling.
When to use / When NOT to use
Use when: adding Checkout or a paywall; taking a one-time or recurring
charge; receiving Stripe webhooks; letting users cancel/upgrade via the portal;
debugging No signatures found matching, double-fired events, or a
checkout.session.completed that never arrives.
Do NOT use for:
- A generic, non-Stripe inbound webhook receiver (arbitrary HMAC, a
retry/queue consumer for any provider) → webhooks. This skill only covers
Stripe's Stripe-Signature scheme and event model.
- The invoice document's legal form — what must appear on it, dunning copy,
payment-status as a business process → invoicing.
- Cash-flow forecasting, bank reconciliation, month-close →
- What to charge / plan tiers / packaging → pricing.
This skill implements a price; it does not decide it.
- A typed client for some other REST API →
api-connector-builder.
Pick the surface
| You need | Use | Why |
|---|---|---|
| A link to sell one product, zero code | Payment Link | No backend; Stripe hosts everything. Outgrow it fast. |
| Hosted checkout, full control of session | Checkout Session | The default. Stripe hosts the page, handles SCA/3DS, PCI scope is minimal. |
| Your own embedded payment form | Payment Element + Checkout Session | Custom UI, but you render the form. Use the Element with a Checkout Session, not raw PaymentIntents, unless you have a reason. |
Default to Checkout Session unless a requirement forces otherwise.
Mental model
Customer ──> Price (you defined it in Stripe) ──> Checkout Session
│ │
│ customer pays (hosted)
▼ ▼
your DB <── webhook (verified) ── Event <── Subscription / Invoice
(a cache) (the real state, in Stripe)
Env vars used throughout — read from the environment, never hard-code:
STRIPE_SECRET_KEY—sk_test_…in dev,sk_live_…in prod.STRIPE_WEBHOOK_SECRET—whsec_…, one per endpoint; differs in test vs live.
Construct the client (pin the API version)
import Stripe from "stripe";
// Pin apiVersion explicitly so a dashboard-level version bump can never change
// your API behavior under you. Match the version your SDK release ships with.
export const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
apiVersion: "2026-05-27.dahlia",
});
Create a Checkout Session
// Subscription mode — recurring price.
const session = await stripe.checkout.sessions.create({
mode: "subscription",
line_items: [{ price: "price_123", quantity: 1 }], // a recurring Price ID
success_url: `${BASE}/success?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${BASE}/pricing`,
// Tie the session to YOUR user so the webhook can find the right row.
client_reference_id: userId,
// 14-day trial; omit for immediate billing.
subscription_data: { trial_period_days: 14 },
});
// Redirect the browser to session.url.
// Payment mode — one-time charge (e.g. a digital download).
const session = await stripe.checkout.sessions.create({
mode: "payment",
line_items: [{ price: "price_onetime", quantity: 1 }],
success_url: `${BASE}/success?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${BASE}/`,
client_reference_id: userId,
});
success_url is a UX redirect, not proof of payment. The customer can close the
tab before it loads, or hit the URL directly. **Grant access from the webhook,
not the redirect.**
The webhook handler (load-bearing)
This is where integrations break. Three non-negotiables:
- Verify against the RAW body.
constructEventrecomputes the signature
over the exact bytes Stripe sent. Any middleware that parses/re-serializes
the body (e.g. express.json() on this route) changes those bytes and you
get No signatures found matching the expected signature.
- Return 2xx before slow work. Verify, record the event, return 200
immediately. Stripe treats a timeout as failure and retries — for up to 3
days in live mode — so slow handlers cause duplicate delivery.
- Be idempotent. Events are unordered and may arrive more than once.
Dedupe on event.id, persisting the idempotency record in the *same
transaction* as the business write. Default replay tolerance is 5 minutes.
// Express. The route gets the RAW body; do NOT mount express.json() here.
app.post("/webhook", express.raw({ type: "application/json" }), async (req, res) => {
let event: Stripe.Event;
try {
event = stripe.webhooks.constructEvent(
req.body, // raw Buffer, untouched
req.headers["stripe-signature"]!, // header name is lowercase
process.env.STRIPE_WEBHOOK_SECRET!,
);
} catch (err) {
return res.status(400).send(`Webhook Error: ${(err as Error).message}`);
}
// Dedupe + record in one transaction; skip if we have seen this event.id.
const fresh = await recordEventOnce(event.id, event.type);
if (!fresh) return res.status(200).send(); // already processed; ack and stop
// Return 2xx FAST. Hand heavy work to a queue/background job if it is slow.
switch (event.type) {
case "checkout.session.completed": {
const s = event.data.object as Stripe.Checkout.Session;
await grantAccess(s.client_reference_id!, s.customer as string);
break;
}
case "customer.subscription.updated":
case "customer.subscription.deleted": {
const sub = event.data.object as Stripe.Subscription;
await syncSubscription(sub.customer as string, sub.status); // mirror state
break;
}
case "invoice.payment_failed":
// dunning lives here; see references/webhook-events.md
break;
}
res.status(200).send();
});