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.
- PhaJay serialises the payload once with
JSON.stringify()(compact, no extra whitespace). - PhaJay computes HMAC-SHA256 of those bytes using your signing key (see section 4).
- The result is Base64-encoded and sent in the
X-Signatureheader. The same bytes are the request body. - Your server reads the raw body and the
X-Signatureheader. - Your server computes the same HMAC with its copy of the key and compares the two values in constant time.
- Match: process the event and return HTTP
200. No match: return HTTP401and ignore the event.
3. Signing Algorithm Details
| Property | Value |
|---|---|
| Algorithm | HMAC-SHA256 |
| Key | secretKey (KYC verified) or devSecretKey (not yet KYC verified) |
| Signed data | Raw request body bytes, exactly as sent |
| Payload serialisation | JSON.stringify(payload) (compact) |
| Signature encoding | Base64 |
| HTTP header name | X-Signature |
| Content-Type | application/json |
4. Which Key Signs Your Webhooks
The signing key depends on your KYC status, and it changes the moment KYC is approved.
| Your account | Signing key |
|---|---|
| Not KYC verified | devSecretKey |
| KYC verified | secretKey |
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'}, 200PHP
<?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-Signaturebefore 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.
secretKeyanddevSecretKeyare 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
200quickly (within 5 s) and process events asynchronously. - Implement idempotency: store processed
transactionIdvalues 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.
| Symptom | Likely cause | Fix |
|---|---|---|
| Signature never matches | You hash JSON.stringify(req.body) or another re-serialised copy | Hash the raw body bytes (req.rawBody, request.get_data(), php://input) |
| Matches in code, fails in Postman | Body was beautified or has line breaks, or contains {{variables}} | Paste compact one-line JSON, regenerate the signature after any edit |
| Fails right after KYC approval | PhaJay now signs with secretKey, your server still uses devSecretKey | Switch the key, or accept both during the change |
| Signature differs only for some payloads | Non-ASCII text (for example Lao) hashed with the wrong encoding | Hash the body as UTF-8 bytes, not a decoded string |
| Raw body is empty | Content-Type is not application/json, so the parser skipped it | Send Content-Type: application/json |
For further assistance contact info@phapay.com.
Last updated: 21 days ago