> ## Documentation Index
> Fetch the complete documentation index at: https://better-auth-razorpay.amankushwaha.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Subscription plans

> Configure Razorpay plans, trials, billing cycles, and subscription lifecycle callbacks inside the Razorpay plugin.

The `subscription` option in the Razorpay plugin controls whether subscriptions are enabled and how plans are defined. This page covers every field inside `SubscriptionOptions` and `RazorpayPlan`, how to load plans dynamically, and how to use limits, groups, and callbacks.

## Subscription options

**enabled** `boolean` *required*

Set to `true` to register subscription endpoints and create the local `subscription` table. Set to `false` to disable subscriptions entirely.

**plans** `RazorpayPlan[] | (() =\> RazorpayPlan[] | Promise\<RazorpayPlan[]\>)`

A static array of plans, or an async function that returns plans at runtime. Use a function when you store plan definitions in your own database or CMS. If the function throws, the plugin raises `FAILED_TO_FETCH_PLANS`.

**requireEmailVerification** `boolean` (default: false)

When `true`, users must verify their email before upgrading. If unverified, the upgrade endpoint returns `EMAIL_VERIFICATION_REQUIRED` or `FORBIDDEN`.

**authorizeReference** `(\{ user, session, referenceId, action \}, ctx) =\> boolean | Promise\<boolean\>` *required*

Authorize subscription actions for a specific reference id. The `action` argument is one of `upgrade-subscription`, `list-subscription`, `cancel-subscription`, `pause-subscription`, `resume-subscription`, `update-subscription`, `restore-subscription`, or `get-subscription`. Required for organization subscriptions; without it the plugin raises `AUTHORIZE_REFERENCE_REQUIRED`. Returning `false` raises `UNAUTHORIZED` or `REFERENCE_ID_NOT_ALLOWED`.

**getSubscriptionCreateParams** `(\{ user, session, plan \}, ctx) =\> Partial\<subscription create params\>`

Merge extra fields into the Razorpay subscription create payload. Common uses include adding `notes`, an `offer_id`, or custom metadata that Razorpay will echo back in webhooks.

## Razorpay plan fields

**planId** `string` *required*

The Razorpay plan id, for example `plan_XXXX`. This is the plan that Razorpay bills against.

**name** `string` *required*

The display name matched case-insensitively during upgrades. The matched name is stored in the local subscription row in lowercase, for example `pro`.

**annualPlanId** `string`

An optional Razorpay plan id used when the user selects annual billing during upgrade. If omitted, annual upgrades fall back to `planId`.

**limits** `Record\<string, unknown\>`

Arbitrary key-value pairs you can read in your application to gate features. For example, `{ projects: 5, storageGb: 10 }`.

**group** `string`

A group identifier for categorizing plans, such as `individual` or `team`.

**totalCount** `number` (default: 0)

Number of billing cycles before the subscription automatically completes. `0` means no fixed limit.

**quantity** `number` (default: 1)

Default quantity for the subscription. For seat-based plans, this is typically overridden per organization based on member count.

**freeTrial** `\{ days: number, onTrialStart?, onTrialEnd?, onTrialExpired? \}`

Configure a free trial for this plan. `days` is the trial length. `onTrialStart` runs when the trial begins. `onTrialEnd` runs when the trial ends normally. `onTrialExpired` runs if the trial expires without activation.

## Static vs dynamic plans

You can define plans directly in code, or load them from an external source.

### Static plans

Pass a plain array when your plans rarely change:

```ts auth.ts theme={null}
subscription: {
  enabled: true,
  plans: [
    { planId: "plan_starter", name: "starter", totalCount: 12 },
    { planId: "plan_pro", name: "pro", annualPlanId: "plan_pro_yearly", totalCount: 12, quantity: 1 },
  ],
}
```

### Dynamic plans

Pass an async function when you manage plans in a database or CMS:

```ts auth.ts theme={null}
subscription: {
  enabled: true,
  plans: async () => {
    const rows = await db.selectFrom("plans").selectAll().execute();
    return rows.map((r) => ({
      planId: r.razorpayPlanId,
      name: r.slug,
      annualPlanId: r.razorpayAnnualPlanId ?? undefined,
      limits: r.limits as Record<string, unknown>,
      totalCount: r.totalCount ?? 12,
      quantity: r.defaultQuantity ?? 1,
    }));
  },
}
```

If the function throws, the plugin responds with `FAILED_TO_FETCH_PLANS`.

## Annual plans

