Appearance

Visual style

Mode
Theme
Accent
Advanced
Text sizeScales the whole site
16 px
Reduce motionReduce animations or match your system
Separate light and darkChoose a theme, accent and font for each
50

E-commerce Development

How to verify and process payment webhooks on Cloudflare Workers

The pattern I use for Razorpay and Mercado Pago webhooks on Workers, from a real digital-products store, including two flaws I found reviewing my own code.

Treat a payment webhook as an untrusted message that must be verified, persisted and processed exactly once in effect. On Cloudflare Workers that means: verify the HMAC signature against the raw request body, push the event onto a Queue and return 200 quickly, process it in a consumer that is idempotent and retries on failure, and run a scheduled job that repairs anything that slipped through.

This article walks through that pattern as I implemented it in a digital-products store (Hono on Workers, Razorpay, Neon Postgres via Drizzle, R2, Cloudflare Queues), and the two weaknesses I found when I reviewed the code for this write-up.

Why the browser redirect isn’t enough

After paying, the buyer is redirected back to your site. It’s tempting to mark the order paid at that point. Don’t:

  • The redirect can be forged or replayed by anyone who knows the URL shape.
  • The buyer may close the tab before the redirect happens.
  • Asynchronous methods (PIX in Brazil, bank transfers) complete in another app entirely, with no redirect at all.

The provider’s webhook is the reliable signal. The redirect is only a hint to show a “processing” screen.

Step 1: verify the signature against the raw body

Providers sign the exact bytes they send. If you parse the JSON and re-serialise it before verifying, whitespace or key order can change and verification fails, or worse, you end up verifying something other than what was signed. In Hono, read the body as text first:

webhooksRoute.post("/razorpay", async (c) => {
  const rawBody = await c.req.text();
  const signature = c.req.header("x-razorpay-signature");
  if (!signature) throw new UnauthorizedError("Missing signature header");

  await c.get("dependencies").useCases.enqueuePaymentEvent.execute(rawBody, signature);
  return c.json({ received: true });
});

Razorpay’s signature is an HMAC-SHA256 of the raw body using your webhook secret. Workers has Web Crypto built in, so no Node polyfill is needed:

async function hmacSha256Hex(secret: string, message: string): Promise<string> {
  const key = await crypto.subtle.importKey(
    "raw", new TextEncoder().encode(secret),
    { name: "HMAC", hash: "SHA-256" }, false, ["sign"],
  );
  const sig = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(message));
  return [...new Uint8Array(sig)].map((b) => b.toString(16).padStart(2, "0")).join("");
}

function timingSafeEqual(a: string, b: string): boolean {
  if (a.length !== b.length) return false;
  let diff = 0;
  for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
  return diff === 0;
}

Use a constant-time comparison, not ===, so response timing doesn’t leak how much of a forged signature was correct.

Mercado Pago differs. Its x-signature header contains a timestamp (ts) and a signature (v1), and, per its documentation, the HMAC-SHA256 is computed over a manifest built from the notification’s data ID, the x-request-id header and the timestamp, not over the whole body. The principle is the same, but the signed string is different. Whatever the provider, also fetch the payment by ID from the provider’s API before trusting its status.

Step 2: enqueue, then acknowledge

Verification is fast. Fulfilment isn’t: it touches the database, generates tokens and sends email. If that work runs inside the webhook request and anything is slow, the provider times out and retries, and now you have concurrent duplicates.

So the webhook use case does only what must happen synchronously:

async execute(rawBody: string, signature: string) {
  if (!(await this.payments.verifyWebhookSignature(rawBody, signature))) {
    throw new UnauthorizedError("Invalid webhook signature");
  }
  const payload = JSON.parse(rawBody) as RazorpayWebhookPayload;
  if (payload.event !== "payment.captured") return; // ignore events we don't act on

  const { id: paymentId, order_id: providerOrderId } = payload.payload.payment.entity;
  const order = await this.orders.findByProviderOrderId(providerOrderId);
  if (!order) throw new NotFoundError("Order", providerOrderId);

  await this.queue.enqueue({ eventType: payload.event, orderId: order.id, paymentId, providerOrderId });
}

The Queue is declared per environment in wrangler.toml, with a dead-letter queue in production:

