Verify Webhook
Verify the integrity of webhook requests using the signature header.
Overview
To ensure the integrity of webhook data, every webhook request includes a digital signature in the header. You should verify this signature using your Secret Key before processing the request.
Verification Steps
- Get the JSON payload from the request.
- Retrieve the
signaturefrom the request headers. - Alphabetically sort the payload by keys.
- Convert the sorted payload to a JSON string.
- Generate an HMAC-SHA256 signature using your Secret Key (from API Config) as the key.
- Compare your generated signature with the received signature.
Code Examples
- PHP
- Node.js
- Python
// Payload received from webhook
$payload = [
"status" => "failed",
"type" => "sale",
"transaction_id" => "A49dfkqvw",
// ... other fields
];
// Fetch API Secret
$apiSecret = getenv('API_SECRET') ?: 'default_secret';
// Received signature
$receivedSignature = $_SERVER['HTTP_SIGNATURE']; // Adjust based on your header name
// Step 1: Sort payload
ksort($payload);
// Step 2: Convert to JSON
$payloadJson = json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
// Step 3: Generate HMAC
$generatedSignature = hash_hmac('sha256', $payloadJson, $apiSecret);
// Step 4: Verify
if (hash_equals($generatedSignature, $receivedSignature)) {
echo "Signature is valid!";
} else {
echo "Signature is invalid!";
}
const crypto = require('crypto');
// Payload received
let payload = { ... };
// Config
const apiSecret = process.env.API_SECRET;
const receivedSignature = req.headers['signature'];
// Step 1: Sort payload
const sortedPayload = Object.keys(payload).sort().reduce((obj, key) => {
obj[key] = payload[key];
return obj;
}, {});
// Step 2: Convert to JSON
const payloadJson = JSON.stringify(sortedPayload);
// Step 3: Generate HMAC
const generatedSignature = crypto.createHmac('sha256', apiSecret)
.update(payloadJson)
.digest('hex');
// Step 4: Verify
if (generatedSignature === receivedSignature) {
console.log("Valid");
} else {
console.log("Invalid");
}
import hmac
import hashlib
import json
import os
# Config
api_secret = os.getenv('API_SECRET')
received_signature = request.headers.get('signature')
# Step 1: Sort payload
sorted_payload = dict(sorted(payload.items()))
# Step 2: Convert to JSON (ensure separators are correct for standard JSON)
payload_json = json.dumps(sorted_payload, separators=(',', ':'))
# Step 3: Generate HMAC
generated_signature = hmac.new(
api_secret.encode('utf-8'),
payload_json.encode('utf-8'),
hashlib.sha256
).hexdigest()
# Step 4: Verify
if hmac.compare_digest(generated_signature, received_signature):
print("Valid")
else:
print("Invalid")
Important Notes
JSON Formatting
Ensure you use standard JSON formatting with no extra spaces when generating the signature string (e.g., in Python use separators=(',', ':')).