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

# Webhooks

> Receive Razorpay events, verify their signatures, and react to payments, refunds, invoices, and subscriptions with typed callbacks.

Razorpay sends webhook events to your server when payments, orders, refunds, invoices, and subscriptions change state. The plugin exposes a webhook endpoint, verifies each request's signature, keeps the local `subscription` table in sync, and calls the callbacks you configure.

Use webhooks as the source of truth for fulfillment. Client-side verification tells you the checkout finished, but the `order.paid` and `subscription.activated` events confirm that Razorpay actually received the money.

## How it works

1. Razorpay sends a `POST` request with a JSON body and an `x-razorpay-signature` header.
2. The plugin computes an HMAC-SHA256 of the raw body using `razorpayWebhookSecret` and compares it with the header using a timing-safe comparison.
3. For subscription events, the plugin updates the matching local subscription row (status, billing period dates, and counts).
4. The plugin calls the event-specific callback, such as `onOrderPaid`, and `onEvent` for every event.

## Set up webhooks

**1. Add the webhook secret to your environment**

Choose a strong random string. You use the same value in Razorpay and in your server config.

```bash .env theme={null}
RAZORPAY_WEBHOOK_SECRET=whsec_replace_with_a_long_random_string
```

**2. Configure the plugin**

Pass the secret and the callbacks you need.

```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,
      onOrderPaid: async ({ event, order }) => {
        await markOrderPaid(order.id, order.receipt);
      },
      onPaymentFailed: async ({ payment }) => {
        console.warn("Payment failed", payment.id);
      },
      onRefundProcessed: async ({ refund }) => {
        await markRefundComplete(refund.id);
      },
      onEvent: async (event) => {
        console.log("Razorpay event received", event.event);
      },
    }),
  ],
});
```

`markOrderPaid` and `markRefundComplete` stand in for your own application code.

**3. Register the webhook in Razorpay**

In the Razorpay Dashboard, open **Account & Settings > Webhooks** and add a webhook:

* **Webhook URL**: `https://your-domain.com/api/auth/razorpay/webhook`
* **Secret**: the value of `RAZORPAY_WEBHOOK_SECRET`
* **Active events**: the events you handle (see [Webhook events](https://better-auth-razorpay.amankushwaha.dev/reference/webhook-events.md))

> [!NOTE]
>
> The URL follows the plugin's path convention under your Better Auth base path (`/api/auth`). If Razorpay reports `404` responses, confirm the webhook endpoint path registered by the plugin in your server.

**4. Test locally**

Razorpay cannot reach `localhost`. Expose your dev server with a tunnel such as ngrok and use the public URL in the Razorpay Dashboard while in test mode.

```bash theme={null}
ngrok http 3000
```

## Subscription callbacks

Subscription callbacks live inside the `subscription` options. The plugin updates the local subscription row before it calls them, so `subscription` reflects the new state.

```ts auth.ts theme={null}
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_PRO_MONTHLY", name: "pro" }],
    onSubscriptionActivated: async ({ subscription, plan }) => {
      await grantAccess(subscription.referenceId, plan.name);
    },
    onSubscriptionCharged: async ({ subscription, razorpaySubscription }) => {
      console.log("Renewal charged", razorpaySubscription.id, subscription.paidCount);
    },
    onSubscriptionHalted: async ({ subscription }) => {
      await notifyPaymentIssue(subscription.referenceId);
    },
    onSubscriptionCancelled: async ({ subscription }) => {
      await revokeAccess(subscription.referenceId);
    },
  },
});
```

See [Webhook events](https://better-auth-razorpay.amankushwaha.dev/reference/webhook-events.md) for every event, its callback, and the payload shape.

## Errors

| Code | Cause |
| - | - |
| `WEBHOOK_SIGNATURE_NOT_FOUND` | The request has no `x-razorpay-signature` header. |
| `WEBHOOK_SECRET_NOT_FOUND` | `razorpayWebhookSecret` is not configured. |
| `FAILED_TO_VERIFY_WEBHOOK` | The signature does not match the raw body and secret. |
| `WEBHOOK_ERROR` | A handler or callback threw while processing the event. |

> [!TIP]
>
> Keep callbacks idempotent. Razorpay can deliver the same event more than once, so check whether you already fulfilled an order or granted access before doing it again.

## Verify signatures yourself

If you process webhooks outside the plugin, use the exported helpers. See [Signature utilities](https://better-auth-razorpay.amankushwaha.dev/reference/signature-utilities.md).

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

const isValid = verifyRazorpayWebhookSignature(
  rawBody,
  request.headers.get("x-razorpay-signature") ?? "",
  process.env.RAZORPAY_WEBHOOK_SECRET!,
);
```

## Related

> [card] [Webhook events](https://better-auth-razorpay.amankushwaha.dev/reference/webhook-events.md)
>
> Every supported event and callback.

> [card] [Webhook endpoint](https://better-auth-razorpay.amankushwaha.dev/api-reference/webhook.md)
>
> Endpoint behavior, headers, and responses.


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