Assinaturas Stripe: checkout, portal e webhooks idempotentes com Drizzle
Código9 arquivosContexto~633 tokensMCP stripeanálise aprovada
Instalar
$
genpm add @core/billingO que você recebe
- Código em src/lib/billing/, 9 arquivos. (15,7 kB)
- Regras de IA em src/lib/billing/AGENTS.md, mais arquivos de regras da IDE.
- Variáveis de ambiente adicionadas ao .env.example: STRIPE_SECRET_KEY, STRIPE_WEBHOOK_SECRET.
- Resolve @core/auth, @core/db para você.
README
Este pacote não tem README.
~633 tokens→ src/lib/billing/AGENTS.md→ .cursor/rules/genpm-core-billing.mdc
Isto é exatamente o que sua IA lê quando trabalha em src/lib/billing. Nada mais é adicionado ao contexto dela.
@core/billing — rules for AI agents
Purpose
Stripe subscriptions: checkout, customer portal, an idempotent webhook handler that mirrors subscriptions into the
database, and hasEntitlement(user, feature) for gating. Stripe is the source of truth. No usage-based billing,
invoices UI or taxes logic (configure those in Stripe).
Map
index.ts— public API:createCheckoutSession,createPortalSession,handleStripeWebhook,hasEntitlement,activeSubscriptions.plans.ts— your config: Stripe price id → features. Edit this file.schema.ts—billing_customers,subscriptions,stripe_events. Depends on../authand../db.adapters/hono.ts,adapters/next.ts—POST /billing/checkout,/billing/portal,/billing/webhook.
Integration
- Env:
STRIPE_SECRET_KEY,STRIPE_WEBHOOK_SECRET. Use test-mode keys in development. - Use the Stripe MCP server (if the user enabled it) to list real products and prices; otherwise ask the user for price ids.
Put them in
plans.ts:FEATURES_BY_PRICE['price_123'] = ['pro']. - Generate and apply migrations (see
src/lib/db/AGENTS.md). - Mount routes after
@core/auth'ssessionMiddleware:- Hono:
app.route('/billing', billingRoutes())from./lib/billing/adapters/hono.js. - Next.js:
app/billing/{checkout,portal,webhook}/route.tsexportingcheckoutRoute/portalRoute/webhookRouteasPOST. Delete the adapter of the framework you don't use.
- Hono:
- Webhook endpoint in Stripe:
<origin>/billing/webhookwith eventscheckout.session.completedandcustomer.subscription.created|updated|deleted. Locally:stripe listen --forward-to localhost:3000/billing/webhook. - Gate features:
if (!(await hasEntitlement(user, 'pro'))) return c.json({ error: 'upgrade' }, 402). - Frontend:
POST /billing/checkout {priceId}returns{url}; redirect the browser there.
Conventions
- Read subscription state from the database (
hasEntitlement,activeSubscriptions), never from Stripe on each request. - All Stripe writes go through this module; keep amounts and prices in Stripe, not in code.
- The webhook must receive the raw body; do not put a JSON body parser in front of it.
Don't
- Don't skip webhook signature verification or process events outside
handleStripeWebhook. - Don't grant access from the checkout success page: wait for the webhook.
- Don't log card data, full webhook payloads or
STRIPE_SECRET_KEY. - Don't use live keys in tests or with the MCP server unless the user asks.
# @core/billing — rules for AI agents
## Purpose
Stripe subscriptions: checkout, customer portal, an idempotent webhook handler that mirrors subscriptions into the
database, and `hasEntitlement(user, feature)` for gating. Stripe is the source of truth. No usage-based billing,
invoices UI or taxes logic (configure those in Stripe).
## Map
- `index.ts` — public API: `createCheckoutSession`, `createPortalSession`, `handleStripeWebhook`, `hasEntitlement`, `activeSubscriptions`.
- `plans.ts` — **your config**: Stripe price id → features. Edit this file.
- `schema.ts` — `billing_customers`, `subscriptions`, `stripe_events`. Depends on `../auth` and `../db`.
- `adapters/hono.ts`, `adapters/next.ts` — `POST /billing/checkout`, `/billing/portal`, `/billing/webhook`.
## Integration
1. Env: `STRIPE_SECRET_KEY`, `STRIPE_WEBHOOK_SECRET`. Use test-mode keys in development.
2. Use the Stripe MCP server (if the user enabled it) to list real products and prices; otherwise ask the user for price ids.
Put them in `plans.ts`: `FEATURES_BY_PRICE['price_123'] = ['pro']`.
3. Generate and apply migrations (see `src/lib/db/AGENTS.md`).
4. Mount routes after `@core/auth`'s `sessionMiddleware`:
- Hono: `app.route('/billing', billingRoutes())` from `./lib/billing/adapters/hono.js`.
- Next.js: `app/billing/{checkout,portal,webhook}/route.ts` exporting `checkoutRoute`/`portalRoute`/`webhookRoute` as `POST`.
Delete the adapter of the framework you don't use.
5. Webhook endpoint in Stripe: `<origin>/billing/webhook` with events `checkout.session.completed` and
`customer.subscription.created|updated|deleted`. Locally: `stripe listen --forward-to localhost:3000/billing/webhook`.
6. Gate features: `if (!(await hasEntitlement(user, 'pro'))) return c.json({ error: 'upgrade' }, 402)`.
7. Frontend: `POST /billing/checkout {priceId}` returns `{url}`; redirect the browser there.
## Conventions
- Read subscription state from the database (`hasEntitlement`, `activeSubscriptions`), never from Stripe on each request.
- All Stripe writes go through this module; keep amounts and prices in Stripe, not in code.
- The webhook must receive the raw body; do not put a JSON body parser in front of it.
## Don't
- Don't skip webhook signature verification or process events outside `handleStripeWebhook`.
- Don't grant access from the checkout success page: wait for the webhook.
- Don't log card data, full webhook payloads or `STRIPE_SECRET_KEY`.
- Don't use live keys in tests or with the MCP server unless the user asks.
A árvore exata que será injetada, após o .genpmignore. Fixada em
MIT License
Copyright (c) 2026 GenPM
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
- servidor
- stripe
- comando
- npx -y @stripe/mcp
- env
- STRIPE_SECRET_KEY
| Versão | Commit | Publicado | Análise |
|---|---|---|---|
| 1.0.0 | a8a5ac1 | há 5 horas | ✔ análise aprovada |
- proposto
- O GenPM propõe o comando npm e só o executa se você disser sim.
- análise
- análise aprovada · 0 achados
- commit
- v1.0.0 → a8a5ac11d1027ce8ae3bad366f625d135bdf6246 · verificado após o download
- scripts
- Nenhum. O GenPM nunca executa código de pacotes.
- licença
- MIT
- denúncia
- Viu algo errado?