> ## 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.

# Subscriptions

> Enable and manage Razorpay subscriptions with the better-auth-razorpay plugin, including plan upgrades, lifecycle management, and feature gating.

The better-auth-razorpay plugin provides full subscription management backed by Razorpay. This guide covers enabling subscriptions, defining plans, upgrading users, handling the subscription lifecycle, and gating application features based on plan limits and status.

## Enable subscriptions

Set `subscription.enabled: true` in the plugin options and provide at least one plan. Each plan maps a friendly name to a Razorpay `plan_id`.

```ts auth.ts theme={null}
import { betterAuth } from "better-auth";
import { razorpay } from "@amank-root/better-auth-razorpay";

export const auth = betterAuth({
  plugins: [
    razorpay({
      keyId: process.env.RAZORPAY_KEY_ID!,
      keySecret: process.env.RAZORPAY_KEY_SECRET!,
      razorpayWebhookSecret: process.env.RAZORPAY_WEBHOOK_SECRET,
      createCustomerOnSignUp: true,
      subscription: {
        enabled: true,
        plans: [
          {
            planId: "plan_monthly_basic",
            annualPlanId: "plan_annual_basic",
            name: "basic",
            totalCount: 12,
            limits: { projects: 3, storage: 10 },
          },
          {
            planId: "plan_monthly_pro",
            annualPlanId: "plan_annual_pro",
            name: "pro",
            totalCount: 12,
            quantity: 5,
            limits: { projects: 20, storage: 100 },
            freeTrial: { days: 14 },
          },
        ],
      },
    }),
  ],
});
```

> [!NOTE]
>
> Set `createCustomerOnSignUp: true` so every user gets a Razorpay customer ID stored in `user.razorpayCustomerId`. The upgrade endpoint requires it.

After adding the plugin, run Better Auth's schema migration to create the `subscription` table:

```bash theme={null}
npx @better-auth/cli migrate
```

## Upgrade flow

Call `authClient.subscription.upgrade` from your frontend to create a subscription. The plugin creates a local row with status `"created"`, then creates the Razorpay subscription and returns a `shortUrl` (hosted authorization page) and a Razorpay `subscription_id`.

```tsx pages/pricing.tsx theme={null}
"use client";

import { useState } from "react";
import { authClient } from "@/lib/auth-client";
import {
  useUpgradeSubscription,
  useSubscriptionList,
  useSubscriptionStatus,
} from "@amank-root/better-auth-razorpay/react";

export default function PricingPage() {
  const { data: subscriptions } = useSubscriptionList(authClient);
  const upgrade = useUpgradeSubscription(authClient);
  const [annual, setAnnual] = useState(false);

  const activeSub = subscriptions?.[0];
  const status = useSubscriptionStatus(activeSub);

  const handleUpgrade = async (planName: string) => {
    const { data, error } = await upgrade.mutateAsync({
      plan: planName,
      annual,
      quantity: 1,
    });

    if (error) {
      console.error("Upgrade failed:", error.message);
      return;
    }

    // Option 1: redirect to Razorpay's hosted authorization page
    window.location.href = data.subscription.shortUrl!;

    // Option 2: open Razorpay Checkout with subscription_id
    // const rzp = new (window as any).Razorpay({
    //   key: process.env.NEXT_PUBLIC_RAZORPAY_KEY_ID!,
    //   subscription_id: data.razorpaySubscription.id,
    //   name: "My SaaS",
    //   handler: (response: any) => {
    //     console.log("Payment response:", response);
    //   },
    // });
    // rzp.open();
  };

  return (
    <div>
      <label>
        <input
          type="checkbox"
          checked={annual}
          onChange={(e) => setAnnual(e.target.checked)}
        />
        Bill annually
      </label>

      <button onClick={() => handleUpgrade("basic")}>
        Upgrade to Basic
      </button>
      <button onClick={() => handleUpgrade("pro")}>
        Upgrade to Pro
      </button>

      {activeSub && (
        <p>
          Current plan: {activeSub.plan} ({status.isActive ? "active" : "inactive"})
        </p>
      )}
    </div>
  );
}
```

> [!NOTE]
>
> The `annual: true` option swaps the plan to its `annualPlanId`. If you do not define `annualPlanId`, the monthly plan is used regardless of this flag.

## Subscription lifecycle

A subscription moves through several statuses as the customer authorizes payment, the first charge succeeds, and subsequent billing cycles progress. The plugin keeps the local `subscription` row in sync via webhooks.

```mermaid theme={null}
flowchart LR
    A["created"] --> B["authenticated"]
    B --> C["active"]
    C --> D["paused"]
    D --> C
    C --> E["halted"]
    E --> C
    C --> F["cancelled"]
    C --> G["completed"]
    C --> H["expired"]
    B --> I["pending"]
```

**1. Created**

The plugin creates a local row and a Razorpay subscription. The customer has not yet authorized payment.

**2. Authenticated**

The customer completed the Razorpay authorization flow. A trial may be active.

**3. Active**

The first charge succeeded and recurring billing is in progress.

**4. Paused**

Billing is temporarily stopped. Resume to return to active.

**5. Halted**

Razorpay halted the subscription after repeated payment failures. It can be resumed.

**6. Cancelled**

The subscription was cancelled by the user or admin. It will not bill again.

**7. Completed**

All billing cycles finished successfully.

**8. Expired**

The subscription expired without completing all cycles.

## Cancel, pause, resume, and restore

Use the client methods or React mutation hooks to manage an existing subscription.

### Cancel now or at cycle end

