Stripe Checkout with verified webhooks, refunds and idempotency

Sell one-time products with a Stripe-hosted Checkout page: create Checkout Sessions on your server, fulfil orders from signature-verified webhooks (raw body + Stripe-Signature), check PaymentIntent status, refund safely and retry with idempotency keys.

Provider
Stripe
Level
Intermediate
Stacks
Node.js (Express), Python (FastAPI), PHP (Laravel), Java (Spring), React, TypeScript
Code maturity
Sandbox-ready
Last verified
25 Nov 2026

Introduction

Stripe Checkout is a payment page hosted by Stripe. Your server creates a Checkout Session describing what the customer is buying, you send the customer to the session's URL, and Stripe handles card entry, wallets, 3D Secure and local payment methods.

The part most tutorials get wrong is what happens after payment. Stripe's own fulfilment guide is explicit: you cannot rely on the customer reaching your success page, so webhooks are required for fulfilment. This guide builds the full loop in test mode:

  • create a Checkout Session with an idempotency key,
  • receive checkout.session.completed on a webhook endpoint and verify the Stripe-Signature header against the raw request body,
  • fulfil each order exactly once, even when events arrive twice or concurrently,
  • read the PaymentIntent status, and issue refunds safely.

Tip: Snippets are shown for Node/Express first, then FastAPI, Laravel, Spring and React. The flow is identical in every stack; only the way you read the raw request body changes.

What Checkout and webhooks do

Three Stripe objects matter here:

  • Checkout Session (cs_...) — the hosted payment page for one purchase. Its payment_status is paid, unpaid or no_payment_required.
  • PaymentIntent (pi_...) — the underlying payment. Its status is one of requires_payment_method, requires_confirmation, requires_action, processing, requires_capture, canceled or succeeded.
  • Event (evt_...) — a notification Stripe POSTs to your webhook endpoint, e.g. checkout.session.completed.

The flow: your server creates the session → the browser is redirected to session.url → the customer pays → Stripe sends checkout.session.completed to your webhook and redirects the customer to your success_url with {CHECKOUT_SESSION_ID} filled in. Both paths call the same idempotent fulfillCheckout(sessionId) function, which re-reads the session from the API before doing anything.

Countries and availability

Stripe accounts can be opened in a specific list of countries, and customers can usually pay from anywhere their card or payment method works. The list changes, so check stripe.com/global for merchant availability and the payment methods guide for which methods each country supports.

If your business is in a country Stripe does not support, look at the provider directory for local alternatives — this guide does not cover workarounds such as foreign entities.

Payment methods

Checkout shows cards plus whatever methods you enable in the Dashboard (wallets such as Apple Pay / Google Pay, bank debits, bank redirects, BNPL, vouchers). With dynamic payment methods you don't list types in code; Stripe chooses eligible ones per customer.

Some methods are delayed-notification (for example ACH Direct Debit and other bank transfers): Checkout completes with payment_status: "unpaid" and Stripe later sends checkout.session.async_payment_succeeded or checkout.session.async_payment_failed. Your webhook must handle those events too.

When to use this approach

  • You sell one-time products or services and want a secure, PCI-light hosted payment page.
  • You want cards, wallets and local methods without building UI for each.
  • You need dependable fulfilment (licences, downloads, credits, shipping) driven by server-side events.
  • You want a path to subscriptions later — the same session and webhook pattern is reused in the Stripe Billing guide.

When not to use it

  • You need a fully custom, on-page payment form → use the Payment Element (Elements) instead; the webhook part of this guide still applies.
  • Recurring billing → see the stripe-billing-subscriptions guide (Checkout in subscription mode).
  • Marketplace payouts to third parties → Stripe Connect has extra onboarding and compliance steps not covered here.
  • In-person payments → Stripe Terminal.
  • Your business country is not supported by Stripe.

Example scenarios

  • Course platform: a learner buys a course; the webhook grants access and emails a receipt.
  • Digital downloads: the success page shows the download link immediately (fulfilled from the landing page), and the webhook guarantees fulfilment if the browser closed.
  • Event tickets with bank debit: the session completes unpaid; tickets are reserved, and issued only on checkout.session.async_payment_succeeded.

Registration

  • Create an account at dashboard.stripe.com/register. You can use test mode / sandboxes immediately, before activating the account.
  • To accept live payments, activate the account: business details, representative identity, bank account for payouts. Requirements vary by country.
  • In the Dashboard, create a Product with a Price (or pass price_data inline when creating the session).

