Verify Stripe webhooks

Every Stripe webhook includes a Stripe-Signature header containing an HMAC signature. This cryptographic signature allows you to verify that requests genuinely originated from Stripe and haven't been tampered with during transmission. Stripe provides official SDKs in multiple languages that handle signature verification for you.

The facts

Signature header
Stripe-Signature

Format: t=<unix seconds>,v1=<hex>

Scheme
HMAC-SHA256
Signed material
{t}.{raw body}

t from the Stripe-Signature header, a literal dot, then the JSON payload as sent.

Replay window
5 minutes

The default tolerance in Stripe's libraries, which you can change. A tolerance of 0 disables the check.

What to build
Recompute a digest over the timestamp and raw body, and compare
Key
shared secret

Stripe webhook secret

Each webhook endpoint has its own signing secret, which starts with whsec_. It isn't your API key. Keep it in an environment variable, not in source code.

  • In the Dashboard: open the Webhooks tab in Workbench, select the endpoint and click Reveal secret.
  • From the API: creating an event destination returns it as webhook_endpoint.signing_secret.
  • One per endpoint: Stripe generates a unique secret for each endpoint, so with several endpoints you need the secret for each one.
  • Test and live mode: if the same endpoint handles test and live API keys, the secret is different for each.
  • Stripe CLI: stripe listen prints its own secret when it starts. It differs from a Dashboard endpoint's secret, so use it only for events the CLI forwards.
  • Rolling: you can roll a secret from the endpoint's overflow menu and keep the old one active for up to 24 hours.

Source: Stripe docs ↗

Code

express/src/index.js
javascript
require('dotenv').config();
const express = require('express');
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);

const app = express();

// Stripe webhook endpoint - must use raw body for signature verification
app.post('/webhooks/stripe',
  express.raw({ type: 'application/json' }),
  async (req, res) => {
    const sig = req.headers['stripe-signature'];

    let event;
    try {
      // Verify the webhook signature using Stripe SDK
      event = stripe.webhooks.constructEvent(
        req.body,
        sig,
        process.env.STRIPE_WEBHOOK_SECRET
      );
    } catch (err) {
      console.error('Webhook signature verification failed:', err.message);
      return res.status(400).send(`Webhook Error: ${err.message}`);
    }

    // Handle the event based on type
    switch (event.type) {
      case 'payment_intent.succeeded':
        const paymentIntent = event.data.object;
        console.log('Payment succeeded:', paymentIntent.id);
        // Your code: Fulfill the order, send confirmation email, etc.
        break;

      case 'payment_intent.payment_failed':
        const failedPayment = event.data.object;
        console.log('Payment failed:', failedPayment.id);
        // Your code: Notify customer, update order status, etc.
        break;

      case 'customer.subscription.created':
        const subscription = event.data.object;
        console.log('Subscription created:', subscription.id);
        // Your code: Provision access, send welcome email, etc.
        break;

      case 'customer.subscription.deleted':
        const canceledSub = event.data.object;
        console.log('Subscription canceled:', canceledSub.id);
        // Your code: Revoke access, send retention email, etc.
        break;

      case 'invoice.paid':
        const invoice = event.data.object;
        console.log('Invoice paid:', invoice.id);
        // Your code: Record payment, update billing history, etc.
        break;

      default:
        console.log(`Unhandled event type: ${event.type}`);
    }

    // Return 200 to acknowledge receipt
    res.json({ received: true });
  }
);

// Health check endpoint
app.get('/health', (req, res) => {
  res.json({ status: 'ok' });
});

// Export app for testing
module.exports = app;

// Start server only when run directly (not when imported for testing)
if (require.main === module) {
  const PORT = process.env.PORT || 3000;
  app.listen(PORT, () => {
    console.log(`Server running on http://localhost:${PORT}`);
    console.log(`Webhook endpoint: POST http://localhost:${PORT}/webhooks/stripe`);
  });
}
nextjs/app/webhooks/stripe/route.ts
typescript
import { NextRequest, NextResponse } from 'next/server';
import Stripe from 'stripe';

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

