@convex-dev/stripe

中文文档
0.1.7发布于 2026/10/10Apache-2.0TypeScriptES Module近 30 天下载 50.3万

A stripe component for Convex.

原始使用文档
文档目录28 节
  1. Features
  2. Quick Start
  3. 1. Install the Component
  4. 2. Add to Your Convex App
  5. 3. Set Up Environment Variables
  6. 4. Configure Stripe Webhooks
  7. 5. Register Webhook Routes
  8. 6. Use the Component
  9. API Reference
  10. StripeSubscriptions Client
  11. createCheckoutSession
  12. Component Queries
  13. Available Public Queries
  14. Webhook Events
  15. Custom Webhook Handlers
  16. Database Schema
  17. customers
  18. subscriptions
  19. checkout_sessions
  20. payments
  21. invoices
  22. Example App
  23. Authentication
  24. Troubleshooting
  25. Tables are empty after checkout
  26. "Not authenticated" errors
  27. Webhooks returning 400/500
  28. License

@convex-dev/stripe

Integrate Stripe with Convex in 10 mins (Stripe Component)

A Convex component for integrating Stripe payments, subscriptions, and billing into your Convex application.

npm version

Requires Node.js 18 or later, matching the Stripe Node SDK v22 runtime requirement.

Features

  • 🛒 Checkout Sessions - Create one-time payment and subscription checkouts
  • 📦 Subscription Management - Create, update, cancel subscriptions
  • 👥 Customer Management - Automatic customer creation and linking
  • 💳 Customer Portal - Let users manage their billing
  • 🪑 Seat-Based Pricing - Update subscription quantities for team billing
  • 🔗 User/Org Linking - Link payments and subscriptions to users or organizations
  • 🔔 Webhook Handling - Automatic sync of Stripe data to your Convex database
  • 📊 Real-time Data - Query payments, subscriptions, invoices in real-time

Quick Start

1. Install the Component

npm install @convex-dev/stripe

2. Add to Your Convex App

Create or update convex/convex.config.ts:

import { defineApp } from "convex/server";
import stripe from "@convex-dev/stripe/convex.config.js";

const app = defineApp();
app.use(stripe);

export default app;

3. Set Up Environment Variables

Add these to your Convex Dashboard → Settings → Environment Variables:

VariableDescription
STRIPE_SECRET_KEYYour Stripe secret key (sk_test_... or sk_live_...)
STRIPE_WEBHOOK_SECRETWebhook signing secret (whsec_...) - see Step 4

