Fixing Cashfree Webhook Signature Verification Mismatch in Node.js & Next.js
Resolve Cashfree Payment Gateway x-webhook-signature verification failures in Node.js, Express, and Next.js. Concatenate x-webhook-timestamp with raw body bytes and output Base64 HMAC-SHA256.
Unlike Razorpay (which hashes only the raw body and outputs hexadecimal), Cashfree Payment Gateway v2023-08-01+ computes its webhook signature by concatenating the exact x-webhook-timestamp header string directly with the raw UTF-8 request body (timestamp + rawBody, with NO separator character), hashing it with HMAC-SHA256 using your Cashfree Client Secret, and encoding the output in Base64. If you output .digest('hex'), omit the timestamp prefix, or pass a parsed JSON object, signature verification will fail 100% of the time.
Verified Root Causes in Production Environments
- Encoding Digest as Hex Instead of Base64: Developers migrating from Razorpay or Stripe call .digest('hex') instead of .digest('base64').
- Missing x-webhook-timestamp Prefix Concatenation: Hashing only the raw body without prepending req.headers['x-webhook-timestamp'] fails Cashfree's replay-protected HMAC specification.
- Sandbox vs Production Secret Key Mismatch: Using Production Client Secret while testing Sandbox webhooks from the Cashfree dashboard.
1. The Exact Cashfree HMAC-SHA256 Signing Formula (Base64 + Timestamp)
To prevent replay attacks, Cashfree Payments includes two cryptographic headers on every webhook POST request: x-webhook-timestamp (epoch milliseconds string, e.g., 1763300000000) and x-webhook-signature (a Base64-encoded HMAC-SHA256 string).
As documented in the Cashfree Payment Gateway Webhook Signature Verification specification, the signed payload string is constructed by concatenating x-webhook-timestamp and the exact raw body without any colon or period delimiter: signedPayload = timestamp + rawBody. That concatenated string is then hashed using your Client Secret (X-Client-Secret) and encoded as Base64.
In high-throughput Indian fintech and SaaS applications accepting UPI Intent, QR, and RuPay payments through Cashfree Payment Gateway, webhook reliability is critical for instant order fulfillment. Unlike client-side redirect callbacks—which fail whenever a user closes their mobile browser tab after approving a payment in Google Pay or PhonePe—Server-to-Server (S2S) webhooks guarantee delivery even on unstable 4G/5G connections.
Always log the x-webhook-version header alongside x-webhook-timestamp when debugging signature failures across staging and production environments. Cashfree API versions 2023-08-01 and 2025-01-01 standardize the payload schema under data.order and data.payment, and require strict UTF-8 byte preservation prior to computing the Base64 HMAC-SHA256 signature.
import crypto from 'crypto';
export function verifyCashfreeWebhook(
rawBody: string,
timestampHeader: string | null,
signatureHeader: string | null,
clientSecret: string
): boolean {
if (!rawBody || !timestampHeader || !signatureHeader || !clientSecret) {
return false;
}
// Optional: Reject replay attacks older than 5 minutes (300,000 ms)
const nowMs = Date.now();
const webhookMs = Number(timestampHeader);
if (Number.isNaN(webhookMs) || Math.abs(nowMs - webhookMs) > 5 * 60 * 1000) {
console.warn('[Cashfree Webhook] Timestamp outside 5-minute tolerance window');
}
// CRITICAL: Concatenate timestamp + rawBody directly (NO separator) and digest as base64
const signatureData = `${timestampHeader}${rawBody}`;
const computedSignature = crypto
.createHmac('sha256', clientSecret)
.update(signatureData, 'utf8')
.digest('base64');
const a = Buffer.from(computedSignature, 'utf8');
const b = Buffer.from(signatureHeader, 'utf8');
return a.length === b.length && crypto.timingSafeEqual(a, b);
}2. Complete Next.js App Router & Express Implementation
When using the official cashfree-pg Node SDK (Cashfree.PGVerifyWebhookSignature(signature, rawBody, timestamp)), the SDK internally performs the exact concatenation shown above. However, whether you use the SDK or native Node crypto, passing a parsed JavaScript object instead of the raw string or Buffer throws an instant signature mismatch error.
Below is a production-ready Next.js App Router webhook endpoint that verifies Cashfree PAYMENT_SUCCESS_WEBHOOK payloads and extracts the UPI UTR and order metadata.
import { NextRequest, NextResponse } from 'next/server';
import { verifyCashfreeWebhook } from '@/lib/cashfree-verify-helper';
export const runtime = 'nodejs';
export async function POST(req: NextRequest) {
const rawBody = await req.text();
const timestamp = req.headers.get('x-webhook-timestamp');
const signature = req.headers.get('x-webhook-signature');
const clientSecret = process.env.CASHFREE_CLIENT_SECRET!;
const isValid = verifyCashfreeWebhook(rawBody, timestamp, signature, clientSecret);
if (!isValid) {
return NextResponse.json(
{ error: 'Cashfree webhook signature verification failed' },
{ status: 401 }
);
}
const payload = JSON.parse(rawBody);
if (payload.type === 'PAYMENT_SUCCESS_WEBHOOK') {
const orderId = payload.data?.order?.order_id;
const cfPaymentId = payload.data?.payment?.cf_payment_id;
const bankReference = payload.data?.payment?.bank_reference;
console.log(`Verified Cashfree Order ${orderId} (CF ID: ${cfPaymentId}, UTR: ${bankReference})`);
}
return NextResponse.json({ status: 'ok' }, { status: 200 });
}3. Debugging Cashfree Dashboard 'Test Webhook' vs Real Payment Callbacks
A common gotcha reported on Stack Overflow (question 79745537) occurs when clicking the 'Test' button during webhook setup in the Cashfree Merchant Dashboard. Depending on the API version selected in your dashboard dropdown (2022-09-01 vs 2023-08-01), test pings may send synthetic dummy payloads without a valid HMAC signature until the endpoint returns HTTP 200 once. Allow your endpoint to respond 200 to an initial unauthenticated ping only if payload.data.test_object is present in non-production environments, or test using a real ₹1 Sandbox checkout order.
#!/usr/bin/env bash
CLIENT_SECRET="cfsk_ma_test_secret_key"
TIMESTAMP="1763300000000"
BODY='{"data":{"order":{"order_id":"order_vexlo_101","order_amount":149.00}},"event_time":"2026-11-16T18:00:00+05:30","type":"PAYMENT_SUCCESS_WEBHOOK"}'
# Concatenate TIMESTAMP + BODY and compute Base64 HMAC-SHA256
SIGNATURE=$(printf "%s%s" "$TIMESTAMP" "$BODY" | openssl dgst -sha256 -hmac "$CLIENT_SECRET" -binary | base64)
curl -i -X POST http://localhost:3000/api/webhooks/cashfree \
-H "Content-Type: application/json" \
-H "x-webhook-timestamp: $TIMESTAMP" \
-H "x-webhook-signature: $SIGNATURE" \
--data-raw "$BODY"Pre-Deployment Verification Checklist
- Prepend x-webhook-timestamp directly to the raw body string before hashing (`${timestamp}${rawBody}`).
- Encode the HMAC-SHA256 digest in 'base64' (NOT 'hex').
- Ensure CASHFREE_CLIENT_SECRET matches the environment (Sandbox vs Production) generating the webhook.
- Read the raw request body via await req.text() or express.raw() before any JSON middleware touches the stream.
Deploy on Vexlo Cloud in 60s (₹149/mo UPI)
Automated Docker & Nixpacks builds, managed PostgreSQL/Redis, and AI Deployment Doctor. Instant INR UPI for India or USD/EUR/GBP across 17 global currencies.
Frequently Asked Questions
Why does my Cashfree webhook signature not match even with the raw body?
Make sure you are concatenating the x-webhook-timestamp header before the raw body string with no separator, and calling .digest('base64') rather than .digest('hex').
Which secret key does Cashfree use to sign webhooks?
Cashfree signs webhooks using your Payment Gateway Client Secret (the same X-Client-Secret used for server-to-server order creation in that environment).
How do I use Cashfree's official Node.js SDK to verify webhooks?
Call Cashfree.PGVerifyWebhookSignature(req.headers['x-webhook-signature'], req.rawBody, req.headers['x-webhook-timestamp']) and ensure req.rawBody is a raw UTF-8 string or Buffer.