tutorial··5 min read·WoWSQL Team

Verify Razorpay Webhooks and Store Payments in Postgres

Verify Razorpay webhook signatures with HMAC-SHA256 on the raw body, dedupe retries by event ID, and mark orders paid in Postgres. Tested Node.js code.

To verify a Razorpay webhook, compute an HMAC-SHA256 of the raw request body with your webhook secret and compare it, in constant time, with the X-Razorpay-Signature header; then record the event once by its x-razorpay-event-id and mark the matching order paid. WoWSQL gives you the Postgres database for the orders table and a Compute Function that receives the raw body, so the whole flow lives in one project. This guide shows the SQL, the function, a plain Node.js version for any host, and the edge cases (retries, duplicate events, out-of-order delivery, amount mismatches) that break naive handlers.

How we tested: on 2 December 2026 we ran every snippet below on Node.js 24 against PostgreSQL 17.12 with PostgREST (the same REST layer WoWSQL uses) and a local stand-in for the WoWSQL gateway. Our signature check returned the same result as validateWebhookSignature from Razorpay's own Node SDK (razorpay 2.9.8). We replayed payloads shaped like Razorpay's published payment.captured sample. We did not call Razorpay's live API or a live WoWSQL project, so run a Test mode payment end to end before you go live.

Key facts

  • Signature: Razorpay sends X-Razorpay-Signature, an HMAC-SHA256 hex digest of the raw webhook body keyed with your webhook secret. Razorpay's docs say not to parse or cast the body before verifying (Razorpay: validate webhooks, checked 2 Dec 2026).
  • Retries and duplicates: any non-2xx response, or no response within 5 seconds, counts as a failure. Razorpay retries with exponential backoff for 24 hours, then disables the webhook. Delivery is at-least-once, so dedupe on x-razorpay-event-id (Razorpay: best practices, checked 2 Dec 2026).
  • Order of events is not guaranteed: payment.authorized and payment.captured can arrive out of order (Razorpay, checked 2 Dec 2026).
  • WoWSQL Compute Functions: one Node.js or Python file per function at https://<project>.wowsqlconnect.com/functions/v1/<name>, with event.rawBody for signature checks and a per-function Verify JWT / API key switch you turn off for webhooks (Compute docs).
  • Plans: the pricing page lists Edge Functions (the same product as Compute) on Pro ($25/month) and Scale ($99/month). If your plan doesn't include them, the same handler runs on any Node.js server (Step 4).
  • Regions: Mumbai (ap-south-1), US East (us-east-1) and Frankfurt (eu-central-1). A function runs in its project's region.

How the flow fits together

1. Browser ──"buy pro_month"──> create-order function ──> Razorpay Orders API (amount in paise)
                                       └──> orders row (status 'created', razorpay_order_id)
2. Browser opens Razorpay Checkout with that order_id, the customer pays
3. Razorpay ──POST webhook (raw JSON + X-Razorpay-Signature + x-razorpay-event-id)──> payment-webhook function
                                       └──> record_razorpay_event(): dedupe, check amount, mark order 'paid'
4. Your app reads the order through RLS and unlocks the purchase

Two rules drive the design:

  • The webhook is the source of truth, not the browser. Checkout's success handler tells the customer's browser that a payment worked, but the browser can close, lose network or be tampered with. Razorpay's own docs describe webhooks as the server-side check and the Checkout callback as something you verify separately (Razorpay webhooks overview, checked 2 Dec 2026).
  • The database decides. One SQL function does the dedupe, the amount check and the status change in a single transaction, so a retry that arrives while the first delivery is still running can't double-process anything.

Step 1: Create the tables and the settle function

Create a project at app.wowsql.com/signup (Mumbai is the natural region for Razorpay merchants), then run this in the SQL editor:

-- Orders: users can read their own; only your server creates and settles them
create table public.orders (
  id                  uuid primary key default gen_random_uuid(),
  user_id             uuid not null,
  razorpay_order_id   text unique,
  amount_paise        bigint not null check (amount_paise > 0),
  currency            text not null default 'INR',
  status              text not null default 'created'
                      check (status in ('created', 'paid', 'failed')),
  razorpay_payment_id text,
  paid_at             timestamptz,
  created_at          timestamptz not null default now()
);
alter table public.orders enable row level security;
create policy "users read own orders" on public.orders
  for select using (user_id = auth.uid());
