如何在 Next.js 16 中设置 Stripe 订阅(完整指南)

发布: (2026年3月24日 GMT+8 09:44)
4 分钟阅读
原文: Dev.to

Source: Dev.to

huangyongshan46‑a11y

我们正在构建的内容

  • 用于新订阅的 Stripe Checkout
  • 支付事件的 Webhook 处理
  • 包含免费 / 专业 / 企业层级的计划管理
  • 用于自助计费的客户门户

1️⃣ 安装依赖

npm install stripe @stripe/stripe-js

2️⃣ 定义你的计划

为你的计划创建一个中心配置。这是功能和限制的唯一可信来源。

// src/lib/stripe.ts
import Stripe from "stripe";

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

export const PLANS = {
  free: {
    name: "Free",
    price: { monthly: 0 },
    features: ["Up to 3 projects", "Basic analytics", "Community support"],
    limits: { projects: 3, aiMessages: 50 },
  },
  pro: {
    name: "Pro",
    price: { monthly: 29 },
    stripePriceId: process.env.STRIPE_PRO_PRICE_ID,
    features: [
      "Unlimited projects",
      "Advanced analytics",
      "Priority support",
      "AI assistant",
    ],
    limits: { projects: -1, aiMessages: 1000 },
  },
  enterprise: {
    name: "Enterprise",
    price: { monthly: 99 },
    stripePriceId: process.env.STRIPE_ENTERPRISE_PRICE_ID,
    features: [
      "Everything in Pro",
      "SSO/SAML",
      "Unlimited AI",
      "SLA guarantee",
    ],
    limits: { projects: -1, aiMessages: -1 },
  },
};

3️⃣ 创建 Checkout API 路由

这将创建一个 Stripe Checkout 会话并返回重定向 URL。

// src/app/api/stripe/checkout/route.ts
import { NextRequest, NextResponse } from "next/server";
import { stripe } from "@/lib/stripe";
import { auth } from "@/lib/auth";

export async function POST(req: NextRequest) {
  const session = await auth();
  if (!session?.user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const { priceId } = await req.json();

  const checkoutSession = await stripe.checkout.sessions.create({
    mode: "subscription",
    payment_method_types: ["card"],
    line_items: [{ price: priceId, quantity: 1 }],
    success_url: `${process.env.NEXT_PUBLIC_APP_URL}/billing?success=true`,
    cancel_url: `${process.env.NEXT_PUBLIC_APP_URL}/billing?canceled=true`,
    metadata: { userId: session.user.id },
  });

  return NextResponse.json({ url: checkoutSession.url });
}

4️⃣ 处理 Webhook(关键部分)

Webhook 可让你的数据库与 Stripe 保持同步。

// src/app/api/stripe/webhook/route.ts
import { NextRequest, NextResponse } from "next/server";
import { stripe } from "@/lib/stripe";
import { db } from "@/lib/db";

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

  let event;
  try {
    event = stripe.webhooks.constructEvent(
      body,
      signature,
      process.env.STRIPE_WEBHOOK_SECRET!
    );
  } catch {
    return NextResponse.json({ error: "Invalid signature" }, { status: 400 });
  }

  switch (event.type) {
    case "checkout.session.completed": {
      const session = event.data.object as any;
      const subscription = await stripe.subscriptions.retrieve(
        session.subscription as string
      );

      await db.subscription.upsert({
        where: { userId: session.metadata.userId },
        create: {
          userId: session.metadata.userId,
          stripeCustomerId: session.customer as string,
          stripeSubscriptionId: subscription.id,
          stripePriceId: subscription.items.data[0].price.id,
          status: "ACTIVE",
          plan: "PRO",
        },
        update: {
          stripeSubscriptionId: subscription.id,
          status: "ACTIVE",
          plan: "PRO",
        },
      });
      break;
    }

    case "customer.subscription.deleted": {
      const subscription = event.data.object as any;
      await db.subscription.update({
        where: { stripeSubscriptionId: subscription.id },
        data: { status: "CANCELED", plan: "FREE" },
      });
      break;
    }
  }

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

5️⃣ 计费页面

向用户展示他们当前的套餐并允许他们升级。

// Client‑side upgrade button
async function handleUpgrade(priceId: string) {
  const res = await fetch("/api/stripe/checkout", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ priceId }),
  });
  const { url } = await res.json();
  window.location.href = url;
}

6️⃣ 根据计划保护功能

// Middleware or server component
const subscription = await db.subscription.findUnique({
  where: { userId: session.user.id },
});

if (
  subscription?.plan !== "PRO" &&
  subscription?.plan !== "ENTERPRISE"
) {
  redirect("/billing");
}

常见陷阱

  • Webhook签名验证在本地失败 – 开发时使用 stripe listen --forward-to localhost:3000/api/stripe/webhook
  • 订阅状态不同步 – 始终信任 webhook 而不是客户端状态。
  • 缺少元数据 – 始终在结账会话的 metadata 中传递 userId
  • 未处理取消 – 确保处理 customer.subscription.deleted 事件。

取消。处理 customer.subscription.deleted

想要完整的实现吗?

如果你想要所有这些预先集成了 Auth.js v5、Prisma、AI 聊天、邮件和精美 UI 的完整实现,请查看 LaunchKit ——它是一个生产就绪的 SaaS 入门套件,所有功能已连接。

GitHub | 获取 LaunchKit($49)

0 浏览
Back to Blog

相关文章

阅读更多 »