Sandbox / test mode

Every Stripe account has test-mode keys (sk_test_..., pk_test_...); newer accounts can also create isolated sandboxes. Objects created with test keys never move real money and are invisible to live keys — and vice versa, which is a common source of No such price errors.

Install the Stripe CLI to forward webhook events to localhost and trigger test events.

Credentials

  • Secret key sk_test_... / sk_live_... — server only. Prefer a restricted key limited to the resources you use (Checkout Sessions, PaymentIntents, Refunds).
  • Publishable key pk_... — safe in the browser; only needed if you use Stripe.js / Elements. A pure redirect-to-Checkout flow does not need it.
  • Webhook signing secret whsec_... — one per endpoint. The secret printed by stripe listen is different from the one for a Dashboard endpoint.

Security: Never commit keys, never send the secret key to the browser, and never log full webhook signatures or secrets. Roll a key immediately if it leaks.

Environment configuration

Keep every secret in environment variables. A typical .env.example (placeholders only):

.env.example

# Stripe — test-mode placeholders, never real values in git
STRIPE_SECRET_KEY=sk_test_replace_me
STRIPE_PUBLISHABLE_KEY=pk_test_replace_me
# From `stripe listen` (local) or the Dashboard endpoint (deployed)
STRIPE_WEBHOOK_SECRET=whsec_replace_me
# A Price created in test mode, e.g. price_123
STRIPE_PRICE_ID=price_replace_me
APP_URL=http://localhost:4242

Authentication

Stripe's API uses your secret key as a bearer credential (HTTP Basic with the key as username when using curl). The official SDKs handle this when you construct the client.

API versions: Stripe releases monthly, non-breaking versions plus twice-yearly major releases; the versioning page listed 2026-11-18.endive as current on the check date. Recent SDKs (stripe-node v12+, stripe-python v6+, stripe-php v11+, stripe-java) pin the API version that was current at the SDK release, so upgrade deliberately and set your webhook endpoint's API version to match your SDK.

curl — list a few PaymentIntents (test key)

curl https://api.stripe.com/v1/payment_intents?limit=3 \
  -u "$STRIPE_SECRET_KEY:"

Backend: create a Checkout Session

The server decides what is being bought and how much — never accept a price or amount from the browser. Look the item up in your database (or use a Stripe Price ID), create an order row in pending state, then create the session.

Pass your own order ID as client_reference_id and in metadata so the webhook can find the order. Use an idempotency key derived from the order so a retried request can't create a second session.

server.js — create a session (Express, stripe-node) · Node.js (Express)

import express from "express";
import Stripe from "stripe";

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
const app = express();

// IMPORTANT: the webhook route (see Webhooks) is registered BEFORE express.json().
app.use(express.json());

app.post("/api/checkout", async (req, res) => {
  const order = await db.orders.createPending({ userId: req.user.id, sku: req.body.sku }); // your DB
  try {
    const session = await stripe.checkout.sessions.create(
      {
        mode: "payment",
        line_items: [{ price: process.env.STRIPE_PRICE_ID, quantity: 1 }],
        client_reference_id: order.id,
        metadata: { orderId: order.id },
        success_url: `${process.env.APP_URL}/success?session_id={CHECKOUT_SESSION_ID}`,
        cancel_url: `${process.env.APP_URL}/cart`,
      },
      { idempotencyKey: `checkout-${order.id}` },
    );
    await db.orders.update(order.id, { stripeSessionId: session.id });
    res.json({ url: session.url });
  } catch (err) {
    console.error("checkout create failed", err.type, err.code);
    res.status(502).json({ error: "Could not start checkout" });
  }
});

main.py — create a session (FastAPI, stripe-python) · Python (FastAPI)

import os
import stripe
from fastapi import FastAPI, HTTPException

stripe.api_key = os.environ["STRIPE_SECRET_KEY"]
app = FastAPI()

@app.post("/api/checkout")
def create_checkout(body: dict):
    order = orders.create_pending(sku=body["sku"])  # your DB
    try:
        session = stripe.checkout.Session.create(
            mode="payment",
            line_items=[{"price": os.environ["STRIPE_PRICE_ID"], "quantity": 1}],
            client_reference_id=order.id,
            metadata={"orderId": order.id},
            success_url=os.environ["APP_URL"] + "/success?session_id={CHECKOUT_SESSION_ID}",
            cancel_url=os.environ["APP_URL"] + "/cart",
            idempotency_key=f"checkout-{order.id}",
        )
    except stripe.StripeError as e:
        raise HTTPException(502, "Could not start checkout") from e
    orders.update(order.id, stripe_session_id=session.id)
    return {"url": session.url}