4. Configure Stripe Webhooks

  1. Go to Stripe Dashboard → Developers → Webhooks
  2. Click "Add endpoint"
  3. Enter your webhook URL:
    https://<your-convex-deployment>.convex.site/stripe/webhook
    
    (Find your deployment name in the Convex dashboard - it's the part before .convex.cloud in your URL)
  4. Select these events:
    • checkout.session.completed
    • customer.created
    • customer.updated
    • customer.deleted
    • customer.subscription.created
    • customer.subscription.updated
    • customer.subscription.deleted
    • invoice.created
    • invoice.finalized
    • invoice.updated
    • invoice.paid
    • invoice.payment_failed
    • payment_intent.succeeded
    • payment_intent.payment_failed
  5. Click "Add endpoint"
  6. Copy the Signing secret and add it as STRIPE_WEBHOOK_SECRET in Convex

5. Register Webhook Routes

Create convex/http.ts:

import { httpRouter } from "convex/server";
import { components } from "./_generated/api";
import { registerRoutes } from "@convex-dev/stripe";

const http = httpRouter();

// Register Stripe webhook handler at /stripe/webhook
registerRoutes(http, components.stripe, {
  webhookPath: "/stripe/webhook",
  apiVersion: "2026-04-22.dahlia", // Optional
});

export default http;

6. Use the Component

Create convex/stripe.ts:

import { action } from "./_generated/server";
import { components } from "./_generated/api";
import { StripeSubscriptions } from "@convex-dev/stripe";
import { v } from "convex/values";

const stripeClient = new StripeSubscriptions(components.stripe, {});

// Create a checkout session for a subscription
export const createSubscriptionCheckout = action({
  args: { priceId: v.string() },
  returns: v.object({
    sessionId: v.string(),
    url: v.union(v.string(), v.null()),
  }),
  handler: async (ctx, args) => {
    const identity = await ctx.auth.getUserIdentity();
    if (!identity) throw new Error("Not authenticated");

    // Get or create a Stripe customer
    const customer = await stripeClient.getOrCreateCustomer(ctx, {
      userId: identity.subject,
      email: identity.email,
      name: identity.name,
    });

    // Create checkout session
    return await stripeClient.createCheckoutSession(ctx, {
      priceId: args.priceId,
      customerId: customer.customerId,
      mode: "subscription",
      successUrl: "http://localhost:5173/?success=true",
      cancelUrl: "http://localhost:5173/?canceled=true",
      subscriptionMetadata: { userId: identity.subject },
    });
  },
});

// Create a checkout session for a one-time payment
export const createPaymentCheckout = action({
  args: { priceId: v.string() },
  returns: v.object({
    sessionId: v.string(),
    url: v.union(v.string(), v.null()),
  }),
  handler: async (ctx, args) => {
    const identity = await ctx.auth.getUserIdentity();
    if (!identity) throw new Error("Not authenticated");

    const customer = await stripeClient.getOrCreateCustomer(ctx, {
      userId: identity.subject,
      email: identity.email,
      name: identity.name,
    });

    return await stripeClient.createCheckoutSession(ctx, {
      priceId: args.priceId,
      customerId: customer.customerId,
      mode: "payment",
      successUrl: "http://localhost:5173/?success=true",
      cancelUrl: "http://localhost:5173/?canceled=true",
      paymentIntentMetadata: { userId: identity.subject },
    });
  },
});

API Reference

StripeSubscriptions Client

import { StripeSubscriptions } from "@convex-dev/stripe";

const stripeClient = new StripeSubscriptions(components.stripe, {
  STRIPE_SECRET_KEY: "sk_...", // Optional, defaults to process.env.STRIPE_SECRET_KEY
  apiVersion: "2026-04-22.dahlia", // Optional Stripe API version
});

Methods

MethodDescription
createCheckoutSession()Create a Stripe Checkout session
createCustomerPortalSession()Generate a Customer Portal URL
createCustomer()Create a new Stripe customer
getOrCreateCustomer()Get existing or create new customer
cancelSubscription()Cancel a subscription
reactivateSubscription()Reactivate a subscription set to cancel
updateSubscriptionQuantity()Update seat count

createCheckoutSession

await stripeClient.createCheckoutSession(ctx, {
  priceId: "price_...",
  customerId: "cus_...",           // Optional
  mode: "subscription",             // "subscription" | "payment" | "setup"
  successUrl: "https://...",
  cancelUrl: "https://...",
  quantity: 1,                      // Optional, default 1
  metadata: {},                     // Optional, session metadata
  subscriptionMetadata: {},         // Optional, attached to subscription
  paymentIntentMetadata: {},        // Optional, attached to payment intent
  params: {
    allow_promotion_codes: true,
    ui_mode: "embedded_page",
    return_url: "https://...",
  },                                // Optional Stripe Checkout Session params
});

params is a typed passthrough for Stripe Checkout Session fields that the component does not model directly. Fields in params override constructed defaults, except mode, which remains controlled by the top-level mode argument. For non-hosted Checkout UI modes, the component omits successUrl and cancelUrl from the Stripe request and expects redirect behavior to be supplied through Stripe-supported params such as return_url.

Component Queries

Access data directly via the component's public queries:

import { query } from "./_generated/server";
import { components } from "./_generated/api";

// List subscriptions for a user
export const getUserSubscriptions = query({
  args: {},
  handler: async (ctx) => {
    const identity = await ctx.auth.getUserIdentity();
    if (!identity) return [];

    return await ctx.runQuery(
      components.stripe.public.listSubscriptionsByUserId,
      { userId: identity.subject },
    );
  },
});

// List payments for a user
export const getUserPayments = query({
  args: {},
  handler: async (ctx) => {
    const identity = await ctx.auth.getUserIdentity();
    if (!identity) return [];

    return await ctx.runQuery(components.stripe.public.listPaymentsByUserId, {
      userId: identity.subject,
    });
  },
});

Available Public Queries

QueryArgumentsDescription
getCustomerstripeCustomerIdGet a customer by Stripe ID
listSubscriptionsstripeCustomerIdList subscriptions for a customer
listSubscriptionsByUserIduserIdList subscriptions for a user
getSubscriptionstripeSubscriptionIdGet a subscription by ID
getSubscriptionByOrgIdorgIdGet subscription for an org
getPaymentstripePaymentIntentIdGet a payment by ID
listPaymentsstripeCustomerIdList payments for a customer
listPaymentsByUserIduserIdList payments for a user
listPaymentsByOrgIdorgIdList payments for an org
listInvoicesstripeCustomerIdList invoices for a customer
listInvoicesByUserIduserIdList invoices for a user
listInvoicesByOrgIdorgIdList invoices for an org

Webhook Events

The component automatically handles these Stripe webhook events:

EventAction
customer.createdCreates customer record
customer.updatedUpdates customer record
customer.deletedScrubs customer PII
customer.subscription.createdCreates subscription record
customer.subscription.updatedUpdates subscription record
customer.subscription.deletedMarks subscription as canceled
payment_intent.succeededCreates payment record
payment_intent.payment_failedUpdates payment status
invoice.createdCreates invoice record
invoice.finalizedUpserts invoice record
invoice.updatedMirrors invoice metadata changes
invoice.paidUpserts invoice as paid
invoice.payment_failedMarks invoice as failed
checkout.session.completedHandles completed checkout sessions

Custom Webhook Handlers

Add custom logic to webhook events:

import { httpRouter } from "convex/server";
import { components } from "./_generated/api";
import { registerRoutes } from "@convex-dev/stripe";
import type Stripe from "stripe";

const http = httpRouter();

registerRoutes(http, components.stripe, {
  events: {
    "customer.subscription.updated": async (ctx, event: Stripe.CustomerSubscriptionUpdatedEvent) => {
      const subscription = event.data.object;
      console.log("Subscription updated:", subscription.id, subscription.status);
      // Add custom logic here
    },
  },
  onEvent: async (ctx, event: Stripe.Event) => {
    // Called for ALL events - useful for logging/analytics
    console.log("Stripe event:", event.type);
  },
});

export default http;

Database Schema

The component creates these tables in its namespace:

customers

FieldTypeDescription
stripeCustomerIdstringStripe customer ID
emailstring?Customer email
namestring?Customer name
metadataobject?Custom metadata

subscriptions

FieldTypeDescription
stripeSubscriptionIdstringStripe subscription ID
stripeCustomerIdstringCustomer ID
statusstringSubscription status
priceIdstringPrice ID
quantitynumber?Seat count
currentPeriodEndnumberPeriod end timestamp
cancelAtPeriodEndbooleanWill cancel at period end
userIdstring?Linked user ID
orgIdstring?Linked org ID
metadataobject?Custom metadata

checkout_sessions

FieldTypeDescription
stripeCheckoutSessionIdstringCheckout session ID
stripeCustomerIdstring?Customer ID
statusstringSession status
modestringSession mode (payment/subscription/setup)
metadataobject?Custom metadata

payments

FieldTypeDescription
stripePaymentIntentIdstringPayment intent ID
stripeCustomerIdstring?Customer ID
amountnumberAmount in cents
currencystringCurrency code
statusstringPayment status
creatednumberCreated timestamp
userIdstring?Linked user ID
orgIdstring?Linked org ID
metadataobject?Custom metadata

invoices

FieldTypeDescription
stripeInvoiceIdstringInvoice ID
stripeCustomerIdstringCustomer ID
stripeSubscriptionIdstring?Subscription ID
statusstringInvoice status
amountDuenumberAmount due
amountPaidnumberAmount paid
creatednumberCreated timestamp
userIdstring?Linked user ID
orgIdstring?Linked org ID
metadataobject?Invoice metadata

Example App

Check out the full example app in the example/ directory:

git clone https://github.com/get-convex/convex-stripe
cd convex-stripe
npm install
npm run dev

The example includes:

  • Landing page with product showcase
  • One-time payments and subscriptions
  • User profile with order history
  • Subscription management (cancel, update seats)
  • Customer portal integration
  • Team/organization billing

Authentication

This component works with any Convex authentication provider. The example uses Clerk:

  1. Create a Clerk application at clerk.com
  2. Add VITE_CLERK_PUBLISHABLE_KEY to your .env.local
  3. Create convex/auth.config.ts:
export default {
  providers: [
    {
      domain: "https://your-clerk-domain.clerk.accounts.dev",
      applicationID: "convex",
    },
  ],
};

Troubleshooting

Tables are empty after checkout

Make sure you've:

  1. Set STRIPE_SECRET_KEY and STRIPE_WEBHOOK_SECRET in Convex environment variables
  2. Configured the webhook endpoint in Stripe with the correct events
  3. Added invoice.created and invoice.finalized events (not just invoice.paid)

"Not authenticated" errors

Ensure your auth provider is configured:

  1. Create convex/auth.config.ts with your provider
  2. Run npx convex dev to push the config
  3. Verify the user is signed in before calling actions

Webhooks returning 400/500

Check the Convex logs in your dashboard for errors. Common issues:

  • Missing STRIPE_WEBHOOK_SECRET
  • Wrong webhook URL (should be https://<deployment>.convex.site/stripe/webhook)
  • Missing events in webhook configuration

License

Apache-2.0

版本与发布记录

@convex-dev/stripe 共发布 7 个版本,首次发布于 2025/12/02;过去 12 个月发布了 7 个版本。

版本发布日期距今
0.1.7latest2026/10/101 个月前
0.1.62026/07/114 个月前
0.1.42026/03/137 个月前
0.1.32026/01/179 个月前
0.1.22025/12/2010 个月前
0.1.12025/12/0211 个月前

关于 @convex-dev/stripe 的常见问题

@convex-dev/stripe 是什么?

A stripe component for Convex.

如何安装 @convex-dev/stripe?

在项目目录运行 npm install @convex-dev/stripe,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(^18.3.1 || ^19.0.0)、convex(^1.29.3)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@convex-dev/stripe 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@convex-dev/stripe 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@convex-dev/stripe 可以商用吗?

@convex-dev/stripe 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@convex-dev/stripe 的下载量有多少?

根据 npm 官方下载统计,@convex-dev/stripe 在 2026/10/11 – 2026/11/09 这 30 天内被下载 502,616 次,日均约 16,754 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@convex-dev/stripe 还在维护吗?

最新版本 0.1.7 发布于 2026/10/10(1 个月前);至今共发布 7 个版本,其中过去 12 个月发布了 7 个;首次发布于 2025/12/02。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。