Prompt para Adicionar Stripe Checkout a um App Next.js
Prompt para agente de IA adicionar Stripe Checkout com tratamento de webhook, portal do cliente e status de assinatura a um projeto Next.js App Router.
CursorClaude CodeCodexWindsurf Next.jsPostgreSQLTypeScript
Dê este prompt ao seu agente para implementar o fluxo completo de faturamento do Stripe — criação de sessão de checkout, processamento de webhook, portal do cliente e controle de status de assinatura — com verificação adequada de assinatura do webhook e sem segredos no código do cliente.
Prompt Principal
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.Notas de Implementação
- A verificação de assinatura do webhook requer o corpo da requisição bruto — se você o interpretar como JSON primeiro, a verificação da assinatura falhará. Use
request.text()em vez derequest.json(). - O manipulador de webhook deve ser excluído dos limites de tamanho do corpo do Next.js através de uma configuração de rota:
export const config = { api: { bodyParser: false } }(Pages Router) — no App Router, useexport const dynamic = 'force-dynamic'e leia o stream diretamente. - Teste webhooks localmente com a CLI do Stripe:
stripe listen --forward-to localhost:3000/api/stripe/webhook. - Armazene
stripe_customer_idno primeiro checkout para evitar criar clientes Stripe duplicados.
Mudanças Esperadas nos Arquivos
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)Critérios de Aceitação
- Clicar em um CTA de preços redireciona para o Stripe Checkout do plano correto.
- Completar um checkout de teste atualiza
subscription_status = 'active'no PostgreSQL. - O link do Portal do Cliente Stripe redireciona para o portal hospedado pelo Stripe.
- Enviar um evento de teste
customer.subscription.deletedvia CLI do Stripe definesubscription_status = 'canceled'. - Um webhook com assinatura inválida retorna HTTP 400.
Comandos de Teste
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;"Erros Comuns de IA
- Importar
stripe(SDK do servidor) em um Componente Cliente, expondoSTRIPE_SECRET_KEY. - Interpretar o corpo do webhook como JSON antes da verificação da assinatura, fazendo com que todas as validações do webhook falhem.
- Criar um novo cliente Stripe em cada checkout em vez de reutilizar
stripe_customer_id. - Usar
stripe.charges.create(obsoleto) em vez destripe.checkout.sessions.create.
Prompt de Correção
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.