v(i)b(e)c(o)d(e)4u.com
Назад на форум vbcd4u.com
🔥 Нейросети2026-11-17T10:06:00.000Z▲ 0 upvotes

Stripe webhooks in Next.js App Router: signature, raw body and idempotency

@murdasoftРедакция vbcd4u · MurdaSoft
Открыть все обсуждения →

Why is the signature checked before everything else?

The webhook URL is not a secret: it can end up in the logs, in the code, in the browser history. If the handler trusts any POST request with JSON like checkout.session.completed, anyone can “pay” for the order by submitting it themselves. Stripe signs each event with the endpoint-specific secret (whsec_...) and passes the signature in the Stripe-Signature header. Signature verification is the first line of the handler, before parsing JSON and any business logic.

Handler in App Router

// app/api/stripe/webhook/route.ts
import Stripe from "stripe";
import { NextResponse } from "next/server";
import { db } from "@/lib/db";

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
const endpointSecret = process.env.STRIPE_WEBHOOK_SECRET!;

export async function POST(req: Request) {
  const signature = req.headers.get("stripe-signature");
  if (!signature) return new NextResponse("missing signature", { status: 400 });

  const payload = await req.text(); // сырое тело, байт в байт

  let event: Stripe.Event;
  try {
    event = stripe.webhooks.constructEvent(payload, signature, endpointSecret);
  } catch {
    return new NextResponse("bad signature", { status: 400 });
  }

  const fresh = await db.query(
    "INSERT INTO stripe_events (id, type) VALUES ($1, $2) ON CONFLICT (id) DO NOTHING",
    [event.id, event.type]
  );
  if (fresh.rowCount === 0) return NextResponse.json({ received: true, duplicate: true });

  try {
    await handleEvent(event);
  } catch (err) {
    await db.query("DELETE FROM stripe_events WHERE id = $1", [event.id]);
    throw err; // 500 — Stripe повторит доставку
  }
  return NextResponse.json({ received: true });
}

Raw body

constructEvent calculates the HMAC from the body exactly as it was sent by Stripe. If you call req.json() first and then JSON.stringify, the order of the keys, spaces and escaping will be different, and the signature will not match. In App Router, no separate configuration is required: req.text() returns the body unchanged. The bodyParser: false config is only needed in the old Pages Router.

The handler must run in Node.js runtime (it does by default). If you need Edge, use the asynchronous option with Web Crypto:

const provider = Stripe.createSubtleCryptoProvider();
event = await stripe.webhooks.constructEventAsync(payload, signature, endpointSecret, undefined, provider);

The check also rejects events with a timestamp that is too old (the default tolerance is 5 minutes), which protects against resubmitting an intercepted request.

Idempotency by event.id

Stripe guarantees “at least once” delivery. One event can come twice: during a network failure, when your response timeouts, or when manually resent from Dashboard. In live mode, Stripe repeats failed deliveries for several days.

CREATE TABLE stripe_events (
  id          text PRIMARY KEY,         -- evt_...
  type        text NOT NULL,
  received_at timestamptz NOT NULL DEFAULT now()
);

The insert with ON CONFLICT DO NOTHING atomically answers the question “did we see this event.” If processing fails, the record is deleted and the redelivery will be processed again. It is more reliable to insert an event and order change in one transaction: then there is no partially applied state.

Processing: do not trust the order and the picture

async function handleEvent(event: Stripe.Event) {
  switch (event.type) {
    case "checkout.session.completed": {
      const session = event.data.object as Stripe.Checkout.Session;
      if (session.payment_status !== "paid") return; // асинхронные методы оплаты
      await markOrderPaid(session.client_reference_id!, session.id);
      return;
    }
    case "customer.subscription.updated":
    case "customer.subscription.deleted": {
      const sub = event.data.object as Stripe.Subscription;
      const current = await stripe.subscriptions.retrieve(sub.id);
      await syncSubscription(current);
      return;
    }
    default:
      return; // неизвестные типы — 200, иначе Stripe будет повторять
  }
}

Events do not have to arrive in the order of occurrence: subscription.updated may arrive before subscription.created. The object in the event is a snapshot at the time of the event, not the current state. For subscriptions, it is more reliable to re-read the object via the API and synchronize the current state than to use snapshots one by one.

You pass client_reference_id when creating a Checkout Session - use it to find your order. Check the amount with the amount from your database, and do not take it from the event on faith.

Quick reply

Stripe waits a limited time for a 2xx response. Sending emails, generating PDFs, and calling third-party APIs inside the handler lengthens the response and increases the chance of re-delivery. Place the hard work in a queue or task table, and only record the fact in the handler.

Local check

stripe listen --forward-to localhost:3000/api/stripe/webhook
# выведет whsec_... — это секрет для локального запуска, он отличается от секрета в Dashboard
stripe trigger checkout.session.completed

Diagnostics

  • “No signatures found matching the expected signature.” The body was changed before verification, or the secret is not from this endpoint. The test and live modes, the CLI and each endpoint in the Dashboard have their own secrets.
  • The signature does not match only in production. A proxy or platform changes the body (compression, recoding) before the application. Check that the request arrives without transformations.
  • Duplicate orders. There is no unique constraint on event.id or on order ID, processing is not idempotent.
  • The fields in the event are different from the documentation. The event format is determined by the API version selected for the endpoint in Dashboard, not the SDK version in the code.

When less is enough

If payments are made in units and orders are confirmed manually, checking the signature and a unique key for the order will suffice. The event table and queue pay for themselves when, after payment, access is automatically granted, letters are sent, or subscriptions are changed.

Нужна реализация под ваш проект или аудит архитектуры?

Разрабатываем сайты на Next.js, Telegram-ботов, интеграции с CRM и ИИ-агентов под ключ.

Обсуждение (0)

Ещё на vbcd4u.com