CheckoutController.php (Laravel, stripe-php) · PHP (Laravel)

<?php
namespace App\Http\Controllers;

use App\Models\Order;
use Illuminate\Http\Request;
use Stripe\StripeClient;

class CheckoutController extends Controller
{
    public function store(Request $request)
    {
        $data = $request->validate(['sku' => 'required|string|max:64']);
        $order = Order::createPending($request->user(), $data['sku']); // your model
        $stripe = new StripeClient(config('services.stripe.secret')); // reads env('STRIPE_SECRET_KEY')

        $session = $stripe->checkout->sessions->create([
            'mode' => 'payment',
            'line_items' => [['price' => config('services.stripe.price'), 'quantity' => 1]],
            'client_reference_id' => (string) $order->id,
            'metadata' => ['orderId' => (string) $order->id],
            'success_url' => config('app.url') . '/success?session_id={CHECKOUT_SESSION_ID}',
            'cancel_url' => config('app.url') . '/cart',
        ], ['idempotency_key' => 'checkout-' . $order->id]);

        $order->update(['stripe_session_id' => $session->id]);
        return response()->json(['url' => $session->url]);
    }
}

CheckoutController.java (Spring Boot, stripe-java) · Java (Spring)

@RestController
public class CheckoutController {
  public CheckoutController(@Value("${STRIPE_SECRET_KEY}") String key) { Stripe.apiKey = key; }

  @Value("${STRIPE_PRICE_ID}") String priceId;
  @Value("${APP_URL}") String appUrl;

  @PostMapping("/api/checkout")
  public Map<String, String> create(@RequestBody Map<String, String> body) throws StripeException {
    Order order = orders.createPending(body.get("sku")); // your repository
    SessionCreateParams params = SessionCreateParams.builder()
        .setMode(SessionCreateParams.Mode.PAYMENT)
        .addLineItem(SessionCreateParams.LineItem.builder().setPrice(priceId).setQuantity(1L).build())
        .setClientReferenceId(order.getId())
        .putMetadata("orderId", order.getId())
        .setSuccessUrl(appUrl + "/success?session_id={CHECKOUT_SESSION_ID}")
        .setCancelUrl(appUrl + "/cart")
        .build();
    RequestOptions opts = RequestOptions.builder().setIdempotencyKey("checkout-" + order.getId()).build();
    Session session = Session.create(params, opts);
    orders.saveSessionId(order.getId(), session.getId());
    return Map.of("url", session.getUrl());
  }
}

Warning: Amounts are in the currency's smallest unit (e.g. 2000 = $20.00) when you use price_data.unit_amount; zero-decimal currencies such as JPY are not multiplied by 100. Using a Price ID avoids most of these mistakes.

Tip: The Spring snippet omits imports (com.stripe.Stripe, com.stripe.model.checkout.Session, com.stripe.param.checkout.SessionCreateParams, com.stripe.net.RequestOptions) for length; it is marked simplified.

Frontend: send the customer to Checkout

The browser only asks your server to start checkout and then follows the returned URL. It never sends prices, and it never decides whether the order is paid.

Older tutorials call stripe.redirectToCheckout() from Stripe.js; the current fulfilment docs simply redirect to the Session's url, which needs no publishable key on the client.

CheckoutButton.jsx · React

import { useState } from "react";

export default function CheckoutButton({ sku }) {
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState("");

  async function start() {
    setBusy(true);
    setError("");
    try {
      const res = await fetch("/api/checkout", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify({ sku }), // only an identifier — the server sets the price
      });
      if (!res.ok) throw new Error("Checkout unavailable");
      const { url } = await res.json();
      window.location.assign(url);
    } catch (e) {
      setError(e.message);
      setBusy(false);
    }
  }

  return (
    <>
      <button type="button" onClick={start} disabled={busy}>
        {busy ? "Redirecting…" : "Pay with Stripe"}
      </button>
      {error && <p role="alert">{error}</p>}
    </>
  );
}

Initiating the payment

