用途
convex-billing 用于为 Convex 应用添加 Stripe 计费与支付能力。它基于 @convex-dev/stripe 组件,将结账流程、Webhook 处理、订阅状态存储与服务端访问控制接入 Convex,避免手动编写 Webhook 签名校验逻辑。
主要能力
- 提供结账 action:创建 Stripe Checkout Session,支持订阅模式(mode: 'subscription'),并传入 successUrl、cancelUrl 与 subscriptionMetadata。
- 自动注册 Webhook:由组件通过 registerRoutes 注册 httpAction 路由,签名验证由组件内部自动完成。
- 订阅状态存储:订阅状态保存在组件自身的表中,可通过组件查询读取。
- 服务端访问控制:通过 isSubscribed 查询读取组件表,判断当前用户是否存在 active 或 trialing 的订阅。
使用方式
- 安装组件:npm install @convex-dev/stripe(资料中给出的版本范围为 @convex-dev/stripe@^0.1.4)。
- 创建 convex/convex.config.ts,使用 defineApp 并通过 app.use(stripe) 注册组件;注意必须从 '@convex-dev/stripe/convex.config.js' 导入(.js 扩展名是 Convex 打包器要求,不能用 .ts)。
- 在 Convex 环境中配置 STRIPE_SECRET_KEY(sk_test_… / sk_live_…)与 STRIPE_WEBHOOK_SECRET(whsec_…)。
- 创建 convex/http.ts,通过 httpRouter 与 registerRoutes(http, components.stripe, { webhookPath: '/stripe/webhook' }) 注册 Webhook 路由。
- 创建 convex/billing.ts,实例化 StripeSubscriptions(components.stripe, {}),并实现 createSubscriptionCheckout action 与 isSubscribed query。action 中先获取用户身份,再通过 getOrCreateCustomer 获取或创建客户,然后调用 createCheckoutSession。isSubscribed 查询通过 ctx.runQuery(components.stripe.public.listSubscriptionsByUserId, { userId: identity.subject }) 读取订阅并判断状态。
- 运行 npx convex dev --once,安装组件并推送函数,确认输出显示 ✔ Installed component stripe。
- 在 Stripe Dashboard → Webhooks 添加端点 https://<deployment>.convex.site/stripe/webhook,订阅 checkout.session.completed、customer.subscription.、invoice.、payment_intent.* 事件,并将签名密钥复制为 STRIPE_WEBHOOK_SECRET。
适用场景
适用于需要在 Convex 应用中实现订阅计费、结账、支付状态同步与服务端功能门控的场景,例如按订阅状态限制功能访问。
限制与规则
- 必须使用 @convex-dev/stripe 组件,签名验证由 registerRoutes 内部处理,不要手写 constructEvent Webhook。
- Stripe 密钥存放在 Convex 环境变量中。
- 功能门控应基于服务端存储的订阅状态(isSubscribed 查询读取组件表),而非客户端声明。
- convex.config.ts 的导入必须使用 .js 扩展名。
- 资料未提供价格、收费模式、平台支持范围、性能指标或除上述流程外的其他功能说明。