Stripe-Abos: Checkout, Kundenportal und idempotente Webhooks mit Drizzle
Installieren
genpm add @core/billingWas du bekommst
- Quellcode in src/lib/billing/, 9 Dateien. (14,9 kB)
- KI-Regeln in src/lib/billing/AGENTS.md, dazu Regeldateien für die IDE.
- Umgebungsvariablen in .env.example ergänzt: STRIPE_SECRET_KEY, STRIPE_WEBHOOK_SECRET.
- Löst @core/auth, @core/db, @core/stripe für dich auf.
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
Genau das liest deine KI, wenn sie in src/lib/billing arbeitet. Sonst wird ihrem Kontext nichts hinzugefügt.
@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.
Der genaue Baum, der nach .genpmignore eingebunden wird. Gepinnt an
// Checkout, portal, webhooks idempotentes y entitlements. Sin framework: los adaptadores solo traducen HTTP.
import { and, eq, inArray } from 'drizzle-orm';
import type Stripe from 'stripe';
import type { User } from '../auth/index.ts';
import { type Executor, getDb } from '../db/index.ts';
import { onStripeEvent } from '../stripe/index.ts';
import { ACTIVE_STATUSES, FEATURES_BY_PRICE } from './plans.ts';
import { billingCustomers, type Subscription, subscriptions } from './schema.ts';
import { getStripe } from './stripe.ts';
/** Cliente de Stripe del usuario; lo crea la primera vez (con `metadata.userId` para poder volver al usuario). */
export async function ensureCustomer(user: Pick<User, 'id' | 'email' | 'name'>, db: Executor = getDb()): Promise<string> {
const [row] = await db.select().from(billingCustomers).where(eq(billingCustomers.userId, user.id));
if (row) return row.stripeCustomerId;
const customer = await getStripe().customers.create(
{ email: user.email ?? undefined, name: user.name ?? undefined, metadata: { userId: user.id } },
{ idempotencyKey: `customer-${user.id}` },
);
await db.insert(billingCustomers).values({ userId: user.id, stripeCustomerId: customer.id }).onConflictDoNothing();
const [saved] = await db.select().from(billingCustomers).where(eq(billingCustomers.userId, user.id));
return saved!.stripeCustomerId;
}
export async function createCheckoutSession(opts: {
user: Pick<User, 'id' | 'email' | 'name'>;
priceId: string;
successUrl: string;
cancelUrl: string;
}): Promise<{ url: string }> {
if (!(opts.priceId in FEATURES_BY_PRICE)) throw new Error(`Unknown price ${opts.priceId}: add it to plans.ts`);
const customer = await ensureCustomer(opts.user);
const session = await getStripe().checkout.sessions.create({
mode: 'subscription',
customer,
client_reference_id: opts.user.id,
line_items: [{ price: opts.priceId, quantity: 1 }],
success_url: opts.successUrl,
cancel_url: opts.cancelUrl,
subscription_data: { metadata: { userId: opts.user.id } },
allow_promotion_codes: true,
});
if (!session.url) throw new Error('Stripe did not return a checkout URL');
return { url: session.url };
}
export async function createPortalSession(user: Pick<User, 'id' | 'email' | 'name'>, returnUrl: string): Promise<{ url: string }> {
const customer = await ensureCustomer(user);
const s = await getStripe().billingPortal.sessions.create({ customer, return_url: returnUrl });
return { url: s.url };
}
async function userIdFor(sub: Stripe.Subscription, db: Executor): Promise<string | null> {
if (sub.metadata?.userId) return sub.metadata.userId;
const customer = typeof sub.customer === 'string' ? sub.customer : sub.customer.id;
const [row] = await db.select().from(billingCustomers).where(eq(billingCustomers.stripeCustomerId, customer));
return row?.userId ?? null;
}
/** Copia el estado de una suscripción de Stripe a la tabla `subscriptions`. */
export async function syncSubscription(sub: Stripe.Subscription, db: Executor = getDb()): Promise<void> {
const userId = await userIdFor(sub, db);
if (!userId) return;
const item = sub.items.data[0];
const values = {
userId,
status: sub.status,
priceId: item?.price.id ?? '',
currentPeriodEnd: item?.current_period_end ? new Date(item.current_period_end * 1000) : null,
cancelAtPeriodEnd: sub.cancel_at_period_end,
};
await db
.insert(subscriptions)
.values({ id: sub.id, ...values })
.onConflictDoUpdate({ target: subscriptions.id, set: values });
}
// Webhooks: el endpoint, la firma y la idempotencia son de @core/stripe; billing solo registra sus manejadores.
// Stripe no garantiza el orden de entrega: se guarda el estado actual, no la instantánea del evento, para que un
// evento viejo que llegue tarde no pise uno más nuevo.
onStripeEvent(['customer.subscription.created', 'customer.subscription.updated', 'customer.subscription.deleted'], async (event, tx) => {
const sub = event.data.object as Stripe.Subscription;
await syncSubscription(await getStripe().subscriptions.retrieve(sub.id), tx);
});
onStripeEvent('checkout.session.completed', async (event, tx) => {
const s = event.data.object as Stripe.Checkout.Session;
if (s.mode === 'subscription' && s.subscription) {
const id = typeof s.subscription === 'string' ? s.subscription : s.subscription.id;
await syncSubscription(await getStripe().subscriptions.retrieve(id), tx);
}
});
export async function activeSubscriptions(userId: string, db: Executor = getDb()): Promise<Subscription[]> {
return db
.select()
.from(subscriptions)
.where(and(eq(subscriptions.userId, userId), inArray(subscriptions.status, [...ACTIVE_STATUSES])));
}
/** ¿Tiene el usuario una suscripción activa cuyo precio desbloquea `feature` (según plans.ts)? */
export async function hasEntitlement(user: Pick<User, 'id'>, feature: string, db: Executor = getDb()): Promise<boolean> {
const subs = await activeSubscriptions(user.id, db);
return subs.some((s) => FEATURES_BY_PRICE[s.priceId]?.includes(feature));
}
- Server
- stripe
- Befehl
- npx -y @stripe/mcp
- env
- STRIPE_SECRET_KEY
- vorgeschlagen
- GenPM schlägt den npm-Befehl vor und führt ihn nur aus, wenn du zustimmst.
- Verwendet von (0)
- Noch hängt kein öffentliches Paket davon ab.
- Prüfung
- Prüfung bestanden · 0 Befunde
- Commit
- v2.0.1 → c2aa5dae1a50a9d5816dde8dad6aedd6269984cd · nach dem Abruf verifiziert
- Skripte
- Keine. GenPM führt niemals Paketcode aus.
- Lizenz
- MIT
- Qualität
- 100/100
- Anerkannte Lizenzerfüllt
- AGENTS.md erklärt den Zweckerfüllt
- AGENTS.md enthält Integrationsschritteerfüllt
- AGENTS.md nennt Konventionen oder Verboteerfüllt
- Enthält Testserfüllt
- Sicherheitsscan bestandenerfüllt
- In den letzten 6 Monaten veröffentlichterfüllt
- Verifizierter Herausgebererfüllt
- Zusammenfassung und Schlagwörtererfüllt
- Meldung
- Stimmt etwas nicht?