🎉 PhaJay is service now. Get Started

v1
Verify Webhook Signature

Verify Webhook Signature

1. Overview

PhaJay signs every webhook with a shared secret (HMAC-SHA256) and sends the result in the X-Signature header. Your server can verify a callback with the same secretKey or devSecretKey you already use for API calls.

The signature is a keyed hash made with a secret that only you and PhaJay know. If your server computes the same value, the callback came from PhaJay and was not changed on the way.

The signature is attached to every POST sent to your registered Webhook URL.

2. How It Works

Your server must hash the exact bytes PhaJay sent, so read the raw request body before any JSON parsing.

  1. PhaJay serialises the payload once with JSON.stringify() (compact, no extra whitespace).
  2. PhaJay computes HMAC-SHA256 of those bytes using your signing key (see section 4).
  3. The result is Base64-encoded and sent in the X-Signature header. The same bytes are the request body.
  4. Your server reads the raw body and the X-Signature header.
  5. Your server computes the same HMAC with its copy of the key and compares the two values in constant time.
  6. Match: process the event and return HTTP 200. No match: return HTTP 401 and ignore the event.

3. Signing Algorithm Details

PropertyValue
AlgorithmHMAC-SHA256
KeysecretKey (KYC verified) or devSecretKey (not yet KYC verified)
Signed dataRaw request body bytes, exactly as sent
Payload serialisationJSON.stringify(payload) (compact)
Signature encodingBase64
HTTP header nameX-Signature
Content-Typeapplication/json

4. Which Key Signs Your Webhooks

The signing key depends on your KYC status, and it changes the moment KYC is approved.

Your accountSigning key
Not KYC verifieddevSecretKey
KYC verifiedsecretKey

These are the same keys you send in the secretkey header of API calls. Get them from your dashboard in the PhaJay Portal (opens in a new tab) or from support.

⚠️ When your account passes KYC, update the key in your webhook verifier at the same time. Until you do, every signature will fail, because PhaJay now signs with secretKey. A simple approach is to accept either key during the switch-over.

5. Verifying the Signature on Your Server

In every language the rule is the same: hash the raw body bytes, never a re-serialised copy of the parsed JSON. Re-serialising can reorder keys, change spacing or escape characters differently, and the signature will no longer match.

Node.js / Express

const crypto = require('crypto');
const express = require('express');
const app = express();
 
// Keep the raw bytes next to the parsed body
app.use(express.json({
  verify: (req, res, buf) => { req.rawBody = buf; },
}));
 
const SECRET_KEY = process.env.PHAJAY_SECRET_KEY; // secretKey (KYC) or devSecretKey
 
function isValidSignature(rawBody, signature, secret) {
  if (typeof signature !== 'string' || !signature) return false;
  const computed = crypto
    .createHmac('sha256', secret)
    .update(rawBody)
    .digest('base64');
  const a = Buffer.from(computed);
  const b = Buffer.from(signature);
  return a.length === b.length && crypto.timingSafeEqual(a, b);
}
 
app.post('/webhook', (req, res) => {
  const signature = req.headers['x-signature'];
  if (!isValidSignature(req.rawBody, signature, SECRET_KEY)) {
    return res.status(401).json({ message: 'Invalid signature' });
  }
 
  // Process the verified event
  console.log('Event:', req.body.status, req.body.transactionId);
  res.status(200).json({ message: 'OK' });
});

Python (Flask)

import base64, hashlib, hmac, os
from flask import Flask, request
 
app = Flask(__name__)
SECRET_KEY = os.environ['PHAJAY_SECRET_KEY']  # secretKey (KYC) or devSecretKey
 
def is_valid_signature(raw_body: bytes, signature: str, secret: str) -> bool:
    if not signature:
        return False
    digest = hmac.new(secret.encode(), raw_body, hashlib.sha256).digest()
    computed = base64.b64encode(digest).decode()
    return hmac.compare_digest(computed, signature)
 
@app.route('/webhook', methods=['POST'])
def webhook():
    raw_body = request.get_data()  # raw bytes, before JSON parsing
    signature = request.headers.get('X-Signature', '')
    if not is_valid_signature(raw_body, signature, SECRET_KEY):
        return {'message': 'Invalid signature'}, 401
 
    event = request.get_json()
    # process event ...
    return {'message': 'OK'}, 200

PHP

<?php
$secret    = getenv('PHAJAY_SECRET_KEY'); // secretKey (KYC) or devSecretKey
$rawBody   = file_get_contents('php://input');
$signature = $_SERVER['HTTP_X_SIGNATURE'] ?? '';
 
$computed = base64_encode(hash_hmac('sha256', $rawBody, $secret, true));
 
if ($signature === '' || !hash_equals($computed, $signature)) {
    http_response_code(401);
    echo json_encode(['message' => 'Invalid signature']);
    exit;
}
 
$event = json_decode($rawBody, true);
// process event ...
http_response_code(200);
echo json_encode(['message' => 'OK']);

6. Security Recommendations

  • Verify X-Signature before processing any webhook event, and reject the request when it is missing.
  • Keep the key in an environment variable or a secrets manager. Never hardcode it, commit it, or ship it in a browser or mobile app.
  • secretKey and devSecretKey are also your API credentials. Anyone holding the key can forge webhooks, so rotate it if it leaks.
  • Compare signatures in constant time (timingSafeEqual, compare_digest, hash_equals), not with ==.
  • Use HTTPS for your webhook endpoint.
  • Respond with HTTP 200 quickly (within 5 s) and process events asynchronously.
  • Implement idempotency: store processed transactionId values to avoid duplicate processing.
  • When verification fails, log the headers and the length of the body for debugging, but never log the key.

7. Troubleshooting Invalid Signature

Most failures come from the bytes being hashed, not from the key.

SymptomLikely causeFix
Signature never matchesYou hash JSON.stringify(req.body) or another re-serialised copyHash the raw body bytes (req.rawBody, request.get_data(), php://input)
Matches in code, fails in PostmanBody was beautified or has line breaks, or contains {{variables}}Paste compact one-line JSON, regenerate the signature after any edit
Fails right after KYC approvalPhaJay now signs with secretKey, your server still uses devSecretKeySwitch the key, or accept both during the change
Signature differs only for some payloadsNon-ASCII text (for example Lao) hashed with the wrong encodingHash the body as UTF-8 bytes, not a decoded string
Raw body is emptyContent-Type is not application/json, so the parser skipped itSend Content-Type: application/json

For further assistance contact info@phapay.com.


Last updated: 21 days ago