{
  "id": "add-stripe-checkout-to-nextjs",
  "type": "prompts",
  "category": "prompts",
  "locale": "zh",
  "url": "/zh/prompts/add-stripe-checkout-to-nextjs",
  "title": "在 Next.js 应用中添加 Stripe Checkout 的提示",
  "description": "AI 代理提示：为 Next.js App Router 项目添加 Stripe Checkout，包括 webhook 处理、客户门户和订阅状态。",
  "tools": [
    "Cursor",
    "Claude Code",
    "Codex",
    "Windsurf"
  ],
  "stack": [
    "Next.js",
    "PostgreSQL",
    "TypeScript"
  ],
  "tags": [
    "nextjs",
    "typescript",
    "postgres",
    "auth",
    "security"
  ],
  "difficulty": "hard",
  "updated": "2026-06-08",
  "markdown": "将此提示提供给您的代理，以实现完整的 Stripe 计费流程——包括结账会话创建、webhook 处理、客户门户和订阅状态控制——并确保正确的 webhook 签名验证，且不在客户端代码中包含密钥。\n\n## 主要提示\n\n```txt title=\"Main Prompt\"\nYou are working in a Next.js 15 App Router project with TypeScript and PostgreSQL.\nAuth is already set up with a `getSession()` helper. The pricing page already defines\n`PLANS` with Stripe Price IDs.\n\nTask: wire up Stripe Checkout for subscription billing.\n\nRequirements:\n- Install `stripe` (server-only) and `@stripe/stripe-js` (client). Do NOT import `stripe` in\n  Client Components or expose `STRIPE_SECRET_KEY` to the browser.\n- Create `src/lib/stripe.ts`: export a singleton Stripe client using `STRIPE_SECRET_KEY`.\n- Create a Server Action `src/lib/actions/create-checkout.ts`:\n  - Get the current user session; return an error if not authenticated.\n  - Create a Stripe Checkout Session in `subscription` mode.\n  - Set `success_url` to `/dashboard?session_id={CHECKOUT_SESSION_ID}`.\n  - Set `cancel_url` to `/pricing`.\n  - Store the Stripe `customerId` in the `users` table (`stripe_customer_id` column).\n  - Return the Checkout Session URL.\n- Create `src/app/api/stripe/webhook/route.ts`:\n  - Read the raw body using `request.text()`.\n  - Verify the signature using `stripe.webhooks.constructEvent(body, sig, STRIPE_WEBHOOK_SECRET)`.\n  - Handle events: `checkout.session.completed`, `customer.subscription.updated`,\n    `customer.subscription.deleted`.\n  - On each event, update the `users` table: set `subscription_status` and `subscription_tier`.\n  - Return `{ received: true }` with status 200.\n  - On signature failure, return 400.\n- Create `src/lib/actions/create-portal.ts`: create a Stripe Customer Portal session and return the URL.\n- Add a PostgreSQL migration `migrations/0011_add_stripe_columns.sql` adding\n  `stripe_customer_id TEXT`, `subscription_status TEXT`, `subscription_tier TEXT` to `users`.\n- Add all Stripe keys to `.env.example`: `STRIPE_SECRET_KEY`, `STRIPE_WEBHOOK_SECRET`,\n  `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY`.\n- Do NOT use the deprecated `stripe.charges` API. Use Payment Intents / Checkout Sessions only.\n\nStop and list all planned file changes before writing any code.\n```\n\n## 实现说明\n\n- Webhook 签名验证需要**原始**请求正文——如果先将其解析为 JSON，签名检查将失败。请使用 `request.text()` 而非 `request.json()`。\n- 必须通过路由配置将 webhook 处理程序排除在 Next.js 的请求体大小限制之外：`export const config = { api: { bodyParser: false } }`（Pages Router）——在 App Router 中，使用 `export const dynamic = 'force-dynamic'` 并直接读取流。\n- 使用 Stripe CLI 在本地测试 webhook：`stripe listen --forward-to localhost:3000/api/stripe/webhook`。\n- 在首次结账时存储 `stripe_customer_id`，以避免创建重复的 Stripe 客户。\n\n## 预期文件变更\n\n```txt\nsrc/lib/stripe.ts                           (new)\nsrc/lib/actions/create-checkout.ts          (new — Server Action)\nsrc/lib/actions/create-portal.ts            (new — Server Action)\nsrc/app/api/stripe/webhook/route.ts         (new — Route Handler)\nmigrations/0011_add_stripe_columns.sql      (new)\n.env.example                                (edited)\npackage.json                                (edited)\n```\n\n## 验收标准\n\n- 点击定价 CTA 可重定向到 Stripe Checkout 并选择正确的套餐。\n- 完成测试结账后，PostgreSQL 中的 `subscription_status` 会更新为 `'active'`。\n- Stripe 客户门户链接重定向到 Stripe 托管的门户。\n- 通过 Stripe CLI 发送测试 `customer.subscription.deleted` 事件可将 `subscription_status` 设置为 `'canceled'`。\n- 签名无效的 webhook 返回 HTTP 400。\n\n## 测试命令\n\n```bash\nbun add stripe @stripe/stripe-js\npsql \"$DATABASE_URL\" -f migrations/0011_add_stripe_columns.sql\nbun run typecheck\nbun run dev &\nstripe listen --forward-to localhost:3000/api/stripe/webhook\nstripe trigger checkout.session.completed\n# verify users table updated\npsql \"$DATABASE_URL\" -c \"SELECT stripe_customer_id, subscription_status FROM users LIMIT 5;\"\n```\n\n## 常见的 AI 错误\n\n- 在客户端组件中导入 `stripe`（服务器 SDK），从而暴露 `STRIPE_SECRET_KEY`。\n- 在签名验证之前将 webhook 正文解析为 JSON，导致所有 webhook 验证失败。\n- 每次结账时都创建新的 Stripe 客户，而不是重用 `stripe_customer_id`。\n- 使用已弃用的 `stripe.charges.create` 而非 `stripe.checkout.sessions.create`。\n\n## 修复提示\n\n```txt title=\"Fix Prompt\"\nWebhook signature verification fails with `No signatures found matching the expected signature`.\nFix in order:\n1. In the webhook route, replace `await request.json()` with `const body = await request.text()`.\n2. Ensure `stripe.webhooks.constructEvent(body, sig, process.env.STRIPE_WEBHOOK_SECRET!)` receives\n   the raw string body, not a parsed object.\n3. Add `export const dynamic = 'force-dynamic'` at the top of the route file.\nShow only the corrected route handler diff.\n```"
}