grant select on public.orders to authenticated;

-- Every webhook delivery, keyed by Razorpay's x-razorpay-event-id (dedupe + audit trail)
create table public.razorpay_events (
  event_id            text primary key,
  event               text not null,
  razorpay_order_id   text,
  razorpay_payment_id text,
  outcome             text,
  payload             jsonb not null,
  received_at         timestamptz not null default now()
);
alter table public.razorpay_events enable row level security; -- no policies: invisible to app users

-- One atomic step: record the event once, then settle the order
create or replace function public.record_razorpay_event(p_event_id text, p_payload jsonb)
returns text language plpgsql security definer set search_path = public as $$
declare
  v_event   text  := p_payload->>'event';
  v_payment jsonb := p_payload #> '{payload,payment,entity}';
  v_rzp_order text := coalesce(v_payment->>'order_id', p_payload #>> '{payload,order,entity,id}');
  v_order   public.orders;
  v_outcome text;
begin
  insert into public.razorpay_events (event_id, event, razorpay_order_id, razorpay_payment_id, payload)
  values (p_event_id, v_event, v_rzp_order, v_payment->>'id', p_payload)
  on conflict (event_id) do nothing;
  if not found then
    return 'duplicate';                       -- Razorpay retried an event we already handled
  end if;

  select * into v_order from public.orders where razorpay_order_id = v_rzp_order for update;
  if not found then
    v_outcome := 'unknown_order';
  elsif v_event in ('payment.captured', 'order.paid') then
    if (v_payment->>'amount')::bigint <> v_order.amount_paise
       or v_payment->>'currency' <> v_order.currency then
      v_outcome := 'amount_mismatch';         -- never mark paid; review by hand
    elsif v_order.status = 'paid' then
      v_outcome := 'already_paid';            -- order.paid and payment.captured both arrive
    else
      update public.orders
         set status = 'paid', razorpay_payment_id = v_payment->>'id', paid_at = now()
       where id = v_order.id;
      v_outcome := 'paid';
    end if;
  elsif v_event = 'payment.failed' then
    update public.orders set status = 'failed'
     where id = v_order.id and status = 'created'; -- a late failure never undoes a payment
    v_outcome := case when found then 'failed' else 'failed_ignored' end;
  else
    v_outcome := 'ignored';
  end if;

  update public.razorpay_events set outcome = v_outcome where event_id = p_event_id;
  return v_outcome;
end $$;

revoke execute on function public.record_razorpay_event(text, jsonb) from public, anon, authenticated;
grant execute on function public.record_razorpay_event(text, jsonb) to service_role;

What each piece does:

  • orders stores amounts in paise, the unit Razorpay's Orders API uses (Razorpay: create an order, checked 2 Dec 2026). Users can read their own orders through Row Level Security; they have no insert or update policy, so nobody can mark their own order paid through the REST API.
  • razorpay_events has the event ID as its primary key. insert ... on conflict do nothing turns every retry of the same event into a no-op, and the table doubles as an audit log of exactly what Razorpay sent.
  • record_razorpay_event() locks the order row (for update), so two concurrent deliveries for the same order run one after the other. It only marks an order paid when the captured amount and currency match what you stored, and a late payment.failed (from an earlier failed attempt) never overwrites a successful payment.
  • Permissions: execute is revoked from anon and authenticated and granted to service_role, so only a caller holding the service key can settle orders. If your REST calls return 403 with DATA_API_DISABLED, enable the Data API for the project in its settings, as the Compute docs explain.

Step 2: Create the Razorpay order from the server

The price must come from your server, never from the browser. This Compute Function keeps Verify JWT / API key on, identifies the signed-in user from their access token, creates the Razorpay order and saves the row before Checkout opens, so the webhook can always find it:

// create-order: a WoWSQL Compute Function. Verify JWT / API key ON.
// Secrets: RAZORPAY_KEY_ID, RAZORPAY_KEY_SECRET, WOWSQL_ANON_KEY, WOWSQL_SERVICE_KEY.
const PRICES = { pro_month: 49900 } // paise, decided on the server, never sent by the browser

module.exports = async function (event) {
  const env = process.env
  // 1. Who is paying? Ask WoWSQL Auth about the caller's access token.
  const me = await fetch(`${env.WOWSQL_URL}/api/auth/me`, {
    headers: { apikey: env.WOWSQL_ANON_KEY, Authorization: event.headers.authorization || '' },
  })
  if (!me.ok) return { statusCode: 401, body: { error: 'sign in first' } }
  const user = await me.json()

  const plan = event.body && event.body.plan
  const amount = PRICES[plan]
  if (!amount) return { statusCode: 400, body: { error: 'unknown plan' } }

  // 2. Create the Razorpay order (amount in paise)
  const rzp = await fetch('https://api.razorpay.com/v1/orders', {
    method: 'POST',
    headers: {
      Authorization: 'Basic ' + Buffer.from(`${env.RAZORPAY_KEY_ID}:${env.RAZORPAY_KEY_SECRET}`).toString('base64'),
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ amount, currency: 'INR', receipt: `${plan}-${Date.now()}` }),
  })
  if (!rzp.ok) return { statusCode: 502, body: { error: 'razorpay order failed' } }
  const order = await rzp.json()

  // 3. Remember it before Checkout opens, so the webhook always finds the row
  const saved = await fetch(`${env.WOWSQL_URL}/rest/v1/orders`, {
    method: 'POST',
    headers: { apikey: env.WOWSQL_SERVICE_KEY, 'Content-Type': 'application/json' },
    body: JSON.stringify({ user_id: user.id, razorpay_order_id: order.id, amount_paise: amount, currency: 'INR' }),
  })
  if (!saved.ok) return { statusCode: 500, body: { error: 'could not save order' } }

  // 4. The browser opens Razorpay Checkout with these
  return { statusCode: 200, body: { order_id: order.id, amount, currency: 'INR', key_id: env.RAZORPAY_KEY_ID } }
}

