Aller au contenu principal

Handle payment webhooks

  • Audience. Developers who have a payment flow and need a reliable fulfillment trigger.
  • Prerequisites. A server endpoint reachable over HTTPS, and the signing secret from the Stripe Dashboard.
  • Goal. Accept a payment_intent.succeeded event, verify its signature, and fulfill the order exactly once.

By the end, you'll have a handler that rejects a forged payload, acknowledges within the timeout, and records each order once. Notice that the signature check runs before any business logic.

Stripe sends a webhook when an object changes state. Your endpoint receives the event, checks the signature, and acts. The handler must respond inside the timeout, because Stripe treats a slow response as a failed delivery and retries.

Delivery path​

Stripe pushes the event to your endpoint within seconds of the state change. Your handler acknowledges with a 2xx status, then processes the event.

Sequence from checkout through PaymentIntent confirmation to a verified webhook and fulfillment

The numbered steps follow one order. Step 7 shows the event arriving after the client already saw a result, so the client can't serve as the fulfillment trigger.

Configure the endpoint​

Register the endpoint in the Dashboard under Developers → Webhooks → Add endpoint. Stripe shows the signing secret once, and the dashboard reveals it again later.

SettingValue for this guide
Endpoint addresshttps://api.example.com/webhooks/stripe
Events to sendpayment_intent.succeeded, payment_intent.payment_failed, charge.refunded
API versionThe version you wrote the handler against

A handler that subscribes to every event receives traffic it never reads. Select the events the handler acts on, and add more when the code changes.

Remarque

The endpoint version can differ from your account version. An event delivers on the version pinned to the endpoint, so read the event's api_version when you log a payload.

Read the raw body​

Signature verification needs the exact bytes Stripe sent. A body parsed into an object loses whitespace and key order, and the signature check then fails.

server.js
import express from "express";
import Stripe from "stripe";

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

// Keep the raw body for the webhook route only.
app.post(
"/webhooks/stripe",
express.raw({ type: "application/json" }),
handleWebhook
);

// Every other route parses JSON.
app.use(express.json());

Register the raw parser before the JSON parser, or the JSON parser consumes the stream first. Reversing the order gives an empty raw body and a signature mismatch on every request.

Verify the signature​

Stripe signs each delivery with the endpoint secret. Compute the expected signature and compare it in constant time.

server.js
async function handleWebhook(req, res) {
const signature = req.headers["stripe-signature"];

let event;

try {
event = stripe.webhooks.constructEvent(
req.body,
signature,
process.env.STRIPE_WEBHOOK_SECRET
);
} catch (err) {
console.error("Signature verification failed:", err.message);
return res.status(400).send(`Webhook error: ${err.message}`);
}

res.status(200).json({ received: true });

await dispatch(event).catch((err) => {
console.error("Handler failed:", err.message);
});
}

The constructEvent call recomputes the signature, rejects a payload older than the timestamp tolerance, and returns a typed event. All three checks run before your code touches the payload.

danger

Never trust an unverified payload. Without the signature check, anyone who finds the endpoint address can mark orders paid or trigger refunds.

Respond before you work​

Stripe waits about 20 seconds for a response. A handler that fulfills an order, sends an email, and updates analytics in the request path runs out of time on a slow dependency. Stripe then repeats the event.

Split the handler into two stages:

  1. Acknowledge. Verify the signature, write the event to a queue, and return 200.
  2. Process. A worker reads the queue and retries the slow work.
dispatch.js
async function dispatch(event) {
switch (event.type) {
case "payment_intent.succeeded":
return handleSucceeded(event.data.object);
case "payment_intent.payment_failed":
return handlePaymentFailed(event.data.object);
case "charge.refunded":
return handleRefunded(event.data.object);
default:
return;
}
}

An unknown event type isn't an error. Stripe adds event types over time, and a handler that throws on an unknown type fails a delivery it could have ignored.

Fulfill exactly once​

Stripe retries a failed delivery and can also deliver the same event twice when a response is slow. Your handler must tolerate duplicates.

fulfillment.js
async function handleSucceeded(intent) {
const already = await hasProcessed(intent.id);
if (already) return;

const orderId = intent.metadata.order_id;
if (!orderId) {
console.warn("Missing order_id on intent", intent.id);
return;
}

await markOrderPaid(orderId, intent.id);
await recordProcessed(intent.id);
}

Store the event ID or the object ID in a unique index and let the database reject a second write. A check followed by a write races when two deliveries arrive at the same moment. A unique constraint can't race.

astuce

Key the deduplication table on event.id for one-shot events and on object.id for state events. A refund sends one charge.refunded event per refund, and only the object ID collapses repeats for a charge.

Handle the failure events​

A payment that fails sends payment_intent.payment_failed. Read the decline code and decide whether the customer can recover.

failures.js
async function handlePaymentFailed(intent) {
const error = intent.last_payment_error;
const code = error?.decline_code ?? error?.code;

const recoverable = ["insufficient_funds", "processing_error"];
const canRetry = recoverable.includes(code);

await recordDecline(intent.metadata.order_id, code, canRetry);

if (canRetry) {
await sendRetryEmail(intent.metadata.order_id);
}
}

Don't retry a hard decline on your own schedule. The issuer blocked the card, and a second attempt only adds another decline to the account record.

Test the endpoint locally​

The Stripe command-line tool forwards live test events to a local server, so you can watch a delivery without deploying.

stripe login
stripe listen --forward-to localhost:4242/webhooks/stripe

The tool prints a signing secret that starts with whsec_. Use that value locally, and use the Dashboard secret in production. Then trigger an event from another terminal.

stripe trigger payment_intent.succeeded

The first terminal shows the event, and the server log shows the handler output. Change the secret to a wrong value and confirm the endpoint returns 400, which proves the signature check runs.

Diagnose a failed delivery​

SymptomCauseFix
400 on every deliverySignature check failed.Use the endpoint secret. Keep the raw body unparsed.
400 after a library upgradeThe parser changed the body before verification.Move the raw parser ahead of the JSON parser.
One delivery repeatsThe handler waited past the timeout.Acknowledge first, process in a worker.
Handler logs show duplicatesThe response ran past the timeout, or a retry overlapped.Deduplicate on event.id with a unique index.
No deliveries at allThe endpoint address fails a health check.Confirm the address returns 2xx for a test event from the Dashboard.

Replay an old event​

The Dashboard keeps event payloads and lets you resend one. Open Developers → Webhooks → your endpoint → Events, pick the delivery, and choose Resend.

A resend gives you the shortest path to test a handler change against a real payload. Capture the response code, because a resend that returns 500 would have failed in production too.

Next steps​