January 10, 20251 min read
Building a SaaS with Stripe Payments
A complete guide to integrating Stripe payments into your SaaS application for subscriptions and one-time payments.
A complete guide to integrating Stripe payments into your SaaS application for subscriptions and one-time payments.
Building a successful SaaS requires a robust payment system. Stripe makes it easy to accept payments, manage subscriptions, and handle billing.
First, install the Stripe SDK:
npm install stripe @stripe/stripe-js
Create a Stripe instance on the server:
import Stripe from "stripe";
export const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
apiVersion: "2024-12-18.acacia",
});
To create a subscription, you need to:
const subscription = await stripe.subscriptions.create({
customer: customerId,
items: [{ price: priceId }],
payment_behavior: "default_incomplete",
expand: ["latest_invoice.payment_intent"],
});
Webhooks are essential for keeping your database in sync:
export async function POST(req: Request) {
const body = await req.text();
const sig = req.headers.get("stripe-signature")!;
const event = stripe.webhooks.constructEvent(body, sig, webhookSecret);
switch (event.type) {
case "customer.subscription.created":
// Handle new subscription
break;
case "invoice.paid":
// Handle successful payment