Docs / Next.js example
PayRam webhook signature verification in Next.js (App Router)
The most common Next.js mistake is calling request.json() before computing the signature. This guide gives a tested route handler.
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 Next.js 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
- Next.js 13.4 or later with the App Router (route handlers). We did not test the Pages Router; see the FAQ.
- Put the project API key in an environment variable:
.env.locallocally, or the project’s environment variables on Vercel, asPAYRAM_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: app/api/payram/webhook/route.ts
// app/api/payram/webhook/route.ts
import crypto from 'node:crypto';
export const runtime = 'nodejs'; // 需要 node:crypto,不要放到 edge runtime
export const dynamic = 'force-dynamic';
const API_KEY = process.env.PAYRAM_API_KEY ?? ''; // 项目 API 密钥,只放在服务端环境变量里
function isValid(raw: Buffer, signature: string | null): boolean {
const expected = 'sha256=' + crypto.createHmac('sha256', API_KEY).update(raw).digest('hex');
const a = Buffer.from(signature ?? '');
const b = Buffer.from(expected);
return a.length === b.length && crypto.timingSafeEqual(a, b);
}
export async function POST(request: Request) {
// 必须用原始字节算签名:先 request.json() 再重新序列化,签名一定对不上
const raw = Buffer.from(await request.arrayBuffer());
if (!isValid(raw, request.headers.get('x-payram-signature'))) {
return new Response('invalid signature', { status: 401 });
}
const event = JSON.parse(raw.toString('utf8'));
// 以 reference_id + status 做幂等:同一条通知可能重复到达
await handleEvent(event);
return new Response('ok', { status: 200 }); // 尽快返回 2xx,耗时的事放到队列里
}
async function handleEvent(event: { reference_id: string; status: string; invoice_id?: string }) {
// TODO:查你自己的订单(invoice_id),状态是 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.
3. Setup and routing
Save the code above as app/api/payram/webhook/route.ts. The callback address is https://your-domain/api/payram/webhook; register it in the PayRam dashboard.
# .env.local
PAYRAM_API_KEY=your project API key
4. Why it is written this way
- Get the raw bytes with
request.arrayBuffer(). Callingrequest.json()and thenJSON.stringifyto compute the signature fails as soon as key order or whitespace differs. This is the most common mistake. runtime = 'nodejs'. The code usesnode:crypto, which may not run in the Edge runtime. To run at the edge, use the Web Crypto version in the Cloudflare Workers guide.- Compare lengths first, then
timingSafeEqual.crypto.timingSafeEqualthrows when the two lengths differ, so check the length first. - Do not let middleware touch the body. If your
middleware.tsor a gateway rewrites the body, the signature will not match. Let the webhook path bypass that. - Return 2xx first. PayRam retries a request when the response is 400 or above, or nothing arrives within 60 seconds. Put slow work on a queue.
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:3000/api/payram/webhook \
-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_idplusstatusas a unique key and answer 200 straight away if it was already handled. - Ship only after receipt. Ship only on
FILLEDorOVER_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
The signature never matches. What is wrong?
The three usual causes: calling request.json() and re-serialising; using the wrong project’s API key (with several projects, each has its own); or the body being altered by middleware or a proxy. Compare with the webhook guide and check with the curl command above.
How does PayRam reach my laptop during development?
The callback address has to be a publicly reachable HTTPS address. In development, expose the local port with a tunnel such as cloudflared or ngrok and register the tunnel address in the dashboard. You can also simulate a callback yourself with the curl command in this guide.
I use the Pages Router (pages/api). What now?
We did not test the Pages Router. The idea is the same: turn off its default body parsing, read the raw bytes and verify them. Check with the curl command in a test project before going live.
Can I handle this directly in a Vercel serverless function?
Yes, but a function may be frozen after it returns, so slow work such as sending email or updating orders should go on a queue and not continue after you return 2xx.
Related reading
- 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.