Initiation is the checkout.sessions.create call above. Points worth knowing:

  • mode: "payment" for one-time purchases (subscription and setup are the other modes).
  • The default ui_mode is the full hosted page; set the success_url with the literal {CHECKOUT_SESSION_ID} placeholder — Stripe substitutes it.
  • When a webhook endpoint listens for checkout.session.completed and you set a success_url, Checkout waits up to 10 seconds for your endpoint to respond before redirecting. Respond fast.
  • Sessions expire (you'll receive checkout.session.expired); mark the pending order abandoned when that happens.

curl — equivalent request

curl https://api.stripe.com/v1/checkout/sessions \
  -u "$STRIPE_SECRET_KEY:" \
  -H "Idempotency-Key: checkout-order_123" \
  -d mode=payment \
  -d "line_items[0][price]=$STRIPE_PRICE_ID" \
  -d "line_items[0][quantity]=1" \
  -d client_reference_id=order_123 \
  --data-urlencode "success_url=http://localhost:4242/success?session_id={CHECKOUT_SESSION_ID}"

Confirmation: one idempotent fulfil function

Stripe's fulfilment guide asks for a single fulfill_checkout(session_id) function that:

  • is safe to call multiple times, even concurrently, with the same session ID;
  • retrieves the Checkout Session from the API with line_items expanded (never trust data passed in from the browser);
  • checks payment_status — fulfil only when it is not unpaid;
  • fulfils, then records that this session has been fulfilled.

Call it from the webhook and from your success page. The success page gives instant feedback; the webhook guarantees fulfilment when the customer never comes back.

fulfill.ts — idempotent fulfilment (TypeScript, stripe-node) · TypeScript

import Stripe from "stripe";

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY as string);

/** Safe to call from the webhook and the success page, any number of times. */
export async function fulfillCheckout(sessionId: string): Promise<"fulfilled" | "already" | "unpaid"> {
  // 1. Claim the session atomically. A UNIQUE index on fulfilments.session_id makes
  //    concurrent calls safe: only one insert wins.
  const claimed = await db.fulfilments.tryInsert({ sessionId, state: "processing" });
  if (!claimed) return "already";

  try {
    // 2. Re-read the truth from Stripe.
    const session: Stripe.Checkout.Session = await stripe.checkout.sessions.retrieve(sessionId, {
      expand: ["line_items"],
    });

    // 3. Delayed methods complete the session while still unpaid.
    if (session.payment_status === "unpaid") {
      await db.fulfilments.delete(sessionId); // allow a later async_payment_succeeded to claim it
      return "unpaid";
    }

    // 4. Cross-check against YOUR order, then deliver.
    const orderId = session.client_reference_id;
    const order = orderId ? await db.orders.get(orderId) : null;
    if (!order || order.stripeSessionId !== session.id) throw new Error("order mismatch");
    if (session.amount_total !== order.expectedAmount || session.currency !== order.currency) {
      throw new Error("amount mismatch");
    }
    await grantAccess(order, session.line_items?.data ?? []);
    await db.orders.update(order.id, { status: "paid", paymentIntentId: session.payment_intent });
    await db.fulfilments.update(sessionId, { state: "done" });
    return "fulfilled";
  } catch (err) {
    await db.fulfilments.delete(sessionId); // release the claim so a retry can try again
    throw err;
  }
}

Security: Never mark an order paid just because the browser reached /success. Always re-read the Checkout Session (or PaymentIntent) from Stripe with your secret key.

Webhooks: verify Stripe-Signature on the raw body

Every event carries a Stripe-Signature header (t=<timestamp>,v1=<signature>,...). The SDK's constructEvent / construct_event recomputes an HMAC-SHA256 over the exact raw bytes of the body using your endpoint's whsec_ secret and checks the timestamp tolerance (5 minutes by default — never set it to 0).

If any framework middleware parses the JSON first, the bytes change and verification fails with *No signatures found matching the expected signature for payload*. In Express, register the webhook route with express.raw() before app.use(express.json()).

Events to handle for Checkout: checkout.session.completed, checkout.session.async_payment_succeeded, checkout.session.async_payment_failed, checkout.session.expired. Return 2xx quickly; do slow work asynchronously. Return 400 only for verification failures, and 200 for event types you ignore.

webhook.js — Express (register before express.json()) · Node.js (Express)

import express from "express";
import Stripe from "stripe";
import { fulfillCheckout } from "./fulfill.js";

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
export const webhookRouter = express.Router();

