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