new·Earn with mozg — 20% of every monthSend somebody here and take a fifth of every plan payment they make, for as long as they keep paying — not a bounty on the first invoice. Your handle is the link, the window is thirty days, and the commission lands on your balance the second they pay. Free to join: if you have signed in, you already have the link. mozg.sh/earnall news →
mozg.beta
Sign in

Better Auth · Plugins · all subjects

stripe plugin

41 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

Stripe plugin automatic Stripe customer creation

When createCustomerOnSignUp is set to true, a Stripe customer is automatically created on signup and linked to the user in the database.

Stripe plugin installation requires Stripe SDK v22.0.0

The Stripe SDK version 22.0.0 or higher must be installed on the server. The plugin uses the async webhook signature verification method (constructEventAsync) available in Stripe SDK v19 and later.

Stripe plugin requires stripeClient and stripeWebhookSecret

The stripe plugin has two required configuration options: stripeClient (a Stripe client instance) and stripeWebhookSecret (the webhook signing secret from Stripe).

Stripe plugin subscription upgrade endpoint

The endpoint POST /subscription/upgrade creates or upgrades a subscription. Parameters: plan (string, required), annual (boolean, optional, default true), referenceId (string, optional), subscriptionId (string, optional), metadata (Record<string, any>, optional), customerType ("user" | "organization", optional, default "user"), seats (number, optional, default 1), locale (string, optional), successUrl (string, required), cancelUrl (string, required), returnUrl (string, optional), disableRedirect (boolean, optional, default false), scheduleAtPeriodEnd (boolean, optional, default false).

Stripe plugin subscription list endpoint

The endpoint GET /subscription/list retrieves active subscriptions. Parameters: referenceId (string, optional, default '123'), customerType ("user" | "organization", optional, default "user"). Requires authorizeReference function configured in plugin for authorization.

Stripe plugin subscription cancel endpoint

The endpoint POST /subscription/cancel cancels a subscription. Parameters: referenceId (string, optional, default 'org_123'), customerType ("user" | "organization", optional, default "user"), subscriptionId (string, optional, default 'sub_123'), returnUrl (string, required, default '/account'). Redirects user to Stripe Billing Portal.

Stripe plugin subscription restore endpoint

The endpoint POST /subscription/restore restores a subscription that is still active but has a pending cancellation or scheduled plan change. Cannot restore subscriptions that have already ended (status: "canceled" with endedAt set). Parameters: referenceId (string, optional, default '123'), customerType ("user" | "organization", optional, default "user"), subscriptionId (string, optional, default 'sub_123').

Stripe plugin billing portal endpoint

The endpoint POST /subscription/billing-portal creates a Stripe billing portal session. Parameters: locale (string, optional, IETF language tag), referenceId (string, optional, default "123"), customerType ("user" | "organization", optional, default "user"), returnUrl (string, optional), disableRedirect (boolean, optional, default false). Returns a URL in response.data.url.

Stripe plugin only supports one active subscription per reference ID

The plugin only supports one active or trialing subscription per reference ID (user or organization) at a time. Multiple concurrent subscriptions for the same reference ID are not supported. If upgrading an existing subscription, the subscriptionId parameter must be provided to avoid creating duplicate subscriptions.

Stripe plugin subscription schema fields

The subscription table has the following fields: id (string, primary key), plan (string), referenceId (string, not unique), stripeCustomerId (string, optional), stripeSubscriptionId (string, optional), status (string, default "incomplete"), periodStart (Date, optional), periodEnd (Date, optional), cancelAtPeriodEnd (boolean, default false, optional), cancelAt (Date, optional), canceledAt (Date, optional), endedAt (Date, optional), seats (number, optional), trialStart (Date, optional), trialEnd (Date, optional), billingInterval (string, optional), stripeScheduleId (string, optional).

Stripe plugin user table schema addition

The Stripe plugin adds stripeCustomerId (string, optional) field to the user table.

Stripe plugin organization table schema addition

The Stripe plugin adds stripeCustomerId (string, optional) field to the organization table when organization.enabled is true.