webhookRouter.post("/webhook", express.raw({ type: "application/json" }), async (req, res) => {
  let event;
  try {
    // req.body is a Buffer here — exactly what Stripe signed.
    event = stripe.webhooks.constructEvent(req.body, req.headers["stripe-signature"], process.env.STRIPE_WEBHOOK_SECRET);
  } catch (err) {
    console.warn("stripe webhook rejected:", err.message);
    return res.status(400).send("Invalid signature");
  }

  // Event-level dedupe (Stripe may deliver the same event more than once).
  if (!(await db.webhookEvents.tryInsert(event.id))) return res.sendStatus(200);

  try {
    switch (event.type) {
      case "checkout.session.completed":
      case "checkout.session.async_payment_succeeded":
        await fulfillCheckout(event.data.object.id);
        break;
      case "checkout.session.async_payment_failed":
        await db.orders.markFailed(event.data.object.client_reference_id);
        break;
      case "checkout.session.expired":
        await db.orders.markAbandoned(event.data.object.client_reference_id);
        break;
      default:
        break; // ignore other types, still 200
    }
    res.sendStatus(200);
  } catch (err) {
    await db.webhookEvents.delete(event.id); // let Stripe's retry reprocess it
    res.sendStatus(500);
  }
});

// app.js:  app.use(webhookRouter);  app.use(express.json());  ...other routes

webhook.py — FastAPI (await request.body()) · Python (FastAPI)

import os
import stripe
from fastapi import APIRouter, Request, Response

router = APIRouter()
WEBHOOK_SECRET = os.environ["STRIPE_WEBHOOK_SECRET"]

@router.post("/webhook")
async def stripe_webhook(request: Request):
    payload = await request.body()  # raw bytes — do NOT use request.json() first
    sig = request.headers.get("stripe-signature", "")
    try:
        event = stripe.Webhook.construct_event(payload, sig, WEBHOOK_SECRET)
    except ValueError:
        return Response("Invalid payload", status_code=400)
    except stripe.SignatureVerificationError:
        return Response("Invalid signature", status_code=400)

    if not webhook_events.try_insert(event["id"]):  # already processed
        return Response(status_code=200)

    obj = event["data"]["object"]
    try:
        if event["type"] in ("checkout.session.completed", "checkout.session.async_payment_succeeded"):
            fulfill_checkout(obj["id"])  # same idempotent function as the TS example
        elif event["type"] == "checkout.session.async_payment_failed":
            orders.mark_failed(obj.get("client_reference_id"))
    except Exception:
        webhook_events.delete(event["id"])
        return Response(status_code=500)
    return Response(status_code=200)

StripeWebhookController.php (Laravel; route in routes/api.php, no CSRF) · PHP (Laravel)

<?php
namespace App\Http\Controllers;

use App\Services\Fulfilment;
use Illuminate\Http\Request;
use Stripe\Exception\SignatureVerificationException;
use Stripe\Webhook;

class StripeWebhookController extends Controller
{
    public function __invoke(Request $request, Fulfilment $fulfilment)
    {
        $payload = $request->getContent();          // raw body string
        $signature = $request->header('Stripe-Signature', '');
        try {
            $event = Webhook::constructEvent($payload, $signature, config('services.stripe.webhook_secret'));
        } catch (\UnexpectedValueException | SignatureVerificationException $e) {
            return response('Invalid', 400);
        }

        if (! $fulfilment->claimEvent($event->id)) {   // unique index on event id
            return response('', 200);
        }

        $session = $event->data->object;
        match ($event->type) {
            'checkout.session.completed', 'checkout.session.async_payment_succeeded' => $fulfilment->fulfil($session->id),
            'checkout.session.async_payment_failed' => $fulfilment->markFailed($session->client_reference_id),
            default => null,
        };
        return response('', 200);
    }
}

// routes/api.php:  Route::post('/stripe/webhook', StripeWebhookController::class);

StripeWebhookController.java (Spring; @RequestBody String keeps the raw body) · Java (Spring)

@RestController
public class StripeWebhookController {
  @Value("${STRIPE_WEBHOOK_SECRET}") String endpointSecret;

  @PostMapping(value = "/webhook", consumes = "application/json")
  public ResponseEntity<String> handle(@RequestBody String payload,
                                       @RequestHeader("Stripe-Signature") String sigHeader) {
    Event event;
    try {
      event = Webhook.constructEvent(payload, sigHeader, endpointSecret);
    } catch (SignatureVerificationException e) {
      return ResponseEntity.badRequest().body("Invalid signature");
    }
    if (!webhookEvents.tryInsert(event.getId())) return ResponseEntity.ok("");

    switch (event.getType()) {
      case "checkout.session.completed", "checkout.session.async_payment_succeeded" -> {
        // Re-read the session by id inside fulfil(); don't rely on the payload object.
        String sessionId = event.getDataObjectDeserializer().getObject()
            .map(o -> ((com.stripe.model.checkout.Session) o).getId()).orElseThrow();
        fulfilment.fulfil(sessionId);
      }
      default -> { /* ignore */ }
    }
    return ResponseEntity.ok("");
  }
}

Security: Signature verification proves the request came from Stripe and wasn't modified. Stripe additionally publishes webhook source IP addresses you can allowlist — use both.

Warning: In Spring, getDataObjectDeserializer().getObject() is empty when the event's API version differs from the version your stripe-java release pins. Create the endpoint with the same API version as your SDK, or fall back to reading the id and retrieving the object.

Checking payment status

When you need the current truth (support tickets, reconciliation jobs, a delayed webhook), retrieve the object instead of guessing:

  • checkout.sessions.retrieve(id) → status (open, complete, expired) and payment_status (paid, unpaid, no_payment_required).
  • paymentIntents.retrieve(id) → status: requires_payment_method, requires_confirmation, requires_action, processing, requires_capture, canceled, succeeded. Only succeeded means the funds were collected (with capture_method: manual, requires_capture means authorised but not yet captured).

If your endpoint was down, Stripe retries automatically for up to three days; to recover faster, list events with delivery_success=false and process them through the same idempotent handler.

Status endpoint for support/admin use · Node.js (Express)

app.get("/admin/orders/:id/stripe-status", requireStaff, async (req, res) => {
  const order = await db.orders.get(req.params.id);
  if (!order?.stripeSessionId) return res.sendStatus(404);
  const session = await stripe.checkout.sessions.retrieve(order.stripeSessionId, {
    expand: ["payment_intent"],
  });
  res.json({
    sessionStatus: session.status,
    paymentStatus: session.payment_status,
    paymentIntentStatus: session.payment_intent?.status ?? null,
  });
});

Refunds

Create refunds server-side against the PaymentIntent, from an authenticated staff action. Pass amount (minor units) for a partial refund; omit it for a full refund. Use an idempotency key tied to your own refund record so a double-click can't refund twice.

Refunds can be pending, requires_action, succeeded, failed or canceled; listen for refund.updated / refund.failed (and charge.refunded) to keep your records in sync rather than assuming success from the API response.

Refund an order (staff only) · Node.js (Express)

app.post("/admin/orders/:id/refund", requireStaff, async (req, res) => {
  const order = await db.orders.get(req.params.id);
  if (!order || order.status !== "paid") return res.status(409).json({ error: "Not refundable" });

  const amount = req.body.amount == null ? undefined : Number.parseInt(req.body.amount, 10);
  if (amount !== undefined && (!Number.isInteger(amount) || amount <= 0 || amount > order.expectedAmount)) {
    return res.status(400).json({ error: "Invalid amount" });
  }

  const refundRow = await db.refunds.create({ orderId: order.id, amount, requestedBy: req.user.id });
  const refund = await stripe.refunds.create(
    { payment_intent: order.paymentIntentId, amount, metadata: { orderId: order.id } },
    { idempotencyKey: `refund-${refundRow.id}` },
  );
  await db.refunds.update(refundRow.id, { stripeRefundId: refund.id, status: refund.status });
  res.json({ status: refund.status });
});

Error handling

The SDKs throw typed errors. The useful ones:

  • Card errors (StripeCardError, type: card_error) — e.g. code: card_declined with a decline_code such as generic_decline or insufficient_funds. With hosted Checkout, Stripe shows these to the customer; you mostly see them in logs and events.
  • Invalid request (StripeInvalidRequestError) — bad parameters, No such price (test vs live mismatch), or an idempotency_error when a key is reused with different parameters.
  • Authentication (StripeAuthenticationError) — wrong or revoked key.
  • Rate limits (HTTP 429) and API connection errors — retry with exponential backoff and the same idempotency key.

For v1 APIs, Stripe stores the first response for an idempotency key (including 500s) and returns it on retries; keys may be pruned after at least 24 hours.

