Skip to content

Search docs

Jump between documentation pages.

Browse docs

Accept payments with Razorpay in DaloyJS

Razorpay is a default payment stack for India: UPI, cards, netbanking, wallets, EMI, and BNPL through one API. This guide uses the official razorpay Node SDK (2.9.x) for API calls with the Orders flow, and the runtime-portable core verifyWebhookSignature() for both signatures Razorpay sends.

What you should know up front

  • Two signatures, two secrets. (1) The checkout callback signature is HMAC-SHA256 (hex) over order_id|payment_id, keyed with your key secret. (2) The webhook signature in X-Razorpay-Signature is HMAC-SHA256 (hex) over the raw body, keyed with your webhook secret.
  • Orders are the anchor. Create an Order on your server with the amount from your own records, hand order_id to Checkout, then verify the callback. See never trust client amounts.
  • Amounts are paise. 500.00 INR is { amount: 50000, currency: "INR" }. Don't pass floats.
  • Webhook verification needs the raw body. Razorpay's docs warn not to parse or cast the body before verifying.
  • Dedupe on x-razorpay-event-id. Razorpay sends this header, unique per event, specifically so you can drop duplicate deliveries.

1. Provision

  1. Sign in to the Razorpay dashboard.
  2. Account & Settings -> API Keys -> Generate Test Key. Save the key_id and key_secret; the secret is shown once.
  3. Account & Settings -> Webhooks -> Add new. Point it at your DaloyJS endpoint and set a webhook secret. Subscribe to at least payment.captured, payment.failed, order.paid, and refund.processed.
  4. Activate the methods you need (UPI and cards are on by default; netbanking and wallets may need enabling).

2. Install

bash
pnpm add razorpay

3. Environment variables

.envbash
RAZORPAY_KEY_ID=rzp_test_replace_me            # public; also used by Checkout JS
RAZORPAY_KEY_SECRET=replace_me                 # secret; verifies the checkout callback
RAZORPAY_WEBHOOK_SECRET=replace_me             # webhook secret; verifies webhooks
APP_URL=https://your-app.example.com

4. Plugin

src/plugins/razorpay.tsts
import Razorpay from "razorpay";
import { verifyWebhookSignature } from "@daloyjs/core";
import type { App } from "@daloyjs/core";

const razorpay = new Razorpay({
  key_id: process.env.RAZORPAY_KEY_ID!,
  key_secret: process.env.RAZORPAY_KEY_SECRET!,
});

export interface RazorpayClient {
  raw: Razorpay;
  createOrder(input: { amount: number; currency: string; receipt: string }): Promise<{ id: string; amount: number; currency: string }>;
  fetchOrder(orderId: string): Promise<{ id: string; receipt?: string }>;
  fetchPayment(paymentId: string): Promise<{ id: string; status: string; amount: number; currency: string; order_id?: string }>;
  verifyCheckoutSignature(input: { orderId: string; paymentId: string; signature: string }): Promise<boolean>;
  verifyWebhookSignature(rawBody: Uint8Array, signatureHeader: string | null): Promise<boolean>;
  refund(input: { paymentId: string; amount: number; notes?: Record<string, string> }): Promise<{ id: string; status: string }>;
}

// Exported so job handlers (which run outside a request) can use it too.
export const razorpayClient: RazorpayClient = {
  raw: razorpay,

  async createOrder({ amount, currency, receipt }) {
    const order = await razorpay.orders.create({ amount, currency, receipt, notes: { orderId: receipt } });
    return { id: order.id, amount: Number(order.amount), currency: order.currency };
  },

  async fetchOrder(orderId) {
    const order = await razorpay.orders.fetch(orderId);
    return { id: order.id, receipt: order.receipt ?? undefined };
  },

  async fetchPayment(paymentId) {
    const p = await razorpay.payments.fetch(paymentId);
    return { id: p.id, status: p.status, amount: Number(p.amount), currency: p.currency, order_id: p.order_id };
  },

  verifyCheckoutSignature({ orderId, paymentId, signature }) {
    return verifyWebhookSignature({
      payload: `${orderId}|${paymentId}`,
      signature,
      secret: process.env.RAZORPAY_KEY_SECRET!,
      algorithm: "sha256",
    });
  },

  async verifyWebhookSignature(rawBody, signatureHeader) {
    if (!signatureHeader) return false;
    return verifyWebhookSignature({
      payload: rawBody,
      signature: signatureHeader,
      secret: process.env.RAZORPAY_WEBHOOK_SECRET!,
      algorithm: "sha256",
    });
  },

  async refund({ paymentId, amount, notes }) {
    const refund = await razorpay.payments.refund(paymentId, { amount, notes, speed: "normal" });
    return { id: refund.id, status: refund.status };
  },
};