Save the four secrets on the Compute page (or with wowsql secrets set). Secret values are write-only after you save them, and the service key is not injected into functions automatically; you add it yourself, per the Compute docs. The browser calls the function with the user's token:

const res = await fetch('https://myproject.wowsqlconnect.com/functions/v1/create-order', {
  method: 'POST',
  headers: { Authorization: `Bearer ${session.accessToken}`, 'Content-Type': 'application/json' },
  body: JSON.stringify({ plan: 'pro_month' }),
})
const { order_id, amount, currency, key_id } = await res.json()
// Open Razorpay Checkout with key_id, amount, currency and order_id

In our test, a call without a token returned 401, an unknown plan returned 400, and a valid call sent {"amount":49900,"currency":"INR",...} to the Orders API and saved a created row that the user could then read through RLS. The Razorpay call itself was stubbed, since we didn't use live keys.

Step 3: The webhook function

Create a second function from the Webhook template on the Compute page (it starts with Verify JWT / API key off, because Razorpay can't send a WoWSQL key), name it payment-webhook, and paste:

// payment-webhook: a WoWSQL Compute Function (Node.js, CommonJS, built-in modules only)
// Settings: Verify JWT / API key OFF. Secrets: RAZORPAY_WEBHOOK_SECRET, WOWSQL_SERVICE_KEY.
const crypto = require('crypto')

module.exports = async function (event) {
  if (event.method !== 'POST') return { statusCode: 405, body: { error: 'POST only' } }

  const secret = process.env.RAZORPAY_WEBHOOK_SECRET
  const signature = event.headers['x-razorpay-signature'] || ''
  const eventId = event.headers['x-razorpay-event-id'] || ''
  if (!secret || !signature || !eventId) {
    return { statusCode: 400, body: { error: 'missing signature or event id' } }
  }

  // HMAC-SHA256 over the raw body, exactly as received. Never over re-serialised JSON.
  const expected = crypto.createHmac('sha256', secret).update(event.rawBody || '').digest('hex')
  const a = Buffer.from(expected)
  const b = Buffer.from(signature)
  if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) {
    return { statusCode: 400, body: { error: 'invalid signature' } }
  }

  const payload = JSON.parse(event.rawBody)
  const res = await fetch(`${process.env.WOWSQL_URL}/rest/v1/rpc/record_razorpay_event`, {
    method: 'POST',
    headers: { apikey: process.env.WOWSQL_SERVICE_KEY, 'Content-Type': 'application/json' },
    body: JSON.stringify({ p_event_id: eventId, p_payload: payload }),
    signal: AbortSignal.timeout(4000), // Razorpay waits 5 seconds for a response
  })
  if (!res.ok) {
    console.error('record_razorpay_event failed', res.status, await res.text()) // stderr only
    return { statusCode: 500, body: { error: 'not recorded' } } // non-2xx: Razorpay retries
  }
  const outcome = await res.json()
  if (outcome === 'amount_mismatch' || outcome === 'unknown_order') {
    console.error('needs review', eventId, outcome)
  }
  return { statusCode: 200, body: { outcome } }
}

