Verify Paystack webhooks
The x-paystack-signature header lets you confirm that a webhook came from Paystack and wasn't changed on the way. It holds a hex HMAC-SHA512 of the raw request body, keyed with your Paystack secret key, the same key you use for API calls, so there's no separate webhook secret to set up for this header and no timestamp in what's signed. Paystack's Node, Python and Ruby SDKs have no verification helper, so you compute it yourself.
The facts
{raw body} The request body exactly as sent, with no timestamp. Re-serialised JSON can fail.
Recompute an HMAC-SHA512 of the raw body with your secret key, and compare Paystack webhook secret
x-paystack-signature is keyed with your Paystack secret key, the same key you use for API calls. You don't create a separate webhook secret for this header. Keep it in an environment variable, not in source code.
- In the dashboard: go to Settings, then the API Keys & Webhooks tab. Click the eye icon beside a secret key and enter your account password to view it.
- Test and live: each mode has its own secret key, so use the key for the mode that sent the event.
- Format: a test secret key starts with
sk_test_. - Shared with the API: the key that signs webhooks also authorizes API calls, so anyone who gets it can do both. Keep it out of client code and logs.
- Rotation: generate a new secret key from the same tab and choose when the old one expires. Paystack's support article doesn't say which key signs in between, so accept either until the old key expires.
- Newer header: samples Paystack added to its docs code on 2 November 2026 verify a
Paystack-Signatureheader (t=<unix seconds>,v1=<key id>:<hex>) with a dedicatedwhsec_secret, over{t}.{raw body}. Check which header your deliveries carry. The code on this page is forx-paystack-signature.
Source: Paystack docs ↗
Code
// Generated with: paystack-webhooks skill
// https://github.com/hookdeck/webhook-skills
require('dotenv').config();
const express = require('express');
const crypto = require('crypto');
const app = express();
/**
* Verify a Paystack webhook signature.
*
* Paystack signs the RAW request body with HMAC-SHA512 (hex) using your secret
* key and sends it in the `x-paystack-signature` header. The official SDKs have
* no verification helper, so we recompute the HMAC and compare it in constant
* time.
*
* @param {Buffer|string} rawBody - Raw request body (NOT parsed JSON)
* @param {string} signature - Value of the x-paystack-signature header
* @param {string} secret - Paystack secret key (sk_test_… / sk_live_…)
* @returns {boolean} Whether the signature is valid
*/
function verifyPaystackWebhook(rawBody, signature, secret) {
if (!signature) {
return false;
}
const expected = crypto
.createHmac('sha512', secret)
.update(rawBody) // raw bytes/string, NOT parsed JSON
.digest('hex');
try {
return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected));
} catch {
// Different lengths throw — treat as invalid.
return false;
}
}
// Paystack webhook endpoint - must use the raw body for signature verification
app.post('/webhooks/paystack',
express.raw({ type: 'application/json' }),
async (req, res) => {
const signature = req.headers['x-paystack-signature'];
// Verify webhook signature BEFORE parsing the body
if (!verifyPaystackWebhook(req.body, signature, process.env.PAYSTACK_SECRET_KEY)) {
console.error('Webhook signature verification failed');
return res.status(400).send('Invalid signature');
}
// Parse the payload only after verification succeeds
const payload = JSON.parse(req.body.toString());
const { event, data } = payload;
console.log(`Received ${event} event`);
// Acknowledge immediately (respond 200 fast), then process asynchronously.
// Paystack's request timeout is 30s and any non-200 triggers retries.
res.status(200).send('OK');
// The event type is in the body's `event` field, not a header.
switch (event) {
case 'charge.success':
console.log(`Charge succeeded: ${data.reference} (${data.amount} ${data.currency})`);
// Your code: Re-verify via GET /transaction/verify/:reference, then fulfil.
break;
case 'transfer.success':
console.log(`Transfer succeeded: ${data.reference} (${data.transfer_code})`);
// Your code: Mark the payout complete, notify the recipient.
break;
case 'transfer.failed':
console.log(`Transfer failed: ${data.reference} (${data.transfer_code})`);
// Your code: Alert ops, retry the payout, re-credit the balance.
break;
case 'transfer.reversed':
console.log(`Transfer reversed: ${data.reference} (${data.transfer_code})`);
// Your code: Reconcile the ledger.
break;
case 'refund.processed':
console.log(`Refund processed for transaction: ${data.transaction_reference}`);
// Your code: Update your ledger, notify the customer.
break;
case 'subscription.create':
console.log(`Subscription created: ${data.subscription_code}`);
// Your code: Provision the plan, start the billing cycle.
break;
case 'subscription.disable':
console.log(`Subscription disabled: ${data.subscription_code}`);
// Your code: Revoke access, offboard the customer.
break;
case 'invoice.create':
console.log(`Invoice created: ${data.invoice_code}`);
// Your code: Notify the customer of the upcoming charge.
break;
case 'invoice.update':
console.log(`Invoice updated: ${data.invoice_code} (paid: ${data.paid})`);
// Your code: Reconcile the charge result.
break;
case 'invoice.payment_failed':
console.log(`Invoice payment failed: ${data.invoice_code}`);
// Your code: Start dunning, retry, notify the customer.
break;
case 'charge.dispute.create':
console.log(`Dispute opened: ${data.id}`);
// Your code: Gather evidence and respond to the dispute.
break;
default:
console.log(`Unhandled event: ${event}`);
}
}
);
// Health check endpoint
app.get('/health', (req, res) => {
res.json({ status: 'ok' });
});
// Export app for testing
module.exports = { app, verifyPaystackWebhook };
// Start server only when run directly (not when imported for testing)
if (require.main === module) {
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
console.log(`Webhook endpoint: POST http://localhost:${PORT}/webhooks/paystack`);
});
} // Generated with: paystack-webhooks skill
// https://github.com/hookdeck/webhook-skills
import { NextRequest, NextResponse } from 'next/server';
import crypto from 'crypto';
/**
* Verify a Paystack webhook signature.
*
* Paystack signs the RAW request body with HMAC-SHA512 (hex) using your secret
* key and sends it in the `x-paystack-signature` header. The official SDKs have
* no verification helper, so we recompute the HMAC and compare it in constant
* time.
*/
export function verifyPaystackWebhook(
rawBody: string,
signature: string | null,
secret: string
): boolean {
if (!signature) {
return false;
}
const expected = crypto
.createHmac('sha512', secret)
.update(rawBody) // raw string, NOT parsed JSON
.digest('hex');
try {
return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected));
} catch {
// Different lengths throw — treat as invalid.
return false;
}
}
export async function POST(request: NextRequest) {
// Read the RAW body for signature verification (do not parse first)
const rawBody = await request.text();
const signature = request.headers.get('x-paystack-signature');
// Verify the signature BEFORE parsing the body
if (!verifyPaystackWebhook(rawBody, signature, process.env.PAYSTACK_SECRET_KEY!)) {
console.error('Webhook signature verification failed');
return NextResponse.json({ error: 'Invalid signature' }, { status: 400 });
}
// Parse the payload only after verification succeeds
const payload = JSON.parse(rawBody);
const { event, data } = payload;
console.log(`Received ${event} event`);
// The event type is in the body's `event` field, not a header.
switch (event) {
case 'charge.success':
console.log(`Charge succeeded: ${data.reference} (${data.amount} ${data.currency})`);
// Your code: Re-verify via GET /transaction/verify/:reference, then fulfil.
break;
case 'transfer.success':
console.log(`Transfer succeeded: ${data.reference} (${data.transfer_code})`);
// Your code: Mark the payout complete, notify the recipient.
break;
case 'transfer.failed':
console.log(`Transfer failed: ${data.reference} (${data.transfer_code})`);
// Your code: Alert ops, retry the payout, re-credit the balance.
break;
case 'transfer.reversed':
console.log(`Transfer reversed: ${data.reference} (${data.transfer_code})`);
// Your code: Reconcile the ledger.
break;
case 'refund.processed':
console.log(`Refund processed for transaction: ${data.transaction_reference}`);
// Your code: Update your ledger, notify the customer.
break;
case 'subscription.create':
console.log(`Subscription created: ${data.subscription_code}`);
// Your code: Provision the plan, start the billing cycle.
break;
case 'subscription.disable':
console.log(`Subscription disabled: ${data.subscription_code}`);
// Your code: Revoke access, offboard the customer.
break;
case 'invoice.create':
console.log(`Invoice created: ${data.invoice_code}`);
// Your code: Notify the customer of the upcoming charge.
break;
case 'invoice.update':
console.log(`Invoice updated: ${data.invoice_code} (paid: ${data.paid})`);
// Your code: Reconcile the charge result.
break;
case 'invoice.payment_failed':
console.log(`Invoice payment failed: ${data.invoice_code}`);
// Your code: Start dunning, retry, notify the customer.
break;
case 'charge.dispute.create':
console.log(`Dispute opened: ${data.id}`);
// Your code: Gather evidence and respond to the dispute.
break;
default:
console.log(`Unhandled event: ${event}`);
}
// Return 200 to acknowledge receipt (Paystack retries non-200 responses)
return NextResponse.json({ received: true });
} # Generated with: paystack-webhooks skill
# https://github.com/hookdeck/webhook-skills
import os
import hmac
import hashlib
import json
from dotenv import load_dotenv
from fastapi import FastAPI, Request, HTTPException
load_dotenv()
app = FastAPI()
paystack_secret = os.environ.get("PAYSTACK_SECRET_KEY", "")
def verify_paystack_webhook(raw_body: bytes, signature_header: str, secret: str) -> bool:
"""Verify a Paystack webhook signature.
Paystack's SDKs have no webhook verification helper, so we verify manually:
HMAC-SHA512 (hex) over the RAW request body, keyed with your secret key,
compared against the x-paystack-signature header using a timing-safe compare.
"""
if not signature_header:
return False
expected_signature = hmac.new(
secret.encode("utf-8"),
raw_body, # raw bytes, NOT parsed JSON
hashlib.sha512,
).hexdigest()
return hmac.compare_digest(expected_signature, signature_header)
@app.post("/webhooks/paystack")
async def paystack_webhook(request: Request):
# Read the RAW body for signature verification (do not parse first)
raw_body = await request.body()
signature_header = request.headers.get("x-paystack-signature")
# Verify the signature BEFORE parsing the body
if not verify_paystack_webhook(raw_body, signature_header, paystack_secret):
raise HTTPException(status_code=400, detail="Invalid signature")
# Parse the payload only after verification succeeds
payload = json.loads(raw_body)
event = payload.get("event")
data = payload.get("data", {})
print(f"Received {event} event")
# The event type is in the body's `event` field, not a header.
if event == "charge.success":
print(f"Charge succeeded: {data.get('reference')} ({data.get('amount')} {data.get('currency')})")
# Your code: Re-verify via GET /transaction/verify/:reference, then fulfil.
elif event == "transfer.success":
print(f"Transfer succeeded: {data.get('reference')} ({data.get('transfer_code')})")
# Your code: Mark the payout complete, notify the recipient.
elif event == "transfer.failed":
print(f"Transfer failed: {data.get('reference')} ({data.get('transfer_code')})")
# Your code: Alert ops, retry the payout, re-credit the balance.
elif event == "transfer.reversed":
print(f"Transfer reversed: {data.get('reference')} ({data.get('transfer_code')})")
# Your code: Reconcile the ledger.
elif event == "refund.processed":
print(f"Refund processed for transaction: {data.get('transaction_reference')}")
# Your code: Update your ledger, notify the customer.
elif event == "subscription.create":
print(f"Subscription created: {data.get('subscription_code')}")
# Your code: Provision the plan, start the billing cycle.
elif event == "subscription.disable":
print(f"Subscription disabled: {data.get('subscription_code')}")
# Your code: Revoke access, offboard the customer.
elif event == "invoice.create":
print(f"Invoice created: {data.get('invoice_code')}")
# Your code: Notify the customer of the upcoming charge.
elif event == "invoice.update":
print(f"Invoice updated: {data.get('invoice_code')} (paid: {data.get('paid')})")
# Your code: Reconcile the charge result.
elif event == "invoice.payment_failed":
print(f"Invoice payment failed: {data.get('invoice_code')}")
# Your code: Start dunning, retry, notify the customer.
elif event == "charge.dispute.create":
print(f"Dispute opened: {data.get('id')}")
# Your code: Gather evidence and respond to the dispute.
else:
print(f"Unhandled event: {event}")
# Return 2xx to acknowledge receipt (Paystack retries non-200 responses)
return {"received": True}
@app.get("/health")
async def health():
return {"status": "ok"}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000) Or install the Paystack webhooks skill:
npx skills add hookdeck/webhook-skills --skill paystack-webhooks
Common failures
SHA-256 instead of SHA-512
Paystack's digest is HMAC-SHA512, 128 hex characters long. A 64-character digest means your code used SHA-256, and it won't match.
Body changed before verification
Hash the raw request body, before any parsing. Re-serialising parsed JSON can change the bytes. Paystack's Node sample captures req.rawBody for this reason.
Wrong or rotated secret key
Test and live modes have different secret keys. After you generate a new key, your old one stops working at the expiry you chose, so update your handler before then.
A delivery signed with Paystack-Signature
Paystack's samples also show a Paystack-Signature header with a whsec_ secret and a timestamp in the signed content. Code for x-paystack-signature can't verify that scheme.
Let Event Gateway verify Paystack signatures.
Event Gateway verifies the signature on each Paystack delivery before it reaches your service, then queues it and retries failures on your schedule.