Stripe plugin plan configuration options

Plan configuration options: name (string, required), priceId (string, required unless using lookupKey), lookupKey (string, alternative to priceId), annualDiscountPriceId (string, optional), annualDiscountLookupKey (string, optional), limits (object, optional), group (string, optional), seatPriceId (string, optional, requires organization plugin), prorationBehavior (string, optional: "create_prorations" default, "always_invoice", or "none"), lineItems (LineItem[], optional), freeTrial (object, optional).

Stripe plugin free trial configuration

Free trial configuration options: days (number, required), onTrialStart (function, receives subscription), onTrialEnd (function, receives { subscription } and context), onTrialExpired (function, receives subscription and context).

Stripe plugin prevents multiple free trials per user

The Stripe plugin automatically prevents users from getting multiple free trials across plans. Once a user has used a trial period (indicated by trialStart/trialEnd fields or trialing status), they will not be eligible for additional trials on any plan. This is automatic and requires no configuration.

Stripe plugin subscription options

Subscription options: enabled (boolean, required), plans (StripePlan[] or async function, required if enabled), requireEmailVerification (boolean, default false), authorizeReference (function, receives { user, session, referenceId, action } and context), getCheckoutSessionParams (function, receives { user, session, plan, subscription }, request, and context), onSubscriptionComplete (function), onSubscriptionCreated (function), onSubscriptionUpdate (function), onSubscriptionCancel (function), onSubscriptionDeleted (function).

Stripe plugin main configuration options

Main plugin options: stripeClient (Stripe, required), stripeWebhookSecret (string, required), createCustomerOnSignUp (boolean, default false), onCustomerCreate (function), getCustomerCreateParams (function), onEvent (function), subscription (object), organization (object), schema (object).

Stripe plugin organization options

Organization options: enabled (boolean, required), getCustomerCreateParams (function, receives organization and context), onCustomerCreate (function, receives { stripeCustomer, organization } and context).

Stripe plugin webhook endpoint configuration

The Stripe plugin expects webhooks to be sent to https://your-domain.com/api/auth/stripe/webhook where /api/auth is the default auth server path. Required webhook events to select: checkout.session.completed, customer.subscription.created, customer.subscription.updated, customer.subscription.deleted.

Stripe plugin webhook events handled automatically

The plugin automatically handles these webhook events: checkout.session.completed (updates subscription status after checkout), customer.subscription.created (creates a subscription when created outside the checkout flow), customer.subscription.updated (updates subscription details when changed), customer.subscription.deleted (marks subscription as canceled).

Stripe plugin scheduleAtPeriodEnd behavior

When scheduleAtPeriodEnd is true, the subscription plan is not changed until the billing period ends. Only stripeScheduleId is stored so clients can detect the pending change. No redirect to Stripe Checkout or Billing Portal occurs; the change is applied server-side. At period end, Stripe fires a customer.subscription.updated webhook which updates the subscription record automatically. If a new upgrade or schedule is requested before the period ends, the existing pending schedule is released first.

Stripe plugin subscription cancellation state fields

Subscription cancellation tracking fields: cancelAtPeriodEnd (whether subscription will or did cancel at end of billing period), cancelAt (time at which cancellation will take effect if scheduled), canceledAt (time when cancellation was requested or when status changed to canceled), endedAt (date the subscription actually ended).

Stripe plugin checkout session success URL redirect handling

The successUrl parameter will be internally modified by the plugin to handle race conditions between checkout completion and webhook processing. The plugin creates an intermediate redirect that ensures subscription status is properly updated before redirecting to the specified success page.

Stripe plugin client method for subscription upgrade

Example code: await authClient.subscription.upgrade({ plan: "pro", successUrl: "/dashboard", cancelUrl: "/pricing", annual: true, referenceId: "org_123", seats: 5, locale: "en" });

Stripe plugin client method for switching plans

Example code: await authClient.subscription.upgrade({ plan: "pro", successUrl: "/dashboard", cancelUrl: "/pricing", subscriptionId: "sub_123" });

Stripe plugin client method for listing subscriptions

