Skip to content

Stripe Payments

RocketFuel includes optional Stripe integration for payment processing. This guide covers setup, checkout flows, and webhook handling.

Prerequisites

Before starting:

  1. Create a Stripe account
  2. Get your API keys from the Stripe Dashboard
  3. Set up webhook endpoints

Environment Variables

Add these to your .env file:

Terminal window
STRIPE_SECRET_KEY="sk_test_..."
STRIPE_WEBHOOK_SECRET="whsec_..."
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY="pk_test_..."

Creating a Checkout Session

The generated code includes a checkout API route:

src/app/api/stripe/checkout/route.ts
import { stripe } from "@/lib/stripe";
import { NextResponse } from "next/server";
export async function POST(request: Request) {
const { priceId } = await request.json();
const session = await stripe.checkout.sessions.create({
payment_method_types: ["card"],
line_items: [
{
price: priceId,
quantity: 1,
},
],
mode: "subscription", // or "payment" for one-time
success_url: `${process.env.NEXT_PUBLIC_APP_URL}/success`,
cancel_url: `${process.env.NEXT_PUBLIC_APP_URL}/cancel`,
});
return NextResponse.json({ url: session.url });
}

Handling Webhooks

Webhooks notify your app of Stripe events:

src/app/api/stripe/webhooks/route.ts
import { stripe } from "@/lib/stripe";
import { headers } from "next/headers";
import { NextResponse } from "next/server";
export async function POST(request: Request) {
const body = await request.text();
const signature = headers().get("stripe-signature")!;
let event;
try {
event = stripe.webhooks.constructEvent(
body,
signature,
process.env.STRIPE_WEBHOOK_SECRET!
);
} catch (err) {
return NextResponse.json({ error: "Invalid signature" }, { status: 400 });
}
switch (event.type) {
case "checkout.session.completed":
// Handle successful checkout
break;
case "customer.subscription.updated":
// Handle subscription changes
break;
case "customer.subscription.deleted":
// Handle cancellation
break;
}
return NextResponse.json({ received: true });
}

Local Testing

  1. Install Stripe CLI

    Terminal window
    brew install stripe/stripe-cli/stripe
  2. Login to Stripe

    Terminal window
    stripe login
  3. Forward webhooks

    Terminal window
    stripe listen --forward-to localhost:3000/api/stripe/webhooks

    Copy the webhook signing secret and add it to .env.

  4. Trigger test events

    Terminal window
    stripe trigger checkout.session.completed

Further Reading