Abonnements Stripe : checkout, portail et webhooks idempotents avec Drizzle
Installer
genpm add @core/billingCe que vous obtenez
- Source dans src/lib/billing/, 9 fichiers. (14,9 ko)
- Règles IA dans src/lib/billing/AGENTS.md, plus les fichiers de règles de l’IDE.
- Variables d’environnement ajoutées à .env.example : STRIPE_SECRET_KEY, STRIPE_WEBHOOK_SECRET.
- Résout @core/auth, @core/db, @core/stripe pour vous.
README
@core/billing
Stripe subscriptions: checkout, portal and idempotent webhooks with Drizzle
A GenPM module: source code + AI rules + MCP config, injected into your project instead of hidden in node_modules. The code lands in src/lib/billing, pinned to a verified commit, and you own it.
Install
genpm add @core/billingNo genpm yet? curl -fsSL https://genpm.net/install.sh | sh (macOS/Linux), irm https://genpm.net/install.ps1 | iex (Windows), or one-off with npx @genpm-net/cli add @core/billing.
Or let your AI agent do it: run genpm mcp setup once, then ask "add @core/billing with genpm" in Claude Code, Cursor, VS Code, Windsurf, Codex or Gemini CLI. It shows you a dry-run plan before writing anything.
What it does
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).
Setup
After genpm add, follow these steps (your AI agent finds the same steps in src/lib/billing/AGENTS.md and can do them for you):
- 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.
Upgrading from 1.x
2.0 depends on @core/stripe, which now owns the Stripe client, the webhook verification and the stripe_events
table (same name and columns: no data migration). Install @core/stripe, keep your existing /billing/webhook route
(it delegates to @core/stripe) or point Stripe to /api/stripe/webhook; both process each event once. Other modules
(e.g. @core/checkout) receive their events through the same endpoint.
What's inside
Paths are relative to src/lib/billing.
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.
At a glance
- GenPM dependencies (installed with it): @core/db, @core/auth, @core/stripe
- npm dependencies (proposed, never installed without asking):
stripe - Environment variables (added to
.env.example):STRIPE_SECRET_KEY,STRIPE_WEBHOOK_SECRET - MCP servers (only added with your consent):
stripe - AI rules:
AGENTS.md, loaded by your agent only when it works insrc/lib/billing
Security
GenPM installs a 40-character commit SHA (never a branch), verifies an Ed25519-signed manifest, never runs install scripts and scans AI rules for prompt injection. Details: genpm.net/docs/security.
License
Voici exactement ce que lit votre IA quand elle travaille dans src/lib/billing. Rien d’autre n’est ajouté à son contexte.
@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.
Upgrading from 1.x
2.0 depends on @core/stripe, which now owns the Stripe client, the webhook verification and the stripe_events
table (same name and columns: no data migration). Install @core/stripe, keep your existing /billing/webhook route
(it delegates to @core/stripe) or point Stripe to /api/stripe/webhook; both process each event once. Other modules
(e.g. @core/checkout) receive their events through the same endpoint.
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.
### Upgrading from 1.x
2.0 depends on @core/stripe, which now owns the Stripe client, the webhook verification and the `stripe_events`
table (same name and columns: no data migration). Install @core/stripe, keep your existing `/billing/webhook` route
(it delegates to @core/stripe) or point Stripe to `/api/stripe/webhook`; both process each event once. Other modules
(e.g. @core/checkout) receive their events through the same endpoint.
## 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.
L’arborescence exacte qui sera injectée, après .genpmignore. Épinglée à
// Tablas de @core/billing. Stripe es la fuente de verdad; aquí hay una copia sincronizada por webhooks.
import { boolean, pgTable, text, timestamp } from 'drizzle-orm/pg-core';
import { users } from '../auth/schema.ts';
import { timestamps } from '../db/index.ts';
export const billingCustomers = pgTable('billing_customers', {
userId: text('user_id')
.primaryKey()
.references(() => users.id, { onDelete: 'cascade' }),
stripeCustomerId: text('stripe_customer_id').notNull().unique(),
...timestamps,
});
/** Una fila por suscripción de Stripe (`sub_…`), actualizada por los webhooks `customer.subscription.*`. */
export const subscriptions = pgTable('subscriptions', {
id: text('id').primaryKey(),
userId: text('user_id')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
status: text('status').notNull(),
priceId: text('price_id').notNull(),
currentPeriodEnd: timestamp('current_period_end', { withTimezone: true, mode: 'date' }),
cancelAtPeriodEnd: boolean('cancel_at_period_end').notNull().default(false),
...timestamps,
});
// `stripe_events` pasó a @core/stripe en la 2.0 (misma tabla y columnas: sin migración de datos).
export type Subscription = typeof subscriptions.$inferSelect;
- serveur
- stripe
- commande
- npx -y @stripe/mcp
- env
- STRIPE_SECRET_KEY
- proposé
- GenPM propose la commande npm et ne l’exécute que si vous acceptez.
- Utilisé par (0)
- Aucun paquet public n’en dépend pour l’instant.
- analyse
- analyse réussie · 0 problème
- commit
- v2.0.1 → c2aa5dae1a50a9d5816dde8dad6aedd6269984cd · vérifié après téléchargement
- scripts
- Aucun. GenPM n’exécute jamais le code des paquets.
- licence
- MIT
- Qualité
- 100/100
- Licence reconnuevalidé
- AGENTS.md explique son objectifvalidé
- AGENTS.md donne les étapes d’intégrationvalidé
- AGENTS.md liste conventions ou interditsvalidé
- Contient des testsvalidé
- Analyse de sécurité réussievalidé
- Publié au cours des 6 derniers moisvalidé
- Éditeur vérifiévalidé
- Résumé et mots-clésvalidé
- signalement
- Vous avez repéré un problème ?