vibesupport
Security Tutorial

Securing Stripe Webhooks in AI SaaS Apps: Don't Give Away Free Subscriptions

Integrating Stripe with AI coding tools like Cursor or Bolt.new often feels effortless: you prompt "Add Stripe checkout and give users 100 AI credits when they pay", and within minutes, the AI generates a checkout session and a webhook endpoint at /api/webhooks/stripe.

However, in nearly half of all AI-generated SaaS applications, the webhook handler contains a catastrophic vulnerability:

It accepts incoming JSON payloads without verifying Stripe's cryptographic signature.

When this vulnerability exists, anyone on the internet can craft a fake checkout.session.completed event, send it to your webhook endpoint via Postman or curl, and credit their account with unlimited free tokens or lifetime subscriptions.


The Fatal Mistake: Parsing JSON Too Early

To verify that a webhook actually came from Stripe, Stripe signs the payload using an HMAC-SHA256 signature and attaches it in the stripe-signature HTTP header.

To verify this signature, you must pass the exact raw text byte buffer of the incoming request to stripe.webhooks.constructEvent().

Here is the flawed pattern AI frequently writes:

ts
// VULNERABLE CODE: DO NOT USE
export async function POST(req: Request) {
  // BUG: Calling req.json() parses the body into an object!
  const event = await req.json();

  if (event.type === "checkout.session.completed") {
    const userId = event.data.object.metadata.userId;
    await grantCredits(userId, 1000); // FREE CREDITS FOR ANYONE!
  }

  return NextResponse.json({ received: true });
}

Because this code never calls constructEvent(), an attacker can send:

bash
curl -X POST https://your-saas.com/api/webhooks/stripe \
  -H "Content-Type: application/json" \
  -d '{
    "type": "checkout.session.completed",
    "data": {
      "object": {
        "metadata": { "userId": "attacker_user_id" },
        "amount_total": 9900,
        "payment_status": "paid"
      }
    }
  }'

Your database will happily credit the attacker's account, and you will never receive a single dollar.


The Raw Body Challenge in Next.js App Router

In Next.js App Router, you must read the body using await req.text() before doing any JSON parsing. Passing a re-stringified JSON object (JSON.stringify(body)) will fail verification because whitespace and key ordering differ from Stripe's raw byte stream.


Complete Production-Ready Stripe Route

Here is the complete, production-tested webhook implementation for Next.js:

ts
// app/api/webhooks/stripe/route.ts
import { NextResponse } from "next/server";
import Stripe from "stripe";
import { db } from "@/server/db";
import { users, processedEvents } from "@/drizzle/schema";
import { eq } from "drizzle-orm";
import "server-only";

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
  apiVersion: "2024-12-18.acacia",
});

const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET!;

export async function POST(req: Request) {
  const signature = req.headers.get("stripe-signature");

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

  // 1. Read raw body as text for cryptographic signature check
  const rawBody = await req.text();
  let event: Stripe.Event;

  try {
    event = stripe.webhooks.constructEvent(rawBody, signature, webhookSecret);
  } 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 }
    );
  }

  // 2. Prevent replay attacks & duplicate event processing (Idempotency)
  const [existingEvent] = await db
    .select()
    .from(processedEvents)
    .where(eq(processedEvents.eventId, event.id));

  if (existingEvent) {
    // Already processed, return 200 so Stripe doesn't keep retrying
    return NextResponse.json({ received: true, duplicate: true });
  }

  // 3. Handle specific event types
  switch (event.type) {
    case "checkout.session.completed": {
      const session = event.data.object as Stripe.Checkout.Session;
      const userId = session.metadata?.userId;

      if (!userId) {
        console.error("Missing userId in session metadata");
        break;
      }

      // Upgrade customer or credit tokens
      await db
        .update(users)
        .set({
          plan: "pro",
          stripeCustomerId: session.customer as string,
          credits: 1000,
        })
        .where(eq(users.id, userId));
      break;
    }

    case "customer.subscription.deleted": {
      const subscription = event.data.object as Stripe.Subscription;
      const customerId = subscription.customer as string;

      // Downgrade customer when subscription is canceled
      await db
        .update(users)
        .set({ plan: "free" })
        .where(eq(users.stripeCustomerId, customerId));
      break;
    }

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

  // 4. Mark event as processed
  await db.insert(processedEvents).values({
    eventId: event.id,
    eventType: event.type,
    createdAt: new Date(),
  });

  return NextResponse.json({ received: true });
}

Idempotency: Why You Must Handle Duplicate Events

Stripe guarantees at-least-once delivery, which means Stripe will occasionally send the exact same event twice (for example, if your server takes more than 5 seconds to reply with a 200 OK).

If you don't track processed event IDs in your database, a customer who bought 500 tokens might receive 1,000 or 1,500 tokens because the webhook fired multiple times.

Creating a small processed_events table solves this permanently.


Testing Locally with the Stripe CLI

Never test webhooks by pushing code to production. Use the official Stripe CLI:

bash
# 1. Login to Stripe CLI
stripe login

# 2. Forward webhook events to your local Next.js server
stripe listen --forward-to localhost:3000/api/webhooks/stripe

# 3. In another terminal, trigger a test payment event
stripe trigger checkout.session.completed

The Stripe CLI will output your local webhook signing secret (whsec_...). Add it to your .env.local and verify that events are processed cleanly.

BUILT WITH AI? A SECOND LOOK BEFORE YOU LAUNCH

Don't let a hidden bug derail your launch.

vibesupport scans your AI-built codebase or live website for exposed secrets, missing database RLS, and broken access controls—then pairs you with senior engineers to fix them directly in GitHub.

Related Tutorials & Guides