[[env.production.queues.consumers]]
queue             = "payment-events-production"
max_batch_size    = 10
max_batch_timeout = 5
max_retries       = 3
dead_letter_queue = "payment-events-dlq-production"

Step 3: process idempotently, and actually retry

Providers deliver at least once. Queues deliver at least once. Your consumer will see duplicates, so processing must be safe to repeat. The consumer in my store looked like this:

for (const msg of batch.messages) {
  try {
    await confirmPayment.execute(msg.body);
    msg.ack();
  } catch (err) {
    console.error("[payment-worker] failed to process", msg.body.orderId, err);
  }
}

That has a subtle bug. Cloudflare Queues acknowledges the messages in a batch when the consumer returns successfully, unless they were explicitly retried. Because the catch swallows the error and the handler returns normally, a failed message is treated as delivered: it’s never retried, and it never reaches the dead-letter queue configured above. The fix is one line:

  } catch (err) {
    console.error("[payment-worker] failed to process", msg.body.orderId, err);
    msg.retry(); // let Queues retry it, then dead-letter it after max_retries
  }

Inside confirmPayment, the idempotency guard is a state check:

const order = await this.orders.findByProviderOrderId(msg.providerOrderId);
if (order.status.isPaid()) return; // already handled
order.markPaid(msg.paymentId);
await this.orders.save(order);

This handles sequential duplicates. It doesn’t handle concurrent ones: two consumer invocations can both read “pending”, both pass the check and both fulfil. The safer version makes the transition itself conditional, so the database decides who wins:

const [won] = await db
  .update(orders)
  .set({ status: "paid", paymentId: msg.paymentId, paidAt: new Date() })
  .where(and(eq(orders.id, msg.orderId), eq(orders.status, "pending")))
  .returning({ id: orders.id });

if (!won) return; // another delivery already moved this order on
await fulfil(msg.orderId);

Only the invocation that actually changed the row goes on to issue a download link and send email.

Step 4: sweep for anything missed

Even with retries and a dead-letter queue, it’s worth a safety net that reasons from state, not events. A Cron Trigger runs every six hours (crons = ["0 */6 * * *"]) and looks for paid orders with no valid download token, then fulfils them:

async scheduled(_event, env, ctx) {
  ctx.waitUntil(sweepUnfulfilledOrders(env).execute());
}

The sweep makes the system self-healing. If an email provider was down, a deploy interrupted a consumer, or a message was dead-lettered, paid customers still get what they bought within hours, without a support ticket.

The whole flow

StageWhereGuarantees
Verify signature on raw bodyWebhook route (Hono)Only genuine provider events are accepted
Enqueue and return 200Webhook use caseFast response; no provider retries due to timeouts
Conditional “pending → paid”Queue consumerExactly one fulfilment per order, even under concurrency
retry() on failure, DLQ after NQueue consumerTransient failures retried; persistent ones visible
Six-hourly sweepCron TriggerAny paid-but-unfulfilled order is repaired

Checklist

  • Read the raw body before parsing; verify with HMAC-SHA256 and a constant-time comparison.
  • Check the provider’s exact signing scheme (Razorpay signs the body; Mercado Pago signs a manifest).
  • Ignore event types you don’t act on, but return 200 for them so the provider stops retrying.
  • Confirm payment state with the provider’s API when the webhook payload alone isn’t sufficient.
  • Enqueue and respond quickly; never fulfil inside the webhook request.
  • Make the state transition a conditional update; fulfil only if you won it.
  • Call retry() on failures and configure a dead-letter queue, then alert on it.
  • Run a scheduled reconciliation that reasons from state.

References

  1. Razorpay: validate webhook signatures razorpay.com
  2. Mercado Pago: webhook notifications www.mercadopago.com.br
  3. Cloudflare Queues: batching, retries and delays developers.cloudflare.com
  4. Cloudflare Queues: dead letter queues developers.cloudflare.com
  5. Cloudflare Workers: Cron Triggers developers.cloudflare.com
  6. MDN: SubtleCrypto.sign() developer.mozilla.org

Working on something like this?

If this article maps to a problem in your own product, send me a short note about it. I'm happy to give a second opinion.