Example code: const { data: subscriptions } = await authClient.subscription.list({ query: { referenceId: "org_123456" } });

Stripe plugin client method for canceling subscription

Example code: await authClient.subscription.cancel({ referenceId: "org_123", subscriptionId: "sub_123", returnUrl: "/account" });

Stripe plugin client method for billing portal

Example code: await authClient.subscription.billing-portal({ locale: "en", referenceId: "123", returnUrl: "/billing", disableRedirect: false });

Stripe plugin with organization plugin usage

To use organization as billing entity instead of user, install both organization() and stripe() plugins. Pass customerType: "organization" when calling subscription.upgrade with the organization ID as referenceId.

Stripe plugin organization customer sync

When Organization Customer is enabled: A Stripe Customer is automatically created when an organization first subscribes, organization name changes are synced to the Stripe Customer, and organizations with active subscriptions cannot be deleted.

Stripe plugin blocking user deletion with active subscription

To prevent users with active subscriptions from being deleted, use the beforeDelete callback in the user config. Organizations with active subscriptions are blocked automatically, but users are not.

Stripe plugin static plan definition example

Example code: subscription: { enabled: true, plans: [{ name: "basic", priceId: "price_1234567890", annualDiscountPriceId: "price_1234567890", limits: { projects: 5, storage: 10 } }, { name: "pro", priceId: "price_0987654321", limits: { projects: 20, storage: 50 }, freeTrial: { days: 14 } }] }

Stripe plugin dynamic plan definition example

Example code: subscription: { enabled: true, plans: async () => { const plans = await db.query("SELECT * FROM plans"); return plans.map(plan => ({ name: plan.name, priceId: plan.stripe_price_id, limits: JSON.parse(plan.limits) })); } }

Stripe plugin authorizeReference implementation example

Example code: authorizeReference: async ({ user, session, referenceId, action }) => { if(action === "list-subscription") { const org = await db.member.findFirst({ where: { organizationId: referenceId, userId: user.id } }); return org?.role === "owner" } return true; }

Stripe plugin subscription lifecycle hooks

Available hooks: onSubscriptionComplete (called when subscription created via checkout), onSubscriptionCreated (called when subscription created outside checkout), onSubscriptionUpdate (called when subscription updated), onSubscriptionCancel (called when subscription canceled), onSubscriptionDeleted (called when subscription deleted).

Stripe plugin trial configuration example

Example code: freeTrial: { days: 14, onTrialStart: async (subscription) => { await sendWelcomeEmail(subscription.referenceId); }, onTrialEnd: async ({ subscription }, ctx) => { await sendTrialEndEmail(subscription.referenceId); }, onTrialExpired: async (subscription, ctx) => { await sendTrialExpiredEmail(subscription.referenceId); } }

Stripe plugin custom checkout session parameters example

Example code: getCheckoutSessionParams: async ({ user, session, plan, subscription }, ctx) => { return { params: { allow_promotion_codes: true, tax_id_collection: { enabled: true }, billing_address_collection: "required", custom_text: { submit: { message: "We'll start your subscription right away" } }, metadata: { planType: "business", referralCode: user.metadata?.referralCode } }, options: { idempotencyKey: `sub_${user.id}_${plan.name}_${Date.now()}` } }; }

Stripe plugin team subscription with seats example

Example code: await authClient.subscription.upgrade({ plan: "team", referenceId: "org_123456", seats: 10, successUrl: "/org/billing/success", cancelUrl: "/org/billing" });

Stripe plugin schema customization

Example code: stripe({ subscription: { modelName: "stripeSubscriptions", fields: { plan: "planName" } } })

Stripe plugin mixed-interval subscriptions limitation

Stripe does not support mixed-interval subscriptions via Checkout Sessions. All line items in a checkout must use the same billing interval (e.g. all monthly or all yearly). If intervals differ, the Stripe API will reject the request.

Stripe plugin local webhook testing

For local development, use the Stripe CLI to forward webhooks to the local environment: stripe listen --forward-to localhost:3000/api/auth/stripe/webhook

Give your agent this brain