Skip to main content

Commerce

How to Build a Razorpay Payment Provider for Medusa v2 (UPI, Cards, Netbanking)

Medusa v2 has no official Razorpay plugin. Build your own payment provider for UPI, cards and netbanking, with webhooks that don't drop orders.

Updated 12 Oct 202611 min readBy ManojFirst published 4 Aug 2026

You have picked Medusa v2 for an Indian store and searched the plugin registry for Razorpay. There is nothing official. The v1 plugin was never ported (GitHub #9881), and the community packages on npm (@sgftech/payment-razorpay, @devx-commerce/razorpay, medusa-plugin-razorpay-v2) have thin documentation. This guide builds your own Razorpay payment provider on Medusa v2's AbstractPaymentProvider for UPI, cards and netbanking, gets webhook signatures right, and includes a flow debugger so you can see where each method breaks.

The v1 Razorpay plugin broke on upgrade because Medusa v2 replaced the plugin loader with a module system. PaymentProcessor became AbstractPaymentProvider, and the checkout workflow was rewritten. If you are porting a v1 integration, little carries over except the Razorpay API calls. I lead commerce and ERP work at MithTech, a team of Frappe specialists in Bengaluru, and wiring Indian payment rails into Medusa stores is part of that work.

Why is there no official Razorpay plugin?

Medusa v2 shipped in late 2024 with a rewritten module system. In v1, payment plugins implemented PaymentProcessor and loaded from medusa-config.js; in v2, providers extend AbstractPaymentProvider and register through medusa-config.ts.

The original community plugin (SGFGOV/medusa-payment-razorpay) was built for v1. After an upgrade to v2 it stopped loading, with Unable to find the plugin 'medusa-payment-razorpay' (GitHub #9881). The maintainer has since published a v2 package (@sgftech/payment-razorpay), and other community packages exist (@devx-commerce/razorpay, @tsc_tech/medusa-plugin-razorpay-payment, medusa-plugin-razorpay-v2), but none is backed by the Medusa team.

That matters because Medusa's payment flow has specific rules for sessions, webhooks and completeCartWorkflow, and community plugins handle them unevenly. Building your own module gives you control over the parts that break, above all webhook signature verification.

How does the payment flow work, step by step?

Every Razorpay payment through Medusa follows the same sequence, whatever the method. UPI (approval in the customer's app), cards (3-D Secure) and netbanking (bank redirect) differ on the Razorpay side; the Medusa side is the same.

Interactive

Payment Flow Debugger

Select a payment method and click through each step to see the exact API calls between your storefront, Medusa backend, and Razorpay — with the known failure points flagged.

The key point is that UPI and netbanking are asynchronous: the customer approves in another app or on the bank's page, and the result comes back by webhook. Async methods trip up Medusa flows that assume a card-style authorisation in the same request (GitHub #13837 shows the same problem with SEPA on Stripe), which is why your webhook handling has to be right.

The webhook signature problem

This is the most common failure in Razorpay integrations on Medusa v2, and it fails silently: your webhook returns 401, Razorpay retries for a while and stops, and the customer has paid but their cart never becomes an order.

The cause: Razorpay's webhook signature is an HMAC over the raw request body. Medusa's API routes parse the body as JSON before your handler runs (GitHub #9541). Re-serialising the parsed body can change the bytes, and then the HMAC no longer matches.

There are two clean fixes:

  1. Use Medusa's built-in payment webhook route. Medusa serves /hooks/payment/[identifier]_[id] out of the box (for a provider with identifier razorpay registered with id razorpay, that is /hooks/payment/razorpay_razorpay). It passes the raw body to your provider's getWebhookActionAndData as rawData, and when you return an authorised or captured action, Medusa updates the payment session and completes the cart (Medusa: payment webhook events).
  2. Keep a custom route, but preserve the raw body. Turn on preserveRawBody for that route and verify against req.rawBody (Medusa: configure the body parser):
TypeScript
// src/api/middlewares.ts
import { defineMiddlewares } from "@medusajs/framework/http"

export default defineMiddlewares({
  routes: [
    {
      method: ["POST"],
      matcher: "/hooks/razorpay",
      bodyParser: { preserveRawBody: true },
    },
  ],
})

// in src/api/hooks/razorpay/route.ts
// validateWebhookSignature(String(req.rawBody), signature, webhookSecret)

The recipe further down verifies against JSON.stringify(req.body). That passes only while re-serialising produces exactly the bytes Razorpay signed, so treat it as a quick test, not the production setup.

Double-capture risk

If both the webhook and the storefront's success callback try to capture, you can capture twice (GitHub #13301 is the Stripe version of the same pattern). Make capturePayment idempotent: check the Razorpay payment's status first, and if it is already captured, return the existing payment instead of calling capture again.

How do you validate your configuration?

Before writing code, check your Razorpay credentials and module configuration. The usual setup errors are a missing or wrong key_id (GitHub #1841), a missing webhook secret, and sending amounts in rupees instead of paise.

Calculator

Razorpay Config Validator

Enter your Razorpay credentials (nothing is sent anywhere — validation runs entirely in your browser) to check for the five most common configuration errors.

Which payment methods should you enable?

UPI is the method many Indian shoppers reach for first; cards come next; netbanking is the usual route for high-value B2B orders; wallets still matter for some customers. The right mix depends on your business model:

Interactive

Payment Method Decider

Select your business model to get a recommended payment method mix, Razorpay configuration, and the edge cases to watch for.

Select your business model:

UPI-specific considerations

Most merchant UPI payments are capped at ₹1 lakh a transaction. NPCI allows more for some verified-merchant categories, and banks can set their own lower limits, so check NPCI's current circulars for your category. Check the cart total before opening the UPI flow; otherwise the customer goes through approval on their phone only to be rejected by their bank.

Razorpay Checkout handles the QR code and UPI ID entry. Pre-fill prefill.contact with the customer's phone number from the shipping address so they type less.

RBI tokenisation rules

Since 1 October 2022, RBI's card-on-file tokenisation rules bar merchants and payment aggregators from storing card numbers. Razorpay stores a token when a customer saves a card, and you charge against that token. With Razorpay Checkout this is handled for you; with a custom card form you must use Razorpay's tokenisation API. Storing raw card numbers is a compliance breach.

How do you build the payment provider module?

The recipe below covers four files: the provider service, a webhook handler, the storefront checkout component and the registration in medusa-config.ts.

Code recipe

Razorpay Code Recipe

Four-tab code recipe — payment provider module, webhook handler with signature verification, Next.js storefront checkout button, and medusa-config.ts registration.

// src/modules/razorpay/service.ts
import {
  AbstractPaymentProvider,
  PaymentProviderError,
  PaymentSessionStatus,
} from "@medusajs/framework/utils"
import Razorpay from "razorpay"

type RazorpayOptions = {
  key_id: string
  key_secret: string
  webhook_secret: string
}

class RazorpayPaymentProvider extends AbstractPaymentProvider<
  RazorpayOptions
> {
  static identifier = "razorpay"
  protected client_: InstanceType<typeof Razorpay>
  protected options_: RazorpayOptions

  constructor(container: Record<string, unknown>, options: RazorpayOptions) {
    super(container, options)
    this.options_ = options
    this.client_ = new Razorpay({
      key_id: options.key_id,
      key_secret: options.key_secret,
    })
  }

  async initiatePayment(input: {
    amount: number
    currency_code: string
    context: Record<string, unknown>
  }) {
    const order = await this.client_.orders.create({
      amount: input.amount, // already in paise
      currency: input.currency_code.toUpperCase(),
      receipt: input.context.cart_id as string,
    })

    return {
      id: order.id,        // razorpay_order_id
      data: { order_id: order.id },
    }
  }

  async getPaymentStatus(
    paymentSessionData: Record<string, unknown>
  ): Promise<PaymentSessionStatus> {
    const orderId = paymentSessionData.order_id as string
    const order = await this.client_.orders.fetch(orderId)

    switch (order.status) {
      case "paid":
        return PaymentSessionStatus.AUTHORIZED
      case "attempted":
        return PaymentSessionStatus.PENDING
      default:
        return PaymentSessionStatus.PENDING
    }
  }

  // ... capturePayment, refundPayment, cancelPayment
}

export default RazorpayPaymentProvider

0 of 6 steps done

Tick a step’s number when it is done; the ticks stay on this device.

Scaffold the module directory

Create src/modules/razorpay/ with service.ts and index.ts. The service extends AbstractPaymentProvider from @medusajs/framework/utils. Install the Razorpay Node SDK: npm install razorpay.

Implement the provider methods

initiatePayment creates a Razorpay order and returns its order_id in the session data. authorizePayment and getPaymentStatus fetch the order and map Razorpay's created, attempted and paid states to Medusa's PaymentSessionStatus. capturePayment calls POST /v1/payments/:id/capture; refundPayment calls POST /v1/payments/:id/refund. cancelPayment usually has nothing to call, because an unpaid Razorpay order is simply left unpaid. getWebhookActionAndData turns a Razorpay event into Medusa's action. The provider reference lists the rest (retrievePayment, updatePayment, deletePayment).

Register in medusa-config.ts

Add the provider to the Payment Module with key_id, key_secret and webhook_secret from environment variables. Never hard-code credentials.

Handle the webhook

Point Razorpay's webhook at /hooks/payment/razorpay_razorpay and handle payment.authorized, payment.captured and payment.failed in getWebhookActionAndData. If you use a custom route instead, enable preserveRawBody, verify against req.rawBody, resolve the payment session by order_id, and complete the cart.

Wire the storefront

Load Razorpay Checkout.js with a <Script> tag. At checkout, create a payment session through the Medusa Store API, then open the Razorpay modal with the session's order_id. The handler callback fires on success; use it to complete the cart, with the webhook as the backstop.

Test with Razorpay test credentials

Use success@razorpay as the UPI ID for a successful UPI payment, and Razorpay's test card 4111 1111 1111 1111 with any future expiry and any CVV. Check that the webhook fires, the payment session moves to authorized, and the cart becomes an order.

What to know before you commit

Switching gateways later. Moving to Cashfree, PayU or Juspay means a new provider module. The Medusa interface stays the same; the API calls, webhook formats and error codes change.

Settlement. Razorpay's standard settlement for domestic payments is T+2 working days from capture (Razorpay settlements, checked 12 October 2026). Faster settlement is available on request. Plan cash flow around it.

Refunds. Refunds reach the customer after several working days, and the time differs by method; Razorpay's refund docs give the current timelines. Medusa records the refund at once, so your order workflow needs a refund-pending state the customer can see.

Gateway fees and GST. Razorpay's standard rate is a 2% platform fee per successful transaction on cards, UPI, netbanking and wallets, with 18% GST on the fee (razorpay.com/pricing, checked 12 October 2026). UPI and RuPay debit carry no MDR, but the platform fee still applies; a lower rate is negotiated. Your reconciliation must carry the GST on gateway fees.

PCI-DSS. With Razorpay Checkout (the hosted modal), card data never touches your server, which keeps your PCI scope small. A custom card form using Razorpay.js puts the payment page in your scope. Most Indian D2C stores should use the hosted checkout.

PCI-DSS scopeSmallest — Razorpay hosts the card fieldsLarger — your page hosts the form
UPI supportBuilt-in QR and UPI ID flowYou build the UPI intent flow
CustomisationLimited — modal styling onlyFull control over the UI
Build effortLess — script, session, modalMore — form, validation, tokens, testing
SuitsMost D2C and SMB storesStores with specific UX requirements

Razorpay Checkout (hosted modal) vs custom card form for Medusa v2 stores

At a glance

What to know
InterfaceAbstractPaymentProvider from @medusajs/framework/utils
WebhookMedusa's /hooks/payment/[identifier]_[id] route, or a custom route with preserveRawBody
AmountsRazorpay takes paise
CaptureCheck status before capturing, so webhook and callback can't capture twice
SettlementT+2 working days by default (Razorpay, checked 12 October 2026)
Testingsuccess@razorpay for UPI; Razorpay test cards

Common questions about Razorpay on Medusa

How do I add Razorpay to Medusa v2?

Create a payment provider module that extends AbstractPaymentProvider from @medusajs/framework/utils. Implement initiatePayment (creates a Razorpay order), authorizePayment and getPaymentStatus (map the order's state), capturePayment, refundPayment and getWebhookActionAndData. Register the provider in medusa-config.ts. There is no official Razorpay plugin for v2.

Why does Razorpay webhook signature verification fail in Medusa v2?

Razorpay signs the raw request body, and Medusa's API routes parse it as JSON before your handler runs (GitHub #9541). Re-serialising can change the bytes, so the HMAC fails. Use Medusa's built-in /hooks/payment/[identifier]_[id] route, which passes the raw body to your provider, or set bodyParser: { preserveRawBody: true } on your custom route and verify against req.rawBody.

What payment methods should I enable for an Indian Medusa store?

UPI, cards (Visa, Mastercard, RuPay) and netbanking at minimum. Make UPI prominent in checkout. For B2B, netbanking handles amounts above UPI limits. Wallets still matter for some customers. The Payment Method Decider above suggests a mix by business model.

Can I use the old v1 Razorpay plugin with Medusa v2?

No. The v1 plugin (medusa-payment-razorpay) uses the PaymentProcessor interface, which v2 removed; loading it gives Unable to find the plugin (GitHub #9881). Use a community v2 package (@sgftech/payment-razorpay, @devx-commerce/razorpay) or a custom module as described here.

What is the UPI transaction limit for Razorpay payments?

Most merchant UPI payments are capped at ₹1 lakh a transaction. NPCI allows more for some verified-merchant categories, and banks can set lower limits, so check NPCI's current circulars for your category. Check the cart total before opening the UPI flow, and offer netbanking or a payment link for larger amounts.

Does Razorpay charge fees on UPI transactions?

UPI carries no MDR, but Razorpay charges a platform fee. On its standard pricing that fee is 2% per successful transaction on UPI as on cards and netbanking, plus 18% GST on the fee (razorpay.com/pricing, checked 12 October 2026). Lower UPI rates are negotiated; check your own agreement.

How do I handle refunds in a Medusa and Razorpay setup?

Call POST /v1/payments/:id/refund with the amount in paise and a speed of normal or optimum. Medusa marks the refund as processed at once, but the customer sees the money days later, and the time differs by method. Track the real status through the refund.processed webhook event.

What version of Medusa does this guide apply to?

It was written against Medusa 2.18 (released July 2026); on 12 October 2026 the latest release on npm is 2.21.2. AbstractPaymentProvider has kept the same module structure and registration across v2. Recheck webhook handling if Medusa changes how API routes parse bodies.

Razorpay's rails work; the hard part is wiring them through Medusa's module system without the silent failures that lose orders. If your test webhook returns 200 and your cart becomes an order, production is the same code with live keys and a verified domain.

Live demo

Your next step

Building an Indian store on Medusa?

Sales and orders

An online order, start to finish

5 screens · about 8 min · you end with a payment recorded

See it live

Sales OrderTo deliver and bill

The customer's confirmed order: who it's for, the items at their price list and when it's due.

Customer
A demo customer
Prices
From their price list

Mith Demo Traders · demo company

Commerce

Now see what a store you own would look like

How we build and run Medusa storefronts and B2B portals connected to ERPNext, and when staying on a hosted platform is the better call.

Comments & ratings

No comments yet. Start a new discussion.

0

Manoj · Published on 4 August 2026

Worked with us? Leave a Google review

Questions about this? Talk to the team.

Book a 30-minute Google Meet, WhatsApp us, or send a message. The engineer who works on this replies.

Send us a message

Your details go to our team's CRM and are used only to reply.