```ts theme={null}
// Immediate cancellation
const { data, error } = await authClient.subscription.cancel({
  cancelAtCycleEnd: false,
});

// Cancel at the end of the current billing period
const { data, error } = await authClient.subscription.cancel({
  cancelAtCycleEnd: true,
});
```

### Pause and resume

```ts theme={null}
// Pause billing immediately
const { data, error } = await authClient.subscription.pause({
  pauseAt: "now",
});

// Resume billing
const { data, error } = await authClient.subscription.resume({
  resumeAt: "now",
});
```

### Restore a pending cancellation

If a subscription has `cancelAtCycleEnd: true`, you can restore it before the cycle ends:

```ts theme={null}
const { data, error } = await authClient.subscription.restore();
```

> [!WARNING]
>
> Restore only clears the local `cancelAtCycleEnd` flag. Razorpay does not expose a native restore API for subscriptions scheduled to cancel.

## Update a subscription

Change the plan, seat quantity, metadata, or schedule a change for the next cycle.

```ts theme={null}
const { data, error } = await authClient.subscription.update({
  planId: "plan_monthly_enterprise",
  quantity: 10,
  scheduleChangeAt: "cycle_end",
  metadata: { team: "engineering" },
});
```

**planId** `string`

Razorpay plan ID to switch to.

**quantity** `number`

Number of seats or units.

**scheduleChangeAt** `string`

`"now"` applies immediately. `"cycle_end"` applies after the current period.

**metadata** `object`

Arbitrary key-value data stored on the subscription.

## List and get subscriptions

Fetch local subscriptions for the current user or an organization.

```ts theme={null}
// List all subscriptions for the current user
const { data: subs } = await authClient.subscription.list();

// Get a specific subscription by local ID
const { data: sub } = await authClient.subscription.get({
  subscriptionId: "sub_local_123",
});
```

For organization subscriptions, pass `customerType: "organization"` and optionally `referenceId`:

```ts theme={null}
const { data: orgSubs } = await authClient.subscription.list({
  customerType: "organization",
  referenceId: "org_123",
});
```

## Feature gating with plan limits

Use `limits` defined in each plan and `useSubscriptionStatus` to guard features in your UI.

```tsx components/feature-gate.tsx theme={null}
"use client";

import { authClient } from "@/lib/auth-client";
import {
  useSubscriptionList,
  useSubscriptionStatus,
} from "@amank-root/better-auth-razorpay/react";

export function ProjectCreator() {
  const { data: subscriptions } = useSubscriptionList(authClient);
  const sub = subscriptions?.[0];
  const status = useSubscriptionStatus(sub);

  const planLimits = sub?.metadata
    ? JSON.parse(sub.metadata)
    : { projects: 0 };

  if (!status.isUsable) {
    return <p>Please upgrade to create projects.</p>;
  }

  return (
    <div>
      <p>
        Projects used: {planLimits.projectsUsed ?? 0} /{" "}
        {planLimits.projects ?? 0}
      </p>
      <button disabled={(planLimits.projectsUsed ?? 0) >= (planLimits.projects ?? 0)}>
        Create project
      </button>
    </div>
  );
}
```

> [!NOTE]
>
> `isUsable` returns `true` when the subscription is `active` or in a usable authenticated/trial state. `isTerminal` returns `true` for `cancelled`, `completed`, or `expired`.

## Common errors

| Error code | When it occurs |
| - | - |
| `SUBSCRIPTION_PLAN_NOT_FOUND` | The plan name passed to upgrade does not exist in the plugin config. |
| `ALREADY_SUBSCRIBED_PLAN` | The user or organization already has an active or authenticated subscription on the same plan. |
| `CUSTOMER_NOT_FOUND` | The user does not have a `razorpayCustomerId`. Enable `createCustomerOnSignUp`. |
| `EMAIL_VERIFICATION_REQUIRED` | `requireEmailVerification` is enabled and the user's email is not verified. |
| `SUBSCRIPTION_NOT_FOUND` | The subscription does not exist for the given reference. |
| `SUBSCRIPTION_ALREADY_CANCELLED` | The subscription is already cancelled. |
| `SUBSCRIPTION_NOT_ACTIVE` | Pause or resume called on a subscription that is not active. |
| `SUBSCRIPTION_NOT_PAUSED` | Resume called on a subscription that is not paused. |
| `SUBSCRIPTION_NOT_PENDING_CANCEL` | Restore called on a subscription that is not scheduled to cancel at cycle end. |
| `SUBSCRIPTION_UPDATE_FAILED` | Razorpay rejected the update request. |
| `ORGANIZATION_REFERENCE_ID_REQUIRED` | Organization upgrade called without a `referenceId` and no active organization in the session. |
| `AUTHORIZE_REFERENCE_REQUIRED` | `authorizeReference` is not configured for organization subscriptions. |

## Webhook activation

Razorpay sends `subscription.authenticated`, `subscription.activated`, and `subscription.charged` events as the subscription progresses. The plugin updates the local row before firing your callbacks. You do not need to poll for status changes if webhooks are configured.

```ts auth.ts theme={null}
razorpay({
  // ...
  subscription: {
    enabled: true,
    plans: [...],
    onSubscriptionActivated: async ({ subscription, plan }) => {
      console.log("Subscription activated:", subscription.id, plan.name);
    },
    onSubscriptionCharged: async ({ subscription }) => {
      console.log("Billing cycle charged:", subscription.id);
    },
  },
});
```

See [Webhooks](https://better-auth-razorpay.amankushwaha.dev/guides/webhooks.md) for full setup instructions.


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