PayRamHost hosted onboarding is paused · Guides keep updatingGet notified when it reopens →

Docs / Cloudflare Workers example

PayRam webhook signature verification on Cloudflare Workers

Workers has no node:crypto, but Web Crypto’s verify is already a constant-time comparison. This guide shows the complete approach.

Last updated · By the PayRamHost editors · Markdown version

PayRamHost hosted merchant onboarding has been paused since 29 November 2026. Where this guide mentions PayRamHost, it describes the situation before the pause; the PayRam usage it explains still applies.

The short version: a PayRam webhook signature is an HMAC-SHA256 of the raw request body, keyed with your project API key, sent in the header X-Payram-Signature: sha256=<hex>. In Cloudflare Workers the key is to get the raw bytes untouched by the framework and compute the signature over them. Below is a complete, tested version.

1. Before you start

  • A Cloudflare account with wrangler installed.
  • Store the project API key as a secret rather than in code: wrangler secret put PAYRAM_API_KEY.
  • Register an HTTPS callback address for the project in the PayRam dashboard and set it to active; see the webhook guide.
  • With several projects, verify each with its own API key; see multiple projects.

2. The complete code

File: worker.js

// Cloudflare Workers:用 Web Crypto 校验 PayRam Webhook 签名
// wrangler secret put PAYRAM_API_KEY  (把项目 API 密钥存成 Secret,不要写进代码)

const encoder = new TextEncoder();

function hexToBytes(hex) {
  if (!/^[0-9a-f]{64}$/i.test(hex)) return null; // HMAC-SHA256 的十六进制摘要固定是 64 个字符
  return Uint8Array.from(hex.match(/../g), (h) => parseInt(h, 16));
}

async function isValid(raw, header, apiKey) {
  const prefix = 'sha256=';
  if (!header || !header.startsWith(prefix)) return false;
  const signature = hexToBytes(header.slice(prefix.length));
  if (!signature) return false;
  const key = await crypto.subtle.importKey('raw', encoder.encode(apiKey), { name: 'HMAC', hash: 'SHA-256' }, false, ['verify']);
  return crypto.subtle.verify('HMAC', key, signature, raw); // verify 内部是恒定时间比较
}

export default {
  async fetch(request, env, ctx) {
    if (request.method !== 'POST') return new Response('method not allowed', { status: 405 });

    const raw = await request.arrayBuffer(); // 原始字节,不要先 request.json()
    if (!(await isValid(raw, request.headers.get('X-Payram-Signature'), env.PAYRAM_API_KEY))) {
      return new Response('invalid signature', { status: 401 });
    }

    const event = JSON.parse(new TextDecoder().decode(raw));
    ctx.waitUntil(handleEvent(event, env)); // 先返回 2xx,再在后台处理
    return new Response('ok', { status: 200 });
  },
};

async function handleEvent(event, env) {
  // TODO:以 reference_id + status 做幂等(比如存进 KV 或 D1),状态是 FILLED 或 OVER_FILLED 才发货
}

The code in this guide was tested locally before publishing: test cases cover a valid signature, a tampered body, re-serialised JSON, a missing signature, a short signature, a wrong key and more, and we confirmed that the openssl command below produces the same signature as the code. The code was tested on Node.js’s Web Crypto implementation (the same standard interface Workers uses); we did not run it in the Workers runtime itself.

3. Setup and routing

Configure wrangler.toml and deploy. The callback address is your Worker’s address (or a custom domain bound to it):

# wrangler.toml
name = "payram-webhook"
main = "worker.js"
compatibility_date = "2026-11-01"

# deploy
wrangler secret put PAYRAM_API_KEY
wrangler deploy

4. Why it is written this way

  • crypto.subtle.verify is itself a constant-time comparison. You do not need your own comparison function: convert the hex signature to bytes and hand it to verify.
  • Check the hex format first. An HMAC-SHA256 digest is always 64 hex characters, so anything else is invalid, which avoids exceptions later.
  • Get the raw bytes with request.arrayBuffer(). Do not call request.json() first.
  • ctx.waitUntil. Return 200 first and let the background work keep running instead of being cut off when the response is sent.
  • Never put the key in wrangler.toml. It gets committed. Use a secret.

5. Testing locally

The command below computes the correct signature with your key and sends a simulated callback to your local server. It should return 200; change any one character in BODY and send it again, and it should return 401. Use the key of a separate test project, not a production one.

export PAYRAM_API_KEY='your test project API key'
BODY='{"reference_id":"a1b2c3d4e5","invoice_id":"INV-0090","status":"FILLED"}'
SIG="sha256=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "$PAYRAM_API_KEY" -hex | sed 's/^.* //')"
curl -i -X POST http://localhost:8787/ \
  -H "Content-Type: application/json" \
  -H "X-Payram-Signature: $SIG" \
  -d "$BODY"

6. What to add before going live

  • Idempotency. The same notification can arrive twice. Use reference_id plus status as a unique key and answer 200 straight away if it was already handled.
  • Ship only after receipt. Ship only on FILLED or OVER_FILLED; see payment statuses.
  • Return 2xx first, then process. PayRam retries requests answered with 400 or above, or with no response within 60 seconds; the rules are in the webhook guide.
  • Use the status endpoint as a safety net. If a notification is ever missed, reconcile with the status endpoint.
  • Run it once with a real 1 US dollar payment. See the go-live checklist.

7. FAQ

Can the Edge runtime in Next.js use this code?

The core isValid function is built on standard Web Crypto, so it works in the Edge runtime and other environments that support it. Write the route handler shell as in the Next.js guide.

Where do I keep the idempotency records?

In Workers KV or D1: use reference_id:status as the key, check before handling and write after. Note that KV is eventually consistent, so under high concurrency a unique index in D1 is more reliable.

How do I test it locally?

wrangler dev starts a local server; use the curl command above with the address it prints.

  • Webhook guide: How to receive PayRam webhooks: register an endpoint, verify X-Payram-Signature, understand retry rules and payment states, handle duplicates, with Node.js and Python examples.
  • Payment statuses: What PayRam's five payment statuses mean, how to handle underpaid (PARTIALLY_FILLED), overpaid (OVER_FILLED) and expired (CANCELLED) payments, and how to keep your order status in sync using webhooks and the status endpoint.
  • Create payments via API: Add crypto payments to your own site with the PayRam API: create a payment and get a payment link, send the customer to the payment page, confirm receipt with webhooks and the status endpoint, and reconcile by order number. With curl, Node.js and Python examples.
  • Go-live checklist: PayRam mainnet has no sandbox, so test with small real amounts before launch. This checklist covers, in order: checking the configuration, one payment per chain and coin, verifying sweeping, under- and overpayment and expiry, webhooks, refunds and payouts, the card channel, and where to look when something fails.

Sources

This guide is based on the PayRam official documentation below, checked on 2026-11-12. PayRamHost is an independently operated service and is not affiliated with PayRam. If anything differs, the official documentation prevails.