When a user upgrades with `annual: true`, the plugin swaps `planId` for `annualPlanId` in the Razorpay subscription create call. If `annualPlanId` is absent, it falls back to the monthly `planId`.

```ts client.ts theme={null}
const { data, error } = await authClient.subscription.upgrade({
  plan: "pro",
  annual: true,
});
```

## Using limits to gate features

Store feature limits on each plan, then read them by the stored subscription plan name:

```ts server.ts theme={null}
const subscription = await db
  .selectFrom("subscription")
  .selectAll()
  .where("referenceId", "=", user.id)
  .orderBy("createdAt", "desc")
  .executeTakeFirst();

const plan = auth.options.plugins
  .find((p) => p.id === "razorpay")
  ?.options.subscription.plans
  .find((p) => p.name === subscription?.plan);

const maxProjects = (plan?.limits?.projects as number) ?? 1;
```

> [!TIP]
>
> Keep a local cache of plan definitions if you query them on every request, or store denormalized limits on the subscription row after upgrade.

## Groups, total count, and quantity

* **group** lets you render plan selectors in your UI by category.
* **totalCount** sets a fixed number of billing cycles. When reached, the subscription status becomes `completed`.
* **quantity** is the default number of units billed per cycle. For seat-based plans, the plugin can override this automatically based on organization membership.

## Free trials

A trial delays the first charge by the specified number of days. The plugin records `trialStart` and `trialEnd` on the local subscription row. Trials are only granted if the reference id has never had a trial before.

```ts auth.ts theme={null}
{
  planId: "plan_pro",
  name: "pro",
  freeTrial: {
    days: 14,
    onTrialStart: (subscription) => {
      console.log("Trial started", subscription.id);
    },
    onTrialEnd: ({ subscription }) => {
      console.log("Trial ended", subscription.id);
    },
    onTrialExpired: (subscription) => {
      console.log("Trial expired without activation", subscription.id);
    },
  },
}
```

For a complete guide on free trials, including how they interact with upgrades and cancellations, read [free trials](https://better-auth-razorpay.amankushwaha.dev/guides/free-trials.md).

## Lifecycle callbacks

Subscription webhooks update the local row automatically, but you can hook into specific transitions for side effects such as provisioning features or sending emails.

**onSubscriptionActivated** `(\{ event, razorpaySubscription, subscription, plan \}) =\> void | Promise\<void\>`

Fired when a subscription becomes active.

**onSubscriptionCharged** `(\{ event, razorpaySubscription, subscription \}) =\> void | Promise\<void\>`

Fired on each successful charge.

**onSubscriptionAuthenticated** `(\{ event, razorpaySubscription, subscription \}) =\> void | Promise\<void\>`

Fired when the subscription is authenticated.

**onSubscriptionCancelled** `(\{ event, razorpaySubscription, subscription \}) =\> void | Promise\<void\>`

Fired when the subscription is cancelled.

**onSubscriptionPaused** `(\{ event, razorpaySubscription, subscription \}) =\> void | Promise\<void\>`

Fired when the subscription is paused.

**onSubscriptionResumed** `(\{ event, razorpaySubscription, subscription \}) =\> void | Promise\<void\>`

Fired when the subscription resumes.

**onSubscriptionHalted** `(\{ event, razorpaySubscription, subscription \}) =\> void | Promise\<void\>`

Fired when the subscription is halted.

**onSubscriptionPending** `(\{ event, razorpaySubscription, subscription \}) =\> void | Promise\<void\>`

Fired when the subscription enters a pending state.

**onSubscriptionCompleted** `(\{ event, razorpaySubscription, subscription \}) =\> void | Promise\<void\>`

Fired when the subscription completes all billing cycles.

**onSubscriptionUpdated** `(\{ event, razorpaySubscription, subscription \}) =\> void | Promise\<void\>`

Fired when the subscription is updated.

**onSubscriptionRenewed** `(\{ event, razorpaySubscription, subscription \}) =\> void | Promise\<void\>`

Fired when the subscription renews.

### Example: sending emails on activation

```ts auth.ts theme={null}
subscription: {
  enabled: true,
  plans: [...],
  onSubscriptionActivated: async ({ subscription, plan }) => {
    await sendEmail({
      to: subscription.userEmail,
      subject: `Welcome to ${plan.name}`,
      body: `Your subscription is now active.`,
    });
  },
}
```

> [!NOTE]
>
> The README shows some subscription callbacks at the top level of the plugin options, but the TypeScript types define them inside `subscription`. The types are authoritative, so always place callbacks under `subscription`.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.