Going to production

  • Activate the account and switch to live keys via environment variables (no code changes).
  • Register a live webhook endpoint (HTTPS with a valid certificate; Stripe supports TLS 1.2 and 1.3) subscribed only to the events you handle.
  • Set the endpoint's API version to match your SDK; plan upgrades using the changelog.
  • Use restricted keys, roll secrets periodically (Stripe lets an old webhook secret stay valid for up to 7 days while you deploy the new one).
  • Process events through a queue so month-start spikes don't time out your endpoint.
  • Configure Radar rules and receipts; reconcile payouts with balance transactions.

Security checklist

  • Secret key and whsec_ secret only in server env vars; restricted keys where possible.
  • Verify every webhook signature on the raw body; never disable the timestamp tolerance.
  • Price and amount come from your server/DB or Stripe Prices — never from the client.
  • Fulfil only after re-reading the session/PaymentIntent from Stripe; ignore what the redirect URL claims.
  • Idempotent fulfilment (unique constraint on session id and event id).
  • Exempt only the webhook route from CSRF; keep CSRF on everything else.
  • Refunds and status endpoints behind staff authorisation, audited.
  • Don't put personal data in idempotency keys or metadata you don't need.

Testing

Forward events to your machine and complete a test checkout:

  • Card 4242 4242 4242 4242 — succeeds. Any future expiry (e.g. 12/34), any 3-digit CVC.
  • Card 4000 0000 0000 3220 — requires 3D Secure authentication.
  • Card 4000 0000 0000 0002 — declined (card_declined / generic_decline).
  • Card 4000 0000 0000 9995 — declined (insufficient_funds).

For server-side API tests without a browser, Stripe recommends test PaymentMethods such as pm_card_visa instead of raw card numbers.

Stripe CLI — forward and trigger events

stripe login
# Prints the whsec_ secret for THIS forwarding session — put it in STRIPE_WEBHOOK_SECRET
stripe listen --forward-to localhost:4242/webhook
# (current docs show `stripe listen --all-snapshot --forward-to ...` with CLI v1.51+)

# In another terminal:
stripe trigger checkout.session.completed
stripe trigger payment_intent.succeeded

Tip: Write an automated test that posts a body signed with a test secret to your webhook handler (stripe-node exposes stripe.webhooks.generateTestHeaderString) and asserts that a second delivery of the same event does not fulfil twice.

Common mistakes

  • Parsing JSON before verification. app.use(express.json()) placed before the webhook route, Next.js body parsing, or re-serialising with JSON.stringify(req.body) changes the bytes → signature failure.
  • Wrong signing secret. Using the stripe listen secret in production or the Dashboard secret locally; trailing whitespace in the env var.
  • Fulfilling from the success page only. Customers close tabs; delayed methods complete later. Webhooks are required.
  • Not handling async_payment_succeeded. Bank debits complete the session as unpaid.
  • Non-idempotent fulfilment. Duplicate deliveries and the success page racing the webhook grant access twice.
  • Trusting client amounts or decimals (20.00) instead of minor units (2000).
  • Slow handlers. Doing heavy work before returning 2xx → timeouts → retries → duplicates.
  • Returning 4xx/5xx for unhandled event types, so Stripe keeps retrying them.
  • Reusing an idempotency key with different parameters → idempotency_error.

Troubleshooting

  • No signatures found matching the expected signature for payload — the body was modified or the secret is wrong. Log Buffer.isBuffer(req.body) in Express; print the secret's last 4 characters and compare with the Dashboard / CLI.
  • Timestamp outside the tolerance zone — server clock drift or a replayed request; sync with NTP.
  • Header has no t= / v1= — you're reading the wrong header or a proxy strips it. Your parser must also accept unknown extra entries in the header.
  • Webhook shows 302/3xx — redirects (http→https, trailing slash, auth redirect) count as failures; use the final URL.
  • 403/419 from Laravel or Django — CSRF middleware is blocking the webhook route.
  • No such checkout.session / No such price — test object used with a live key (or a different account / sandbox).
  • Events never arrive locally — stripe listen not running, or the forward URL path doesn't match your route.
  • Missed events after an outage — list events with delivery_success=false and replay through your idempotent handler.

Further reading

Official documentation

Everything in this guide was checked against Stripe's documentation on 2026-11-25. Stripe ships monthly API versions, so re-check the pages below — especially the webhook and versioning pages — before you go live:

Official documentation

Sources

More payment guides