Stripe-Abos: Checkout, Kundenportal und idempotente Webhooks mit Drizzle
Code9 DateienKontext~633 TokensMCP stripePrüfung bestanden
Installieren
$
genpm add @core/billingWas du bekommst
- Quellcode in src/lib/billing/, 9 Dateien. (15,7 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 für dich auf.
README
Dieses Paket hat keine README.
~633 Tokens→ src/lib/billing/AGENTS.md→ .cursor/rules/genpm-core-billing.mdc
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.
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.
Der genaue Baum, der nach .genpmignore eingebunden wird. Gepinnt an
// Adaptador Next.js (App Router), Request/Response estándar:
// app/billing/checkout/route.ts → export const POST = checkoutRoute;
// app/billing/portal/route.ts → export const POST = portalRoute;
// app/billing/webhook/route.ts → export const POST = webhookRoute;
import { getUserFromCookieHeader } from '../../auth/index.js';
import { createCheckoutSession, createPortalSession, handleStripeWebhook, WebhookSignatureError } from '../index.js';
const json = (body: unknown, status = 200) => Response.json(body, { status });
export async function checkoutRoute(req: Request): Promise<Response> {
const user = await getUserFromCookieHeader(req.headers.get('cookie'));
if (!user) return json({ error: 'unauthorized' }, 401);
const { priceId } = (await req.json().catch(() => ({}))) as { priceId?: string };
if (!priceId) return json({ error: 'priceId required' }, 400);
const { origin } = new URL(req.url);
return json(await createCheckoutSession({ user, priceId, successUrl: `${origin}/billing/success`, cancelUrl: `${origin}/pricing` }));
}
export async function portalRoute(req: Request): Promise<Response> {
const user = await getUserFromCookieHeader(req.headers.get('cookie'));
if (!user) return json({ error: 'unauthorized' }, 401);
return json(await createPortalSession(user, `${new URL(req.url).origin}/account`));
}
export async function webhookRoute(req: Request): Promise<Response> {
try {
return json(await handleStripeWebhook(await req.text(), req.headers.get('stripe-signature')));
} catch (e) {
if (e instanceof WebhookSignatureError) return json({ error: e.message }, 400);
throw e;
}
}
- Server
- stripe
- Befehl
- npx -y @stripe/mcp
- env
- STRIPE_SECRET_KEY
| Version | Commit | Veröffentlicht | Prüfung |
|---|---|---|---|
| 1.0.0 | a8a5ac1 | vor 5 Stunden | ✔ Prüfung bestanden |
- vorgeschlagen
- GenPM schlägt den npm-Befehl vor und führt ihn nur aus, wenn du zustimmst.
- Prüfung
- Prüfung bestanden · 0 Befunde
- Commit
- v1.0.0 → a8a5ac11d1027ce8ae3bad366f625d135bdf6246 · nach dem Abruf verifiziert
- Skripte
- Keine. GenPM führt niemals Paketcode aus.
- Lizenz
- MIT
- Meldung
- Stimmt etwas nicht?