export async function POST(request: NextRequest) {
  // Get the raw body for signature verification
  const body = await request.text();
  const sig = request.headers.get('stripe-signature');

  if (!sig) {
    return NextResponse.json(
      { error: 'Missing stripe-signature header' },
      { status: 400 }
    );
  }

  let event: Stripe.Event;
  try {
    // Verify the webhook signature using Stripe SDK
    event = stripe.webhooks.constructEvent(
      body,
      sig,
      process.env.STRIPE_WEBHOOK_SECRET!
    );
  } catch (err) {
    const message = err instanceof Error ? err.message : 'Unknown error';
    console.error('Webhook signature verification failed:', message);
    return NextResponse.json(
      { error: `Webhook Error: ${message}` },
      { status: 400 }
    );
  }

  // Handle the event based on type
  switch (event.type) {
    case 'payment_intent.succeeded':
      const paymentIntent = event.data.object as Stripe.PaymentIntent;
      console.log('Payment succeeded:', paymentIntent.id);
      // Your code: Fulfill the order, send confirmation email, etc.
      break;

    case 'payment_intent.payment_failed':
      const failedPayment = event.data.object as Stripe.PaymentIntent;
      console.log('Payment failed:', failedPayment.id);
      // Your code: Notify customer, update order status, etc.
      break;

    case 'customer.subscription.created':
      const subscription = event.data.object as Stripe.Subscription;
      console.log('Subscription created:', subscription.id);
      // Your code: Provision access, send welcome email, etc.
      break;

    case 'customer.subscription.deleted':
      const canceledSub = event.data.object as Stripe.Subscription;
      console.log('Subscription canceled:', canceledSub.id);
      // Your code: Revoke access, send retention email, etc.
      break;

    case 'invoice.paid':
      const invoice = event.data.object as Stripe.Invoice;
      console.log('Invoice paid:', invoice.id);
      // Your code: Record payment, update billing history, etc.
      break;

    default:
      console.log(`Unhandled event type: ${event.type}`);
  }

  // Return 200 to acknowledge receipt
  return NextResponse.json({ received: true });
}
fastapi/main.py
python
import os
from dotenv import load_dotenv
from fastapi import FastAPI, Request, HTTPException
import stripe

load_dotenv()

app = FastAPI()

stripe.api_key = os.environ.get("STRIPE_SECRET_KEY")
webhook_secret = os.environ.get("STRIPE_WEBHOOK_SECRET")


@app.post("/webhooks/stripe")
async def stripe_webhook(request: Request):
    # Get the raw body for signature verification
    payload = await request.body()
    sig_header = request.headers.get("stripe-signature")

    if not sig_header:
        raise HTTPException(status_code=400, detail="Missing stripe-signature header")

    try:
        # Verify the webhook signature using Stripe SDK
        event = stripe.Webhook.construct_event(
            payload=payload,
            sig_header=sig_header,
            secret=webhook_secret
        )
    except ValueError as e:
        # Invalid payload
        raise HTTPException(status_code=400, detail=f"Invalid payload: {str(e)}")
    except stripe.error.SignatureVerificationError as e:
        # Invalid signature
        raise HTTPException(status_code=400, detail=f"Invalid signature: {str(e)}")

    # Handle the event based on type
    event_type = event["type"]
    data_object = event["data"]["object"]

    if event_type == "payment_intent.succeeded":
        print(f"Payment succeeded: {data_object['id']}")
        # Your code: Fulfill the order, send confirmation email, etc.

    elif event_type == "payment_intent.payment_failed":
        print(f"Payment failed: {data_object['id']}")
        # Your code: Notify customer, update order status, etc.

    elif event_type == "customer.subscription.created":
        print(f"Subscription created: {data_object['id']}")
        # Your code: Provision access, send welcome email, etc.

    elif event_type == "customer.subscription.deleted":
        print(f"Subscription canceled: {data_object['id']}")
        # Your code: Revoke access, send retention email, etc.

    elif event_type == "invoice.paid":
        print(f"Invoice paid: {data_object['id']}")
        # Your code: Record payment, update billing history, etc.

    else:
        print(f"Unhandled event type: {event_type}")

    # Return 200 to acknowledge receipt
    return {"received": True}


@app.get("/health")
async def health():
    return {"status": "ok"}


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=3000)

From hookdeck/webhook-skills ↗

Or install the Stripe webhooks skill:

npx skills add hookdeck/webhook-skills --skill stripe-webhooks

Common failures

Body parsed before verification

Frameworks that parse JSON change the bytes. Verify against the raw request body, before any parsing.

Wrong secret

Use the signing secret of the specific endpoint, not your API key. Test and live mode endpoints have different secrets.

Clock skew

The signed timestamp is checked against a tolerance. Keep server clocks in sync with NTP.

From Hookdeck's Stripe guide

Let Event Gateway verify Stripe signatures.

Event Gateway verifies the signature on each Stripe delivery before it reaches your service, then queues it and retries failures on your schedule.

Not affiliated with Stripe. Facts are compiled from public sources and linked inline.