Deploy on Vexlo Cloud in 60s (₹149/mo UPI) — India's First & Only Developer PaaS. Instant INR UPI & 17 global currencies ($5/mo).
Deploy Now
Bucket 2: Indian Payment Gateways & UPI Webhooks7 min readVerified

Fixing PhonePe Payment Gateway X-VERIFY Checksum & S2S Webhook Verification in Node.js

Resolve PhonePe PG BAD_REQUEST and X-VERIFY checksum verification errors in Node.js and Next.js. Implement exact SHA256(base64Payload + apiEndpoint + saltKey) + ### + saltIndex formulas.

TL;DR — Immediate Production Fix

PhonePe Payment Gateway returns 400 BAD_REQUEST (Checksum verification failed) when the X-VERIFY header is malformed. Unlike HMAC-SHA256 gateways, PhonePe Standard Checkout v1 uses plain SHA-256 (not HMAC) over the concatenated string base64Payload + "/pg/v1/pay" + saltKey, followed by the literal delimiter "###" and the saltIndex (e.g., sha256Hex + "###1"). For incoming Server-to-Server (S2S) webhooks, PhonePe either sends X-VERIFY calculated as SHA256(base64Response + saltKey) + "###" + saltIndex OR (in v2 Basic Auth mode) sends an Authorization header containing SHA256(username:password).

Verified Root Causes in Production Environments

  • Using HMAC-SHA256 Instead of Standard SHA-256: Calling crypto.createHmac('sha256', saltKey) instead of crypto.createHash('sha256').update(base64Payload + endpoint + saltKey).
  • Omitting the API Path in Outgoing Pay Requests vs Including It in Webhooks: Outgoing /pg/v1/pay requests require the path '/pg/v1/pay' in the hash string, whereas incoming S2S webhook X-VERIFY hashes ONLY base64Response + saltKey without any URL path.
  • Missing ###1 Salt Index Suffix: Forgetting to append ### followed by the exact Salt Index (usually 1) at the end of the hex digest.

1. Outgoing /pg/v1/pay Request vs Incoming S2S Webhook X-VERIFY Formulas

The number one cause of PhonePe integration bugs in Node.js is mixing up the three distinct X-VERIFY formulas across (A) initiating a payment, (B) checking payment status via GET, and (C) verifying an incoming Server-to-Server (S2S) webhook callback.

First, PhonePe uses standard SHA-256 (crypto.createHash('sha256')), NOT HMAC. Second, the API path (/pg/v1/pay) is included when initiating a payment, but is NOT included when verifying an incoming S2S webhook POST body.

When integrating PhonePe Payment Gateway Standard Checkout in production Node.js or Next.js backends, remember that PhonePe enforces strict IP whitelisting and callback URL validation alongside cryptographic X-VERIFY headers. If your application runs inside a Docker container behind a reverse proxy, ensure your webhook route responds with HTTP 200 within 3 seconds and offloads invoice PDF generation or container provisioning to an asynchronous background queue.

Furthermore, if a webhook ever fails to arrive due to an upstream network blip, implement PhonePe's mandatory Status Check API reconciliation schedule (polling at 20-25 seconds, then every 3 seconds for 30 seconds, every 6 seconds for 60 seconds, and concluding at 15 minutes) using the GET status X-VERIFY formula documented above.

phonepe-checksum-formulas.ts
typescript
import crypto from 'crypto';

/**
 * 1. Outgoing Payment Initiation (/pg/v1/pay)
 * Formula: SHA256(base64Body + "/pg/v1/pay" + saltKey) + "###" + saltIndex
 */
export function generatePhonePePayChecksum(
  jsonPayload: Record<string, unknown>,
  saltKey: string,
  saltIndex = '1'
): { base64Body: string; xVerify: string } {
  const base64Body = Buffer.from(JSON.stringify(jsonPayload), 'utf8').toString('base64');
  const stringToHash = `${base64Body}/pg/v1/pay${saltKey}`;
  const sha256Hex = crypto.createHash('sha256').update(stringToHash, 'utf8').digest('hex');
  return {
    base64Body,
    xVerify: `${sha256Hex}###${saltIndex}`,
  };
}

/**
 * 2. Outgoing Status Check GET (/pg/v1/status/{merchantId}/{merchantTransactionId})
 * Formula: SHA256("/pg/v1/status/{merchantId}/{merchantTransactionId}" + saltKey) + "###" + saltIndex
 */
export function generatePhonePeStatusChecksum(
  merchantId: string,
  merchantTransactionId: string,
  saltKey: string,
  saltIndex = '1'
): string {
  const endpoint = `/pg/v1/status/${merchantId}/${merchantTransactionId}`;
  const sha256Hex = crypto
    .createHash('sha256')
    .update(`${endpoint}${saltKey}`, 'utf8')
    .digest('hex');
  return `${sha256Hex}###${saltIndex}`;
}

/**
 * 3. Incoming S2S Webhook Callback Verification
 * Formula: SHA256(body.response + saltKey) + "###" + saltIndex
 */
