Full-Stack SaaS•8 min read•0 views•

Production Stripe Billing: Webhook Security, Dunning & Multi-Tenant SaaS Architecture

A complete engineering guide to implementing bulletproof Stripe Checkout, idempotency locks, subscription tier updates, and customer portal webhooks in Next.js.

Abu Nayem

Abu Nayem

Full-Stack Developer & AI Specialist

Production Stripe Billing: Webhook Security, Dunning & Multi-Tenant SaaS Architecture

1. Creating Secure Stripe Checkout Sessions

When users click 'Upgrade Plan', create an authenticated Stripe Checkout session containing their Organization ID and customer email in session metadata.

Never pass price amounts from the client; always reference server-side verified Stripe Price IDs.

2. Verifying Raw Webhook Signatures in App Router

In Next.js App Router, ensure you read `req.text()` to extract the raw unparsed request buffer before passing it to `stripe.webhooks.constructEvent()`:

app/api/webhooks/stripe/route.ts
import { NextRequest, NextResponse } from "next/server";
import Stripe from "stripe";
import { prisma } from "@/lib/prisma";

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

export async function POST(req: NextRequest) {
  const body = await req.text();
  const signature = req.headers.get("stripe-signature")!;

  let event: Stripe.Event;

  try {
    event = stripe.webhooks.constructEvent(
      body,
      signature,
      process.env.STRIPE_WEBHOOK_SECRET!
    );
  } catch (err: any) {
    return new NextResponse(`Webhook Signature Error: ${err.message}`, { status: 400 });
  }

  // Handle Event Idempotently
  switch (event.type) {
    case "checkout.session.completed":
    case "invoice.payment_succeeded":
      await handleSubscriptionSync(event.data.object as Stripe.Subscription);
      break;
    case "customer.subscription.deleted":
      await handleSubscriptionCancellation(event.data.object as Stripe.Subscription);
      break;
  }

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

3. Idempotency Locks to Prevent Double-Billing

Stripe webhooks are delivered with at-least-once guarantees. If your server takes more than 2 seconds to respond, Stripe retries the webhook. Maintain a `stripe_processed_events` table in PostgreSQL to ensure an event ID is processed only once.

Key TakeawayAlways wrap subscription updates in a PostgreSQL database transaction to prevent race conditions during concurrent webhook deliveries.

4. Graceful Dunning & Failed Payment Recovery

When `invoice.payment_failed` fires, avoid immediately revoking customer access. Instead, set the subscription status to `past_due`, trigger an automated email with an update-payment link, and give customers a 3-day grace period.

Conclusion & Final Thoughts

A bulletproof billing architecture guarantees that your SaaS revenue flows smoothly, edge cases are handled automatically, and customer subscription management is 100% automated.

Did you enjoy this article?

Give love to support more technical masterclasses & writing!

Tags:#Stripe#SaaS Billing#Webhooks#PostgreSQL#Prisma#Next.js
Abu Nayem

Abu Nayem

Full-Stack & AI Specialist

Abu Nayem architects multi-tenant SaaS payment backends, recurring billing pipelines, and Stripe integrations.

Book Strategy Call
Enjoyed this engineering guide?