Then in the Razorpay Dashboard, add a webhook (Test mode first) pointing at https://myproject.wowsqlconnect.com/functions/v1/payment-webhook, set a webhook secret, store the same value as RAZORPAY_WEBHOOK_SECRET, and subscribe to payment.captured, order.paid and payment.failed.

Why each line is there:

  • event.rawBody, not event.body. event.body is already-parsed JSON. Re-serialising it changes whitespace or key order and the HMAC no longer matches. In our test, a signature computed over JSON.stringify(JSON.parse(raw), null, 2) was rejected with 400, exactly as it should be.
  • crypto.timingSafeEqual with a length check first. A plain === comparison can leak how many leading characters matched.
  • Missing header = reject. Requests with no signature or no event ID never reach the database.
  • Return 2xx once the event is recorded, even for unknown_order or amount_mismatch. Those need a human, not a retry storm; a console.error (stderr, because stdout carries the function's response) flags them in Recent invokes.
  • Return 5xx if the database write failed, so Razorpay retries later. AbortSignal.timeout(4000) keeps the function inside Razorpay's 5-second window.

What our test run returned, in order:

Delivery Function response Order after
payment.captured, valid signature 200 {"outcome":"paid"} paid
Same event ID again (a retry) 200 {"outcome":"duplicate"} unchanged
order.paid for the same order 200 {"outcome":"already_paid"} unchanged
Signed with the wrong secret 400 invalid signature unchanged
Signed over re-serialised JSON 400 invalid signature unchanged
No signature header 400 missing signature or event id unchanged
Captured amount differs from the order 200 {"outcome":"amount_mismatch"} still created
payment.failed after a capture 200 {"outcome":"failed_ignored"} stays paid

Razorpay sends both payment.captured (payment entity only) and order.paid (order and payment entities) when an order's payment is captured (Razorpay payment events, checked 2 Dec 2026). Subscribing to both is harmless here because the second one becomes already_paid.

Step 4: The same handler on any Node.js server

If your WoWSQL plan doesn't include Compute Functions, or you already run a Node.js API, wrap the same file. The only rule is to read the body as raw bytes before anything parses it:

// server.mjs: the same handler on any Node.js 18+ host (Render, Railway, a VM...)
import http from 'node:http'
import { createRequire } from 'node:module'
const handler = createRequire(import.meta.url)('./payment-webhook.js')

http.createServer(async (req, res) => {
  if (req.url !== '/webhooks/razorpay') { res.writeHead(404).end(); return }
  const chunks = []
  for await (const chunk of req) chunks.push(chunk)
  const rawBody = Buffer.concat(chunks).toString('utf8') // keep the exact bytes Razorpay signed

  const out = await handler({ method: req.method, headers: req.headers, rawBody })
  res.writeHead(out.statusCode, { 'content-type': 'application/json' })
  res.end(JSON.stringify(out.body))
}).listen(process.env.PORT || 8080)

With Express, the equivalent is express.raw({ type: 'application/json' }) on that one route, then req.body.toString('utf8') as rawBody. We ran server.mjs with curl and a body signed by openssl dgst -sha256 -hmac: the first delivery returned {"outcome":"paid"} and the retry {"outcome":"duplicate"}. Razorpay webhook URLs must use port 80 or 443, and Razorpay blocks common tunnel domains such as ngrok for testing, so use a staging URL (Razorpay, checked 2 Dec 2026).

Step 5: Show the result to the customer

The browser shouldn't decide that a payment succeeded. After Checkout's success handler fires, read the order through RLS until the webhook has settled it:

async function waitForPaid(orderId, accessToken, tries = 10) {
  for (let i = 0; i < tries; i++) {
    const res = await fetch(
      `https://myproject.wowsqlconnect.com/rest/v1/orders?razorpay_order_id=eq.${orderId}&select=status`,
      { headers: { apikey: 'wowsql_anon_your_key_here', Authorization: `Bearer ${accessToken}` } },
    )
    const [order] = await res.json()
    if (order?.status === 'paid') return true
    await new Promise((r) => setTimeout(r, 1500))
  }
  return false // show "we're confirming your payment" and let the webhook finish
}

Razorpay recommends a direct API fetch of the payment or order if a user-facing flow can't wait for the webhook (Razorpay webhooks overview, checked 2 Dec 2026). You can also verify Checkout's razorpay_signature on your server: it is an HMAC-SHA256 of order_id + "|" + razorpay_payment_id keyed with your API key secret, not the webhook secret (Razorpay integration steps, checked 2 Dec 2026). Treat that as a fast hint; the webhook still settles the order.

Where to host a Razorpay webhook: options compared

WoWSQL Compute Function Supabase Edge Function Firebase Cloud Functions Your own Node.js server
Runtime Node.js or Python, one file, built-in modules only TypeScript on Deno Node.js, Python Anything
Turn off platform auth for the webhook Verify JWT / API key switch verify_jwt = false per function Public HTTPS function Not applicable
Plan needed Pricing page lists Edge Functions on Pro $25 and Scale $99 Free plan includes 500,000 invocations Blaze (pay as you go); Spark shows Cloud Functions as not applicable Your hosting bill
Database next to it Your WoWSQL Postgres, same region Supabase Postgres Firestore or another database Whatever you connect
Third-party packages No (no npm install; use crypto and fetch) Yes Yes Yes
Limits we found Pro and Scale: 100 execution hours/month, 60 s timeout 256 MB memory, 2 s CPU time, 150 s idle timeout See Google Cloud pricing Your server

Sources checked 2 Dec 2026: WoWSQL pricing, WoWSQL Compute docs, Supabase pricing, Supabase function configuration, Supabase Edge Function limits, Firebase pricing.

Where others are better: Supabase includes Edge Function invocations on its free plan and lets you import npm packages, including Razorpay's SDK. Firebase and a self-hosted server give you the full Node.js ecosystem. WoWSQL's case is that the function, the Postgres tables and Auth sit in one project in Mumbai, US East or Frankfurt, and that a webhook needs nothing beyond crypto and fetch, which the runtime provides.

Production checklist

  • Test mode first, with a separate Test webhook and secret; switch the secret when you go live. If you rotate the webhook secret, Razorpay's docs say retries of older events are signed with the old one.
  • Keep the service key only in function secrets. It bypasses RLS; the signature check is what stands between the internet and record_razorpay_event().
  • Watch razorpay_events.outcome. A daily query for amount_mismatch and unknown_order catches integration bugs early.
  • Refunds and disputes follow the same pattern: add the events you subscribe to, extend the function and add a status such as refunded.
  • Data and tax rules are yours to check: see the DPDP Act checklist for developers.

Related guides

FAQ

How do I verify a Razorpay webhook signature in Node.js?

Compute crypto.createHmac('sha256', webhookSecret).update(rawBody).digest('hex') over the raw request body and compare it with the X-Razorpay-Signature header using crypto.timingSafeEqual. Never verify against parsed and re-stringified JSON; it changes the bytes and the check fails.

Why does my Razorpay webhook signature not match?

The usual causes are verifying a parsed body instead of the raw body, using the API key secret instead of the webhook secret, a Test mode secret against Live events, or a secret that was rotated (retries of older events use the old secret).

How do I store Razorpay payments in Postgres?

Keep an orders table with the Razorpay order ID and amount in paise, and an events table keyed by x-razorpay-event-id. In one transaction, insert the event with on conflict do nothing, check the amount and currency, and mark the order paid. On WoWSQL that is one SQL function called from the webhook.

How do I handle duplicate Razorpay webhooks?

Razorpay delivers at least once and retries non-2xx responses for 24 hours. Store each x-razorpay-event-id under a unique constraint and treat a conflict as "already handled", returning 200.

Should I use payment.captured or order.paid?

Either works for marking an order paid. payment.captured carries the payment entity; order.paid carries both the order and the payment. If you subscribe to both, make the handler idempotent so the second event changes nothing.

Can I run a Razorpay webhook on WoWSQL's free plan?

WoWSQL's pricing page lists Edge Functions (Compute Functions) on Pro and Scale, so check your plan's Compute page. If functions aren't available to you, run the same handler on any Node.js host and keep the tables in WoWSQL.

Create a free WoWSQL project · Compute docs · Pricing