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

# Plans

> Create, list, and fetch Razorpay plans, then use them in the better-auth-razorpay plugin configuration and React hooks.

Razorpay plans define the billing interval, amount, and item details for subscriptions. The better-auth-razorpay plugin lets you create plans programmatically, list existing ones, and reference them in your subscription configuration.

## Create a plan

Call `auth.api.createPlan` from the server to create a new Razorpay plan. This is typically an admin-only operation. Validate the caller's role before invoking the endpoint.

```ts app/api/admin/plans/route.ts theme={null}
import { auth } from "@/lib/auth";
import { headers } from "next/headers";

export async function POST(request: Request) {
  const body = await request.json();

  // Verify admin role before creating plans
  const session = await auth.api.getSession({ headers: await headers() });
  if (!session || session.user.role !== "admin") {
    return new Response("Unauthorized", { status: 403 });
  }

  const { data, error } = await auth.api.createPlan({
    body: {
      period: "monthly",
      interval: 1,
      itemName: "Pro plan",
      itemAmount: 99900, // INR 999 in paise
      itemCurrency: "INR",
      itemDescription: "Monthly pro subscription with full features",
      notes: { internal_code: "PRO_M_001" },
    },
    headers: await headers(),
  });

  if (error) {
    return Response.json({ error: error.message }, { status: 400 });
  }

  return Response.json(data);
}
```

**period** `string` *required*

Billing frequency: `"daily"`, `"weekly"`, `"monthly"`, `"quarterly"`, or `"yearly"`.

**interval** `number` *required*

Interval count. For example, `1` with `"monthly"` means every month; `3` means every 3 months.

**itemName** `string` *required*

Display name for the plan item.

**itemAmount** `number` *required*

Amount in currency subunits (paise for INR).

**itemCurrency** `string` (default: INR)

3-character ISO currency code.

**itemDescription** `string`

Optional description for the plan item.

**notes** `object`

Up to 15 key-value pairs stored with the plan.

> [!WARNING]
>
> Plan creation is an admin operation. Always verify the caller's permissions on the server before creating plans, because the endpoint does not enforce role checks internally.

## List plans

Fetch all plans from your Razorpay account.

```ts theme={null}
const { data, error } = await authClient.razorpay.plan.list();

if (!error) {
  data.items.forEach((plan: any) => {
    console.log(plan.id, plan.item.name, plan.period, plan.interval);
  });
}
```

## Fetch a single plan

Retrieve a specific plan by its Razorpay ID.

```ts theme={null}
const { data, error } = await authClient.razorpay.plan.get({
  query: { planId: "plan_XXXX" },
});
```

## Use a created plan in plugin config

After creating a plan in Razorpay, copy its `id` into the plugin's `subscription.plans` array so users can subscribe to it.

```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_XXXX", // monthly plan created via API
            annualPlanId: "plan_YYYY", // optional yearly variant
            name: "pro",
            totalCount: 12,
            limits: { projects: 20, storage: 100 },
            freeTrial: { days: 14 },
          },
        ],
      },
    }),
  ],
});
```

> [!NOTE]
>
> The `name` field is matched case-insensitively when users call `authClient.subscription.upgrade({ plan: "pro" })`. The plugin stores the plan name lowercased in the database.

## Dynamic plans

If your application supports plan creation from an admin dashboard, you can fetch the latest plans from Razorpay at runtime and use them to populate your pricing page or plugin configuration.

```tsx app/admin/plans/page.tsx theme={null}
"use client";

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

export default function AdminPlansPage() {
  const { data: plans, isLoading } = useRazorpayPlans(authClient);

  if (isLoading) return <p>Loading plans...</p>;

  return (
    <table>
      <thead>
        <tr>
          <th>ID</th>
          <th>Name</th>
          <th>Period</th>
          <th>Amount</th>
        </tr>
      </thead>
      <tbody>
        {plans?.items?.map((plan: any) => (
          <tr key={plan.id}>
            <td>{plan.id}</td>
            <td>{plan.item.name}</td>
            <td>{plan.period}</td>
            <td>{plan.item.amount / 100} {plan.item.currency}</td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}
```

## React hook: useRazorpayPlans

`useRazorpayPlans` fetches the full list of Razorpay plans and caches it with TanStack Query. You can pass `queryOptions` to customize caching behavior.

```tsx theme={null}
import { useRazorpayPlans } from "@amank-root/better-auth-razorpay/react";

const { data, isLoading, error } = useRazorpayPlans(authClient, {
  queryOptions: {
    staleTime: 5 * 60 * 1000, // 5 minutes
  },
});
```

## Common errors

| Error code | When it occurs |
| - | - |
| `PLAN_CREATE_FAILED` | Razorpay rejected the plan creation request. |
| `PLAN_NOT_FOUND` | The requested plan ID does not exist in Razorpay. |
| `FAILED_TO_FETCH_PLANS` | The plugin could not retrieve plans from Razorpay. |


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