// Call with the root app, not through app.register(): a decoration made
// inside a registered plugin is visible only to that plugin's own routes.
export function razorpayPlugin(app: App) {
  app.decorate("razorpay", razorpayClient);
}

declare module "@daloyjs/core" {
  interface AppState {
    razorpay: RazorpayClient;
  }
}

The SDK also ships validatePaymentVerification and validateWebhookSignature in razorpay/dist/utils/razorpay-utils.js. Under ESM you must import that path with the .js extension. The core helper is preferable anyway: it compares in constant time (the SDK helpers use ===) and runs on WebCrypto, so it also works where Node's crypto module does not.

5. Create an order

The frontend uses Razorpay Checkout JS with the razorpayOrderId from this endpoint plus your public key_id. The route relies on the shared app wiring (session, scoped csrf() and rateLimit()) and the overview's orders module.

src/routes/checkout-razorpay.tsts
import { z } from "zod";
import { razorpayPlugin } from "../plugins/razorpay.ts";
import { orders } from "../orders.ts";
import { db } from "../db.ts";

razorpayPlugin(app);

app.post(
  "/checkout/razorpay/order",
  {
    operationId: "createRazorpayOrder",
    request: {
      body: z.object({ orderId: z.string().min(1).max(40) }).strict(), // becomes "receipt"
    },
    responses: {
      201: {
        description: "order created",
        body: z.object({ razorpayOrderId: z.string(), amount: z.number(), currency: z.string(), keyId: z.string() }),
      },
    },
  },
  async ({ body, state }) => {
    const order = await orders.forCheckout(body.orderId, state.session.get<string>("userId"));

    // The Orders API has no idempotency key: reuse the Razorpay order already
    // created for this cart version instead of creating a second one.
    const existing = await db.orders.providerOrderFor(order.id, order.version);
    const rzp = existing ?? (await state.razorpay.createOrder({
      amount: order.amountMinor, // paise, from your records
      currency: order.currency,
      receipt: order.id,
    }));
    if (!existing) await db.orders.saveProviderOrder(order.id, order.version, rzp);

    return {
      status: 201,
      body: { razorpayOrderId: rzp.id, amount: rzp.amount, currency: rzp.currency, keyId: process.env.RAZORPAY_KEY_ID! },
    };
  },
);

6. Verify the client callback

Order + client callback verification
BrowserDaloyJS routeRazorpay
  1. 01requestBrowserDaloyJS routePOST /checkout/razorpay/order{ orderId } only
  2. 02requestDaloyJS routeRazorpayorders.create with the server-side amountCheckout JS opens with order_id
  3. 03requestBrowserDaloyJS routePOST /checkout/razorpay/verifyrazorpay_order_id, _payment_id, _signature
  4. 04noteDaloyJS routeDaloyJS routeHMAC over order_id|payment_id with the key secret401 on mismatch, 404 if the order is not yours
  5. 05responseDaloyJS routeBrowser200 when captured, 409 when not yetsignature proves origin, not capture
Verify the callback signature with your key secret, check that the Razorpay order belongs to the signed-in user's order, then refetch the payment because the signature proves the callback came from Razorpay but not that it was captured.

After a successful payment, Checkout JS hands { razorpay_order_id, razorpay_payment_id, razorpay_signature } to your client. Forward them to the server:

ts
app.post(
  "/checkout/razorpay/verify",
  {
    operationId: "verifyRazorpayCheckout",
    request: {
      body: z.object({
        orderId: z.string().min(1).max(40),
        razorpay_order_id: z.string().max(64),
        razorpay_payment_id: z.string().max(64),
        razorpay_signature: z.string().max(128),
      }).strict(),
    },
    responses: {
      200: { description: "captured", body: z.object({ status: z.literal("captured") }) },
      401: { description: "bad signature", body: z.object({ error: z.string() }) },
      409: { description: "not captured yet", body: z.object({ status: z.string() }) },
    },
  },
  async ({ body, state }) => {
    const valid = await state.razorpay.verifyCheckoutSignature({
      orderId: body.razorpay_order_id,
      paymentId: body.razorpay_payment_id,
      signature: body.razorpay_signature,
    });
    if (!valid) return { status: 401, body: { error: "signature mismatch" } };

    // Ownership: the Razorpay order must be the one we created for this user's order.
    const order = await orders.forCheckout(body.orderId, state.session.get<string>("userId"));
    const rzp = await db.orders.providerOrderFor(order.id, order.version);
    if (!rzp || rzp.id !== body.razorpay_order_id) throw new NotFoundError("Order not found.");

    const payment = await state.razorpay.fetchPayment(body.razorpay_payment_id);
    if (payment.order_id !== rzp.id || payment.status !== "captured") {
      return { status: 409, body: { status: payment.status } };
    }
    // UX confirmation only; the webhook worker marks the order paid.
    return { status: 200, body: { status: "captured" as const } };
  },
);

