stripe-billing
БесплатноБез исполняемых скриптовНе проверенStripe Billing is Stripe's subscription and invoicing product for SaaS: recurring plans, free trials, usage-based pricing with billing meters, proration, the…
от TerminalSkills★ 221 звезда на GitHubОб этом скилле
Stripe Billing — SaaS Subscription & Usage-Based Billing
Overview
Stripe Billing turns products and prices into subscriptions that renew, prorate, invoice and retry failed payments. This skill covers the server-side flow with the Node SDK: Checkout for sign-up, Billing Meters for usage, webhooks as the source of truth, and the customer portal for self-service.
Important change: the legacy usage-record API (subscriptionItems.createUsageRecord, prices with usage_type: "metered" and no meter, aggregate_usage, billing_thresholds) was removed in API version 2025-03-31.basil. Usage is now reported as meter events against a meter that the price references. Code written for createUsageRecord fails on current API versions.
Instructions
npm install stripe
Keep the key in the environment (STRIPE_SECRET_KEY, sk_test_... while developing; restricted keys in production).
Subscription Setup (flat price + metered price)
import Stripe from "stripe";
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
// Create product + price
const product = await stripe.products.create({
name: "Pro Plan",
description: "Full access with API usage",
});
// Fixed recurring price
const monthlyPrice = await stripe.prices.create({
product: product.id,
unit_amount: 2900, // $29.00
currency: "usd",
recurring: { interval: "month" },
});
// Meter: what to count and how to aggregate it per billing period
const meter = await stripe.billing.meters.create({
display_name: "API calls",
event_name: "api_call",
default_aggregation: { formula: "sum" },
customer_mapping: { event_payload_key: "stripe_customer_id", type: "by_id" },
value_settings: { event_payload_key: "value" },
});
// Usage-based price that references the meter
const apiPrice = await stripe.prices.create({
product: product.id,
currency: "usd",
recurring: { interval: "month", usage_type: "metered", meter: meter.id },
billing_scheme: "tiered",
tiers_mode: "graduated",
tiers: [
{ up_to: 1000, unit_amount: 0 }, // First 1000 free
{ up_to: 10000, unit_amount_decimal: Stripe.Decimal.from("1") }, // 1 cent per call
{ up_to: "inf", unit_amount_decimal: Stripe.Decimal.from("0.5") }, // 0.5 cent per call
],
});
// Create checkout session
const session = await stripe.checkout.sessions.create({
mode: "subscription",
customer_email: user.email,
metadata: { userId: user.id }, // session-level: the checkout.session.completed handler reads session.metadata
line_items: [
{ price: monthlyPrice.id, quantity: 1 },
{ price: apiPrice.id }, // Metered — no quantity
],
subscription_data: {
trial_period_days: 14, // add payment_method_collection: "if_required" on the session to skip the card
metadata: { userId: user.id }, // copied to the Subscription object
},
success_url: "https://app.northwind.dev/billing/success?session_id={CHECKOUT_SESSION_ID}",
cancel_url: "https://app.northwind.dev/billing/cancel",
});
// Redirect to session.url
Usage Reporting
// Report one unit of usage as a meter event (replaces createUsageRecord)
async function reportUsage(stripeCustomerId: string, value: number, requestId: string) {
await stripe.billing.meterEvents.create({
event_name: "api_call", // must match the meter's event_name
payload: { stripe_customer_id: stripeCustomerId, value: String(value) },
identifier: requestId, // dedupes retries of the same event
});
}
// In your API middleware
app.use((req, res, next) => {
res.on("finish", () => {
if (req.user?.stripeCustomerId) {
reportUsage(req.user.stripeCustomerId, 1, req.id).catch(console.error);
}
});
next();
});
Webhook Handler
// Express: this route needs the RAW body (express.raw({ type: "application/json" })),
// not express.json(), or signature verification fails.
app.post("/api/webhooks/stripe", express.raw({ type: "application/json" }), async (req, res) => {
const event = stripe.webhooks.constructEvent(
req.body, req.headers["stripe-signature"]!, process.env.STRIPE_WEBHOOK_SECRET!,
);
switch (event.type) {
case "checkout.session.completed": {
const session = event.data.object as Stripe.Checkout.Session;
await db.users.update(session.metadata!.userId, {
plan: "pro",
stripeCustomerId: session.customer as string,
stripeSubscriptionId: session.subscription as string,
});
break;
}
case "invoice.paid": {
const invoice = event.data.object as Stripe.Invoice;
await db.invoices.create({
userId: await getUserByStripeCustomer(invoice.customer as string),
amount: invoice.amount_paid,
pdfUrl: invoice.invoice_pdf,
});
break;
}
case "customer.subscription.deleted": {
const sub = event.data.obj
Установить stripe-billing в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл stripe-billing?
Stripe Billing is Stripe's subscription and invoicing product for SaaS: recurring plans, free trials, usage-based pricing with billing meters, proration, the hosted customer portal and webhook-driven lifecycle handling. Use when someone asks to "add subscriptions with Stripe", "bill per API call", "set up metered or usage-based billing", "add a free trial", "let customers manage their plan", or "fix createUsageRecord no longer working".
Как установить скилл stripe-billing?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл stripe-billing запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic