Razorpay Orders API + Checkout with signature verification and webhooks

Accept payments in India with Razorpay: create an Order on your server (amount in paise), open Checkout on web or Flutter, verify the payment signature HMAC-SHA256(order_id|payment_id), confirm with signed webhooks (X-Razorpay-Signature) and issue refunds.

Provider
Razorpay
Level
Intermediate
Stacks
Node.js (Express), Python (Django), Java (Spring), Flutter
Code maturity
Sandbox-ready
Last verified
25 Nov 2026

Introduction

Razorpay is one of India's largest payment gateways. Its recommended online flow is built on Orders: your server creates an order for a fixed amount, Razorpay Checkout collects the payment (cards, UPI, netbanking, wallets…), and your server verifies a signature before trusting the result.

In this guide you will:

  • create an order server-side (amounts in paise),
  • open Checkout from a web page and from a Flutter app,
  • verify razorpay_signature = HMAC-SHA256(order_id|razorpay_payment_id, key secret),
  • confirm with webhooks signed via X-Razorpay-Signature, deduplicated by x-razorpay-event-id,
  • check status, capture, and refund.

How the Orders flow works

  • Server → POST https://api.razorpay.com/v1/orders with amount (integer, smallest currency unit), currency, optional receipt (≤ 40 chars) and notes. Response: an order_id like order_... with status created.
  • Client opens Checkout with your public Key ID and the order_id.
  • On success, Checkout returns razorpay_payment_id, razorpay_order_id and razorpay_signature to your handler.
  • Server recomputes the signature using the order_id from your own database, and only then marks the order as paid (or waits for the webhook).

Order states: created → attempted → paid (an order stays paid even if refunded later). Payment states: created → authorized or failed → captured (and later refunded). Authorised payments must be captured to settle — configure automatic capture in the Dashboard (recommended).

Countries and availability

Razorpay onboards businesses registered in India and settles in INR. International card acceptance and other currencies require enabling international payments on your account. Razorpay also has regional offerings outside India; check their site for your country rather than assuming the same APIs and methods apply.

Payment methods

Standard Checkout can show cards, UPI (collect and intent/QR), netbanking, wallets, EMI and Pay Later, depending on what is enabled for your account. You don't code each method — Checkout renders the enabled ones. Methods like UPI and netbanking complete asynchronously more often, which is why webhooks matter.

When to use it

  • You sell to customers in India and need UPI + cards + netbanking in one integration.
  • You want a hosted, PCI-light checkout on web, Android, iOS or Flutter.
  • You need server-verifiable results (signatures) and webhooks for reconciliation.

When not to use it

  • Your business isn't registered in a country Razorpay onboards.
  • You only need recurring mandates — use Razorpay Subscriptions / recurring payments (separate APIs).
  • Marketplace split settlements → look at Razorpay Route (not covered here).

Example scenarios

  • Online course in INR: a learner pays ₹499 (amount: 49900); the handler verifies the signature and the order.paid webhook grants access if the browser closed.
  • Flutter grocery app: the app gets an order_id from your API, opens native Checkout, and sends the three returned values to your server for verification.
  • Failed first attempt: a UPI attempt fails, the customer retries with a card on the same order; your webhook sees payment.failed then payment.captured, and only the latter fulfils.

Registration

  • Sign up at dashboard.razorpay.com. Test mode is available immediately.
  • Complete KYC/activation (business details, PAN, bank account) for live mode.
  • In Account & Settings → API Keys, generate test keys; generate live keys after activation.
  • Set payment capture to automatic in the Dashboard's payment settings unless you deliberately capture manually.

Test mode

Test keys start with rzp_test_. Test payments open a mock bank page where you choose Success or Failure; no money moves. Webhooks can be configured separately for test mode in the Dashboard.

Credentials

  • Key ID (rzp_test_... / rzp_live_...) — public; passed to Checkout.
  • Key Secret — server only; authenticates API calls and is the HMAC key for payment signatures.
  • Webhook secret — a separate value you choose when creating the webhook; the HMAC key for X-Razorpay-Signature.

Security: The key secret must never ship in a web bundle or mobile app. Webhook secret ≠ key secret — mixing them up is a classic verification failure.

Environment configuration

Placeholders only:

.env.example

RAZORPAY_KEY_ID=rzp_test_replace_me
RAZORPAY_KEY_SECRET=replace_me
# Chosen by you when creating the webhook in the Dashboard (test and live differ)
RAZORPAY_WEBHOOK_SECRET=replace_me

Authentication

Razorpay's REST API uses HTTP Basic auth with Key ID as username and Key Secret as password. The official SDKs take both in their constructor.

curl — create an order (test mode)

curl -u "$RAZORPAY_KEY_ID:$RAZORPAY_KEY_SECRET" \
  -X POST https://api.razorpay.com/v1/orders \
  -H "Content-Type: application/json" \
  -d '{"amount": 49900, "currency": "INR", "receipt": "order_rcpt_123", "notes": {"orderId": "123"}}'

Backend: create the order

Create your own order row first (pending), compute the amount on the server, then create the Razorpay order and store its ID. Return only what Checkout needs: order_id, amount, currency and your public key ID.

orders.js — Express + razorpay (npm) · Node.js (Express)

import express from "express";
import Razorpay from "razorpay";

const razorpay = new Razorpay({
  key_id: process.env.RAZORPAY_KEY_ID,
  key_secret: process.env.RAZORPAY_KEY_SECRET,
});
export const router = express.Router();

router.post("/api/razorpay/orders", express.json(), async (req, res) => {
  const order = await db.orders.createPending({ userId: req.user.id, sku: req.body.sku });
  try {
    const rzpOrder = await razorpay.orders.create({
      amount: order.amountPaise, // integer paise: ₹499.00 -> 49900
      currency: "INR",
      receipt: `rcpt_${order.id}`.slice(0, 40),
      notes: { orderId: order.id },
    });
    await db.orders.update(order.id, { razorpayOrderId: rzpOrder.id });
    res.json({
      keyId: process.env.RAZORPAY_KEY_ID,
      orderId: rzpOrder.id,
      amount: rzpOrder.amount,
      currency: rzpOrder.currency,
    });
  } catch (e) {
    console.error("razorpay order failed", e?.statusCode, e?.error?.code);
    res.status(502).json({ error: "Could not create order" });
  }
});

views.py — Django + razorpay (pip) · Python (Django)

import json, os
import razorpay
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.views.decorators.http import require_POST
from .models import Order

client = razorpay.Client(auth=(os.environ["RAZORPAY_KEY_ID"], os.environ["RAZORPAY_KEY_SECRET"]))

@login_required
@require_POST
def create_order(request):
    sku = json.loads(request.body).get("sku", "")[:64]
    order = Order.create_pending(user=request.user, sku=sku)  # price from your DB
    rzp_order = client.order.create(data={
        "amount": order.amount_paise,
        "currency": "INR",
        "receipt": f"rcpt_{order.id}"[:40],
        "notes": {"orderId": str(order.id)},
    })
    order.razorpay_order_id = rzp_order["id"]
    order.save(update_fields=["razorpay_order_id"])
    return JsonResponse({
        "keyId": os.environ["RAZORPAY_KEY_ID"],
        "orderId": rzp_order["id"],
        "amount": rzp_order["amount"],
        "currency": rzp_order["currency"],
    })

RazorpayController.java — Spring + razorpay-java · Java (Spring)

import com.razorpay.Order;
import com.razorpay.RazorpayClient;
import com.razorpay.RazorpayException;
import org.json.JSONObject;

@RestController
public class RazorpayController {
  private final RazorpayClient client;
  private final String keyId;

  public RazorpayController(@Value("${RAZORPAY_KEY_ID}") String keyId,
                            @Value("${RAZORPAY_KEY_SECRET}") String keySecret) throws RazorpayException {
    this.keyId = keyId;
    this.client = new RazorpayClient(keyId, keySecret);
  }

  @PostMapping("/api/razorpay/orders")
  public Map<String, Object> create(@RequestBody Map<String, String> body) throws RazorpayException {
    AppOrder order = orders.createPending(body.get("sku")); // your repository
    JSONObject req = new JSONObject()
        .put("amount", order.getAmountPaise())
        .put("currency", "INR")
        .put("receipt", "rcpt_" + order.getId())
        .put("notes", new JSONObject().put("orderId", order.getId()));
    Order rzpOrder = client.orders.create(req);
    String rzpOrderId = rzpOrder.get("id");
    orders.saveRazorpayOrderId(order.getId(), rzpOrderId);
    return Map.of("keyId", keyId, "orderId", rzpOrderId,
                  "amount", order.getAmountPaise(), "currency", "INR");
  }
}

Warning: amount is in the smallest currency unit: paise for INR. Sending 499 charges ₹4.99, not ₹499.

Frontend: open Checkout (web and Flutter)

Web: load https://checkout.razorpay.com/v1/checkout.js, create new Razorpay(options) with key, amount, currency, name, order_id and a handler, then call rzp.open(). Razorpay recommends the handler for standard web integrations — callback_url bypasses it.

Flutter: the official razorpay_flutter plugin wraps the native Android/iOS SDKs. Register listeners for Razorpay.EVENT_PAYMENT_SUCCESS, EVENT_PAYMENT_ERROR and EVENT_EXTERNAL_WALLET, call open(options), and clear() in dispose(). PaymentSuccessResponse exposes paymentId, orderId and signature.

In both cases the client only forwards the three values to your server — it never decides that the order is paid.

public/pay.js — web Checkout (served by your Express app) · Node.js (Express)

// <script src="https://checkout.razorpay.com/v1/checkout.js"></script> must be on the page.
async function pay(sku) {
  const res = await fetch("/api/razorpay/orders", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ sku }),
  });
  if (!res.ok) return showError("Could not start payment");
  const { keyId, orderId, amount, currency } = await res.json();

  const rzp = new Razorpay({
    key: keyId,
    amount,
    currency,
    name: "Example Store",
    order_id: orderId,
    handler: async (response) => {
      // { razorpay_payment_id, razorpay_order_id, razorpay_signature }
      const verify = await fetch("/api/razorpay/verify", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(response),
      });
      verify.ok ? showSuccess() : showPending(); // webhook may still confirm it
    },
    modal: { ondismiss: () => showError("Payment cancelled") },
  });
  rzp.on("payment.failed", (r) => showError(r.error?.description || "Payment failed"));
  rzp.open();
}

checkout_page.dart — razorpay_flutter · Flutter

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:razorpay_flutter/razorpay_flutter.dart';

class CheckoutPage extends StatefulWidget {
  const CheckoutPage({super.key, required this.sku});
  final String sku;
  @override
  State<CheckoutPage> createState() => _CheckoutPageState();
}

class _CheckoutPageState extends State<CheckoutPage> {
  static const api = String.fromEnvironment('API_BASE'); // your backend, never Razorpay secrets
  late final Razorpay _razorpay;

  @override
  void initState() {
    super.initState();
    _razorpay = Razorpay();
    _razorpay.on(Razorpay.EVENT_PAYMENT_SUCCESS, _onSuccess);
    _razorpay.on(Razorpay.EVENT_PAYMENT_ERROR, _onError);
    _razorpay.on(Razorpay.EVENT_EXTERNAL_WALLET, (ExternalWalletResponse r) {});
  }

  @override
  void dispose() {
    _razorpay.clear();
    super.dispose();
  }

  Future<void> _pay() async {
    final res = await http.post(Uri.parse('$api/api/razorpay/orders'),
        headers: {'Content-Type': 'application/json'}, body: jsonEncode({'sku': widget.sku}));
    if (res.statusCode != 200) return _show('Could not start payment');
    final o = jsonDecode(res.body) as Map<String, dynamic>;
    _razorpay.open({
      'key': o['keyId'],
      'amount': o['amount'],
      'currency': o['currency'],
      'order_id': o['orderId'],
      'name': 'Example Store',
    });
  }

  Future<void> _onSuccess(PaymentSuccessResponse r) async {
    final res = await http.post(Uri.parse('$api/api/razorpay/verify'),
        headers: {'Content-Type': 'application/json'},
        body: jsonEncode({
          'razorpay_payment_id': r.paymentId,
          'razorpay_order_id': r.orderId,
          'razorpay_signature': r.signature,
        }));
    _show(res.statusCode == 200 ? 'Payment received' : 'Payment pending confirmation');
  }

  void _onError(PaymentFailureResponse r) => _show(r.message ?? 'Payment failed');

  void _show(String msg) =>
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(msg)));

  @override
  Widget build(BuildContext context) =>
      Scaffold(body: Center(child: FilledButton(onPressed: _pay, child: const Text('Pay'))));
}

Tip: Run flutter pub add razorpay_flutter http (the plugin was at 1.4.x on the check date). Android needs a minSdk supported by the plugin; see its README.

Initiating the payment

Initiation = create order on the server + open() on the client. Tips:

  • Reuse the same Razorpay order if the customer retries on the same cart; a single order can have several payment attempts (attempted), only one of which can make it paid.
  • prefill (name, email, contact) improves conversion but is optional; never put secrets in notes.
  • Payments created without an order_id cannot be captured and are refunded automatically — always use Orders.

Confirmation: verify the payment signature

The signature proves the payment_id belongs to your order and wasn't forged in the browser:

expected = HMAC_SHA256(key_secret, order_id + "|" + razorpay_payment_id) (hex), compared with razorpay_signature in constant time.

Use the order_id you stored when creating the order — not the one the client sends back. The official helpers: Node validatePaymentVerification({ order_id, payment_id }, signature, secret) from razorpay/dist/utils/razorpay-utils; Python client.utility.verify_payment_signature({...}) (raises SignatureVerificationError on mismatch); Java Utils.verifyPaymentSignature(JSONObject, secret).

A valid signature means the payment was authorised for this order. If auto-capture is on it will be captured shortly; mark the order paid idempotently, and let the webhook be the safety net.

verify.js — Express · Node.js (Express)

import express from "express";
import { validatePaymentVerification } from "razorpay/dist/utils/razorpay-utils.js";

export const verifyRouter = express.Router();

verifyRouter.post("/api/razorpay/verify", express.json(), async (req, res) => {
  const { razorpay_payment_id: paymentId, razorpay_order_id: clientOrderId, razorpay_signature: signature } = req.body || {};
  if (![paymentId, clientOrderId, signature].every((v) => typeof v === "string" && v.length < 100)) {
    return res.status(400).json({ error: "Bad request" });
  }
  const order = await db.orders.findByRazorpayOrderId(clientOrderId);
  if (!order || order.userId !== req.user.id) return res.sendStatus(404);

  const ok = validatePaymentVerification(
    { order_id: order.razorpayOrderId, payment_id: paymentId }, // order id from OUR DB
    signature,
    process.env.RAZORPAY_KEY_SECRET,
  );
  if (!ok) return res.status(400).json({ error: "Signature mismatch" });

  await markPaidOnce(order.id, paymentId); // UPDATE ... WHERE status <> 'paid'; delivers once
  res.json({ ok: true });
});

views.py — verify (Django) · Python (Django)

from razorpay.errors import SignatureVerificationError

@login_required
@require_POST
def verify_payment(request):
    data = json.loads(request.body)
    order = Order.objects.filter(
        razorpay_order_id=data.get("razorpay_order_id", ""), user=request.user
    ).first()
    if not order:
        return JsonResponse({"error": "not found"}, status=404)
    try:
        client.utility.verify_payment_signature({
            "razorpay_order_id": order.razorpay_order_id,  # from our DB
            "razorpay_payment_id": data.get("razorpay_payment_id", ""),
            "razorpay_signature": data.get("razorpay_signature", ""),
        })
    except SignatureVerificationError:
        return JsonResponse({"error": "signature mismatch"}, status=400)
    order.mark_paid_once(payment_id=data["razorpay_payment_id"])  # idempotent
    return JsonResponse({"ok": True})

Verify endpoint — Spring · Java (Spring)

@PostMapping("/api/razorpay/verify")
public ResponseEntity<?> verify(@RequestBody Map<String, String> body,
                                @Value("${RAZORPAY_KEY_SECRET}") String keySecret) throws RazorpayException {
  AppOrder order = orders.findByRazorpayOrderId(body.get("razorpay_order_id"))
      .orElse(null);
  if (order == null) return ResponseEntity.notFound().build();
  JSONObject attrs = new JSONObject()
      .put("razorpay_order_id", order.getRazorpayOrderId()) // from our DB
      .put("razorpay_payment_id", body.get("razorpay_payment_id"))
      .put("razorpay_signature", body.get("razorpay_signature"));
  if (!Utils.verifyPaymentSignature(attrs, keySecret)) {
    return ResponseEntity.badRequest().body(Map.of("error", "Signature mismatch"));
  }
  orders.markPaidOnce(order.getId(), body.get("razorpay_payment_id"));
  return ResponseEntity.ok(Map.of("ok", true));
}

Webhooks

Create a webhook in the Dashboard (separately for test and live) with your HTTPS URL and a secret, and subscribe to the events you use — typically payment.captured, payment.failed, order.paid, and refund.processed / refund.failed.

  • Signature: X-Razorpay-Signature = HMAC-SHA256 (hex) of the raw request body with the webhook secret. Don't parse and re-serialise first — Razorpay's own Node example uses JSON.stringify(body), which can differ from the raw bytes.
  • Idempotency: each delivery has an x-razorpay-event-id header, unique per event. Store processed IDs and skip duplicates.
  • If you rotate the secret, retries of older events are still signed with the old secret — accept both for a while.

Helpers: Node validateWebhookSignature(body, signature, secret); Python client.utility.verify_webhook_signature(body, signature, secret) — it expects a str body, so decode request.body; Java Utils.verifyWebhookSignature(payload, signature, secret).

webhook.js — Express (raw body) · Node.js (Express)

import express from "express";
import { validateWebhookSignature } from "razorpay/dist/utils/razorpay-utils.js";

export const webhookRouter = express.Router();

webhookRouter.post("/webhooks/razorpay", express.raw({ type: "application/json" }), async (req, res) => {
  const raw = req.body.toString("utf8");
  const signature = req.get("x-razorpay-signature") || "";
  let valid = false;
  try {
    valid = validateWebhookSignature(raw, signature, process.env.RAZORPAY_WEBHOOK_SECRET);
  } catch {
    valid = false;
  }
  if (!valid) return res.sendStatus(400);

  const eventId = req.get("x-razorpay-event-id");
  if (eventId && !(await db.webhookEvents.tryInsert(`rzp:${eventId}`))) return res.sendStatus(200);

  const event = JSON.parse(raw);
  const payment = event.payload?.payment?.entity;
  try {
    if (event.event === "payment.captured" || event.event === "order.paid") {
      const order = await db.orders.findByRazorpayOrderId(payment?.order_id ?? event.payload?.order?.entity?.id);
      if (order && payment && payment.amount === order.amountPaise && payment.currency === "INR") {
        await markPaidOnce(order.id, payment.id);
      }
    } else if (event.event === "payment.failed") {
      await db.paymentAttempts.recordFailure(payment?.order_id, payment?.id, payment?.error_code);
    } else if (event.event.startsWith("refund.")) {
      const refund = event.payload?.refund?.entity;
      if (refund) await db.refunds.updateByRazorpayId(refund.id, { status: refund.status });
    }
    res.sendStatus(200);
  } catch (e) {
    if (eventId) await db.webhookEvents.delete(`rzp:${eventId}`); // allow retry
    res.sendStatus(500);
  }
});
// Mount BEFORE app.use(express.json()) so the body stays raw for this route.

webhooks.py — Django (csrf_exempt, raw body) · Python (Django)

import json, os
from django.db import IntegrityError, transaction
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from razorpay.errors import SignatureVerificationError
from .models import Order, ProcessedEvent

@csrf_exempt
@require_POST
def razorpay_webhook(request):
    body = request.body.decode("utf-8")  # the SDK helper expects str, not bytes
    signature = request.headers.get("X-Razorpay-Signature", "")
    try:
        client.utility.verify_webhook_signature(body, signature, os.environ["RAZORPAY_WEBHOOK_SECRET"])
    except SignatureVerificationError:
        return HttpResponse(status=400)

    event_id = request.headers.get("X-Razorpay-Event-Id", "")
    try:
        with transaction.atomic():
            ProcessedEvent.objects.create(key=f"rzp:{event_id}")  # unique field
            event = json.loads(body)
            payment = event.get("payload", {}).get("payment", {}).get("entity", {})
            if event["event"] in ("payment.captured", "order.paid"):
                order = Order.objects.select_for_update().filter(
                    razorpay_order_id=payment.get("order_id")).first()
                if order and payment.get("amount") == order.amount_paise:
                    order.mark_paid_once(payment_id=payment["id"])
    except IntegrityError:
        pass  # duplicate delivery — already processed
    return HttpResponse(status=200)

RazorpayWebhookController.java — Spring (@RequestBody String) · Java (Spring)

@RestController
public class RazorpayWebhookController {
  @Value("${RAZORPAY_WEBHOOK_SECRET}") String webhookSecret;

  @PostMapping("/webhooks/razorpay")
  public ResponseEntity<Void> handle(@RequestBody String payload,
      @RequestHeader("X-Razorpay-Signature") String signature,
      @RequestHeader(value = "X-Razorpay-Event-Id", required = false) String eventId) throws RazorpayException {
    if (!Utils.verifyWebhookSignature(payload, signature, webhookSecret)) {
      return ResponseEntity.badRequest().build();
    }
    if (eventId != null && !processedEvents.tryInsert("rzp:" + eventId)) {
      return ResponseEntity.ok().build();
    }
    JSONObject event = new JSONObject(payload);
    String type = event.getString("event");
    if (type.equals("payment.captured") || type.equals("order.paid")) {
      JSONObject p = event.getJSONObject("payload").getJSONObject("payment").getJSONObject("entity");
      orders.markPaidIfAmountMatches(p.getString("order_id"), p.getString("id"), p.getLong("amount"));
    }
    return ResponseEntity.ok().build();
  }
}

Security: Return 2xx only after the event is safely recorded (or queued). Do heavy work asynchronously so the webhook doesn't time out and get retried.

Checking status and capturing

When the client result and the webhook disagree — or neither arrived — ask the API:

  • GET /v1/orders/{order_id} → status (created, attempted, paid).
  • GET /v1/orders/{order_id}/payments → every payment attempt on the order.
  • GET /v1/payments/{payment_id} → payment status (created, authorized, captured, refunded, failed).

If you use manual capture, call POST /v1/payments/{id}/capture with the amount and currency once you've verified the order. Uncaptured authorised payments are auto-refunded after a fixed period, so don't leave them hanging.

Reconcile an order (cron or support tool) · Node.js (Express)

export async function reconcile(order) {
  const { items } = await razorpay.orders.fetchPayments(order.razorpayOrderId);
  const captured = items.find((p) => p.status === "captured" && p.amount === order.amountPaise);
  if (captured) return markPaidOnce(order.id, captured.id);
  const authorized = items.find((p) => p.status === "authorized");
  if (authorized && order.manualCapture) {
    await razorpay.payments.capture(authorized.id, order.amountPaise, "INR");
  }
}

Refunds

POST /v1/payments/{payment_id}/refund with optional amount (paise; omit for a full refund), speed: "normal", notes (up to 15 key-value pairs) and receipt (your unique reference). Refund statuses: pending, processed (final) and failed. Track the outcome via refund.* webhooks or by fetching the refund.

Refund (staff only, idempotent by receipt) · Node.js (Express)

router.post("/admin/orders/:id/refund", requireStaff, express.json(), async (req, res) => {
  const order = await db.orders.get(req.params.id);
  if (!order?.razorpayPaymentId) return res.status(409).json({ error: "Nothing to refund" });
  const amount = req.body.amountPaise == null ? undefined : Number.parseInt(req.body.amountPaise, 10);
  if (amount !== undefined && (!Number.isInteger(amount) || amount <= 0 || amount > order.amountPaise)) {
    return res.status(400).json({ error: "Invalid amount" });
  }
  const row = await db.refunds.createOnce({ orderId: order.id, amount, requestKey: req.body.requestKey });
  if (row.razorpayRefundId) return res.json({ status: row.status }); // repeated click

  const refund = await razorpay.payments.refund(order.razorpayPaymentId, {
    amount,
    speed: "normal",
    receipt: `refund_${row.id}`,
    notes: { orderId: String(order.id) },
  });
  await db.refunds.update(row.id, { razorpayRefundId: refund.id, status: refund.status });
  res.json({ status: refund.status });
});

Error handling

API errors return JSON { "error": { "code", "description", "source", "step", "reason", "field" } } with HTTP 4xx/5xx. Typical cases:

  • BAD_REQUEST_ERROR — invalid amount/currency, an ID that doesn't exist (often test vs live keys), or an order already paid.
  • 401 — wrong key pair.
  • Checkout payment.failed — the customer can retry on the same order; log error.code / error.reason for analytics, but don't fail the order permanently.
  • Network errors on create — retry; at worst you create an extra unpaid order, which is harmless if your DB links only one to the cart.

Going to production

  • Complete activation, generate live keys, and create a live webhook with its own secret.
  • Confirm automatic capture settings and any international/payment-method enablement you need.
  • Serve Checkout pages over HTTPS and allow checkout.razorpay.com (and Razorpay's API domains) in your Content-Security-Policy.
  • Add a reconciliation job for orders stuck in attempted and payments stuck in authorized.

Security checklist

  • Key secret and webhook secret in server env vars only; different secrets per environment.
  • Amount computed server-side; signature verified with the stored order_id.
  • Constant-time comparisons (the official helpers use crypto.timingSafeEqual / hmac.compare_digest).
  • Webhook signature over the raw body; dedupe on x-razorpay-event-id; check amount and currency before fulfilling.
  • CSRF exemption only on the webhook route.
  • Refunds behind staff auth and audit logs.

Testing

With rzp_test_ keys, Checkout shows a mock bank page where you pick Success or Failure. Published domestic test cards include:

  • Visa debit 4100 2800 0000 1007, Mastercard 5555 5100 0008 1006 — success flows.
  • Visa 4100 2800 0001 0008 — card-number error; Mastercard 5305 6200 0005 0001 — insufficient balance.

Use any future expiry and any CVV unless the test-card page says otherwise. To test webhooks locally, expose your server with a tunnel (e.g. ngrok) and register the tunnel URL as a test-mode webhook.

Tip: Unit-test your verification code with a known vector: compute HMAC-SHA256(secret, "order_X|pay_Y") yourself and assert the helper accepts it and rejects a one-character change.

Warning: Test UPI IDs commonly quoted in blog posts were not found on the official test-card page on 2026-11-25; use the mock bank page or the current docs for UPI testing.

Common mistakes

  • Rupees instead of paise in amount.
  • Verifying with the order_id sent by the client instead of the one in your DB.
  • Using the key secret for webhooks (or the webhook secret for payment signatures).
  • Verifying JSON.stringify(req.body) instead of the raw body; or Express json() parsing the webhook route first.
  • Passing bytes to the Python webhook helper (it expects str).
  • Leaving payments in authorized because capture is manual and nobody captures them → auto-refunds.
  • Using callback_url and expecting the handler to run.
  • Treating payment.failed as order failure although the customer can retry on the same order.
  • Shipping the key secret in the Flutter app.

Troubleshooting

  • Signature mismatch on verify — wrong secret (test vs live), order ID taken from the wrong record, or whitespace in env vars.
  • Webhook signature fails — body modified by middleware, webhook secret confused with key secret, or the event was signed with a secret you've since rotated.
  • Checkout opens then errors "order id is invalid" — the order was created with different keys from the key passed to Checkout.
  • No webhooks in test — the webhook was created in live mode only (they're separate), the URL isn't public HTTPS, or the event isn't subscribed.
  • Flutter build issues — check the plugin README for minimum Android/iOS versions and ProGuard rules.

Further reading

Official documentation

Checked on 2026-11-25. SDK helper names were confirmed in the official SDK sources; re-check the docs before going live:

Official documentation

Sources

More payment guides