NotFoundError comes from @daloyjs/core. A 409 tells the client the payment exists but is not captured yet (for example authorized while auto-capture runs); the webhook settles it.

7. Webhook

Webhook verification
RazorpayDaloyJS routeJob worker
  1. 01requestRazorpayDaloyJS routePOST /webhooks/razorpayX-Razorpay-Signature over raw body
  2. 02noteDaloyJS routeDaloyJS routeverifyWebhookSignature with the webhook secretdifferent secret from the client callback
  3. 03responseDaloyJS routeRazorpay401 when the signature does not match{ error: 'bad signature' }
  4. 04asyncDaloyJS routeJob workerenqueue keyed by x-razorpay-event-id, then 200worker refetches and compares with the order
Verify X-Razorpay-Signature over the raw body with the webhook secret, dedupe atomically on x-razorpay-event-id, and ack every verified event. The worker refetches the payment before fulfilling.

This is the route shown in the shared webhook pattern, specialised to enqueue captured payments:

src/webhooks/razorpay.tsts
import { z } from "zod";
import { readBodyLimited, safeJsonParse, jobIdempotencyKey } from "@daloyjs/core";

app.post(
  "/webhooks/razorpay",
  {
    operationId: "razorpayWebhook",
    responses: {
      200: { description: "ok", body: z.object({ ok: z.literal(true) }) },
      400: { description: "malformed delivery", body: z.object({ error: z.string() }) },
      401: { description: "bad signature", body: z.object({ error: z.string() }) },
    },
  },
  async ({ request, state }) => {
    const raw = await readBodyLimited(request, 1_048_576);
    if (!(await state.razorpay.verifyWebhookSignature(raw, request.headers.get("x-razorpay-signature")))) {
      return { status: 401, body: { error: "bad signature" } };
    }
    const eventId = request.headers.get("x-razorpay-event-id");
    if (!eventId) return { status: 400, body: { error: "missing event id" } };

    const event = safeJsonParse(new TextDecoder().decode(raw)) as {
      event: string;
      payload: { payment?: { entity: { id: string } } };
    };
    const paymentId = event.payload.payment?.entity.id;
    if (event.event === "payment.captured" && paymentId) {
      await app.jobs!.enqueue({
        name: "razorpay.payment",
        payload: { eventId, paymentId },
        idempotencyKey: jobIdempotencyKey({ name: "razorpay.payment", key: eventId }),
      });
    }
    return { status: 200, body: { ok: true as const } };
  },
);
src/jobs/razorpay.tsts
import type { JobHandler } from "@daloyjs/core";
import { razorpayClient } from "../plugins/razorpay.ts";
import { orders } from "../orders.ts";

export const handleRazorpayPayment: JobHandler<{ paymentId: string }> = async ({ job }) => {
  const payment = await razorpayClient.fetchPayment(job.payload.paymentId);
  if (payment.status !== "captured" || !payment.order_id) return;
  const rzpOrder = await razorpayClient.fetchOrder(payment.order_id);
  if (!rzpOrder.receipt) return;
  await orders.markPaid(rzpOrder.receipt, {
    amountMinor: payment.amount,
    currency: payment.currency,
    providerRef: payment.id,
  });
};
// Register it in your single app.useJobs() call (see the payments overview).

Return 200 for every verified event, including ones you don't handle; Razorpay retries non-2xx responses.

8. Refunds

Expose refunds only through a protected refund route. The plugin call:

ts
await state.razorpay.refund({
  paymentId: order.providerRef!,
  amount: 10000, // 100.00 INR in paise, never more than captured minus refunded
  notes: { orderId: order.id, reason: "Item missing" },
});

Runtimes

The razorpay SDK is CommonJS and targets Node; it runs on Node hosts (long-lived Node, Vercel Node.js functions, AWS Lambda, Azure Functions). Deno, Cloudflare Workers, and Vercel Edge are not verified. There, call https://api.razorpay.com/v1 directly with fetch and Basic auth (key_id:key_secret); the core signature helpers used above already work on every runtime. See the runtime table.

Errors

Razorpay errors carry a structured error object with code, description, field, and reason. Log them, and map the failure to problem+json with your own type and title rather than forwarding Razorpay's description.

Modernisation notes

  • Use Orders, not bare payments. The Order gives you a server-side anchor for the amount, lets Checkout JS show the right total, and unlocks order.paid webhooks that fire even when the customer closes the tab before the callback.
  • Verify both signatures. The callback signature stops forged success posts from the browser; the webhook signature stops spoofed notifications.
  • Don't fulfil on the callback alone. Fulfil from the webhook worker after refetching the payment.
  • Use Promises. Every SDK method returns a Promise; the callback parameter exists for legacy code.

See also the payments overview, Tap Payments guide, PayTabs guide, and problem+json errors.

Edit this page on GitHub

Last updated