export function verifyPhonePeWebhookChecksum(
  base64ResponseField: string,
  xVerifyHeader: string | null,
  saltKey: string,
  saltIndex = '1'
): boolean {
  if (!base64ResponseField || !xVerifyHeader) return false;
  const expectedHex = crypto
    .createHash('sha256')
    .update(`${base64ResponseField}${saltKey}`, 'utf8')
    .digest('hex');
  const expectedXVerify = `${expectedHex}###${saltIndex}`;
  return expectedXVerify === xVerifyHeader.trim();
}

2. Production Next.js App Router PhonePe Webhook Handler

When PhonePe sends a Server-to-Server (S2S) callback to your callbackUrl, the HTTP POST body is a JSON object with a single key: { "response": "eyJzdWNjZXNzIjp0cnVlLC..." }. That response string is a Base64-encoded JSON document containing the actual transaction status (PAYMENT_SUCCESS, PAYMENT_ERROR, or PAYMENT_PENDING).

In your webhook route, parse the outer JSON, pass body.response into verifyPhonePeWebhookChecksum along with the x-verify header, and then Base64-decode body.response to read code and data.merchantTransactionId.

app/api/webhooks/phonepe/route.ts
typescript
import { NextRequest, NextResponse } from 'next/server';
import { verifyPhonePeWebhookChecksum } from '@/lib/phonepe-checksum-formulas';

export const runtime = 'nodejs';

export async function POST(req: NextRequest) {
  try {
    const rawJson = await req.json();
    const base64Response: string = rawJson?.response;
    const xVerifyHeader = req.headers.get('x-verify');

    const isValid = verifyPhonePeWebhookChecksum(
      base64Response,
      xVerifyHeader,
      process.env.PHONEPE_SALT_KEY!,
      process.env.PHONEPE_SALT_INDEX || '1'
    );

    if (!isValid) {
      return NextResponse.json({ error: 'Invalid X-VERIFY checksum' }, { status: 401 });
    }

    // Decode the inner Base64 JSON payload
    const decodedString = Buffer.from(base64Response, 'base64').toString('utf8');
    const event = JSON.parse(decodedString);

    if (event.code === 'PAYMENT_SUCCESS') {
      const txnId = event.data.merchantTransactionId;
      const utr = event.data.paymentInstrument?.utr;
      console.log(`PhonePe payment verified for ${txnId} (UTR: ${utr})`);
    }

    return NextResponse.json({ status: 'OK' }, { status: 200 });
  } catch (error) {
    return NextResponse.json({ error: 'Malformed PhonePe callback' }, { status: 400 });
  }
}

3. Verifying PhonePe v2 Webhook Authorization Headers (SHA256 Basic Credentials)

If your merchant account is onboarded on PhonePe PG v2 (Standard Checkout with Dashboard-configured Webhook Username and Password), PhonePe also sends an Authorization header containing the hex-encoded SHA-256 hash of username:password. Always validate crypto.createHash('sha256').update(`${username}:${password}`).digest('hex') against req.headers.get('authorization') when using v2 webhooks.

phonepe-v2-auth-header.ts
typescript
import crypto from 'crypto';

export function verifyPhonePeV2AuthHeader(
  authHeader: string | null,
  webhookUsername: string,
  webhookPassword: string
): boolean {
  if (!authHeader) return false;
  const cleanHeader = authHeader.replace(/^Bearer\s+/i, '').trim();
  const expectedHash = crypto
    .createHash('sha256')
    .update(`${webhookUsername}:${webhookPassword}`, 'utf8')
    .digest('hex');
  return cleanHeader.toLowerCase() === expectedHash.toLowerCase();
}

Pre-Deployment Verification Checklist

  • Use crypto.createHash('sha256') (plain SHA-256), never crypto.createHmac('sha256').
  • Include '/pg/v1/pay' in the hash string for outgoing payment creation, but EXCLUDE any URL path when verifying incoming S2S webhook callbacks.
  • Append '###' + saltIndex (e.g., '###1') to the lowercase hex digest.
  • Ensure amount in the PhonePe payload is passed in integer paise (multiply INR by 100).
India's First & Only Developer PaaS

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 PhonePe return 400 BAD_REQUEST Checksum verification failed on /pg/v1/pay?

Ensure you Base64-encode the JSON string first, send `{ "request": base64Body }` as the HTTP body, and compute X-VERIFY as `SHA256(base64Body + "/pg/v1/pay" + saltKey) + "###" + saltIndex` using standard SHA-256 (not HMAC).

How is PhonePe's S2S webhook X-VERIFY different from the Pay API X-VERIFY?

In the S2S webhook callback, PhonePe hashes only `base64Response + saltKey` without any API endpoint path in the middle, followed by `###` + saltIndex.

What are the official PhonePe UAT Sandbox test credentials for checksum debugging?

Always verify your saltKey and saltIndex against the PhonePe Business Developer documentation for your specific UAT merchant ID, as UAT keys rotate periodically.

Primary Upstream References & Specifications

Keep Debugging

Related Guides

Browse all 30 guides →