Developer Tools
Webhooks
In a nutshell
Webhook event types, payload structure, allowlisted IPs, and the steps required to set up and verify Paystack webhooks.
Copy linkOverview
Paystack webhooks are POST requests sent to your server when the status of an API request changes. They are the recommended way to keep your backend synchronized with asynchronous payment activity because callbacks and client-side flows can fail when the customer’s device goes offline or the network is interrupted.
Your webhook endpoint should parse a JSON request body and return 200 OK. In live mode, failed webhook deliveries are retried every 3 minutes for the first 4 tries, then hourly for up to 72 hours. In test mode, failed deliveries are retried hourly for 10 hours, with a 30-second timeout per attempt.
Copy linkEvent object structure
Webhook payloads are JSON objects with this top-level shape:
{
"event": "charge.success",
"data": {}
}
| Field | Type | Description |
|---|---|---|
event | string | Event name, such as charge.success or refund.processed. |
data | object | Event-specific resource payload. Its structure depends on the event type. |
Copy linkHow to set up and verify webhooks
- Create a public
POSTendpoint
Add a server endpoint that accepts JSON and returns200 OKquickly. - Add the endpoint in the Paystack Dashboard
Go to Developers > API configuration and save your webhook URL. - Verify the signature before processing the event
Webhooks signed with a signing secret carry aPaystack-Signatureheader. Check it on the raw request body before you trust the event. See Verify webhook signatures.
While your integration has a secret key, webhooks also carry theX-Paystack-Signatureheader. This header is deprecated. If your webhooks don't carryPaystack-Signatureyet, generate a signing secret on the Dashboard and keep verifyingX-Paystack-Signatureuntil they do. See X-Paystack-Signature (deprecated). - Allowlist Paystack IP addresses if required by your infrastructure
Restrict access to the three published webhook IP addresses where possible. - Acknowledge immediately
Return200 OKbefore starting long-running work such as database updates, emails, or provisioning. - Process the event by event name
Switch oneventand handle the resource insidedata. - Test delivery
Trigger test payments and confirm that your endpoint receives JSON correctly, verifies the signature, and returns200 OK. - Check common deployment requirements
- Use a publicly reachable URL.
- Do not use localhost. To test on your machine, see Receive webhooks locally.
- If you use
.htaccess, keep the expected trailing slash behavior consistent. - If Paystack does not receive
200 OK, retries continue according to the environment schedule.
Copy linkVerify webhook signatures
Copy linkPaystack-Signature
Paystack signs test and live webhooks with separate signing secrets. Your webhooks carry this header once your integration has an active signing secret for that mode. The secret starts with whsec_. You generate, show, rotate, and revoke it on the Paystack Dashboard under Developers > API configuration > Webhook signing secret.
The header looks like this:
Paystack-Signature: t=1760270400,v1=whk_3f9a1c2e:9d1b...e47a
tis the time Paystack signed the webhook, in unix seconds.- Each
v1is<key id>:<signature>. The key id starts withwhk_. The signature is a lower-case hex HMAC-SHA512, 128 characters long. - There is usually one
v1. While you rotate your secret there are two, one per secret. Other fields may be added later, so ignore any you don't recognise.
If your webhooks don't carry this header, your integration has no active signing secret for this mode. Generate one on the Dashboard. Until the header appears, keep your secret key and verify X-Paystack-Signature.
Copy linkHow to verify it
- Read the raw request body as bytes, before any JSON parsing.
- Split the header on
,. Take the onetvalue and everyv1value. Split eachv1value on its first:into the key id and the signature. - Reject the webhook if
tis more than 300 seconds before or after your server's time. This stops an old webhook from being replayed. - Compute HMAC-SHA512 over
t, then., then the raw body, using your whole signing secret (whsec_included) as the key. - Compare your result with each
v1signature using a constant-time comparison. The webhook is genuine if any of them matches. - Return
401if nothing matches. If it matches, return200quickly, then process the event.
Use the body exactly as received. If your framework parses the JSON and you serialise it again, spacing, number formats such as 1.50, and escaped characters can change, and the signature no longer matches.
A retried or resent webhook is signed again with a new t, so the 300-second window doesn't reject legitimate retries.
Copy linkCode
Each example reads the raw body, checks every v1, compares in constant time and allows 300 seconds of clock difference. secrets is a list so you can hold your old and new secret while you rotate.
const crypto = require('crypto');
const express = require('express');
const TOLERANCE_SECONDS = 300;
// Returns the key id (kid) of the signature that matched, or null.
function verifyPaystackSignature(rawBody, header, secrets, now = Math.floor(Date.now() / 1000)) {
if (!Buffer.isBuffer(rawBody) || typeof header !== 'string') return null;
let t = null;
const entries = [];
for (const part of header.split(',')) {
const i = part.indexOf('=');
if (i === -1) continue;
const key = part.slice(0, i).trim();
const value = part.slice(i + 1).trim();
if (key === 't') {
if (t !== null || !/^[0-9]+$/.test(value)) return null;
t = Number(value);
} else if (key === 'v1') {
const j = value.indexOf(':');
if (j !== -1) entries.push({ kid: value.slice(0, j), hex: value.slice(j + 1) });
}
}
if (t === null || entries.length === 0) return null;
if (Math.abs(now - t) > TOLERANCE_SECONDS) return null;
for (const secret of secrets) {
const expected = crypto.createHmac('sha512', secret).update(`${t}.`).update(rawBody).digest();
for (const { kid, hex } of entries) {
if (!/^[0-9a-f]{128}$/.test(hex)) continue;
if (crypto.timingSafeEqual(expected, Buffer.from(hex, 'hex'))) return kid;
}
}
return null;
}
const app = express();
// express.raw keeps req.body as the exact bytes Paystack sent. Register this route before any
// app.use(express.json()): a JSON parser that runs first consumes the body and every check fails.
app.post('/webhooks/paystack', express.raw({ type: 'application/json' }), (req, res) => {
const secret = process.env.PAYSTACK_WEBHOOK_SECRET; // whsec_...
if (!secret) return res.sendStatus(500);
const kid = verifyPaystackSignature(req.body, req.get('paystack-signature'), [secret]);
if (!kid) return res.sendStatus(401);
res.sendStatus(200);
const event = JSON.parse(req.body.toString('utf8'));
// handle event.event and event.data
});
import hashlib
import hmac
import json
import os
import re
import time
from flask import Flask, abort, request
TOLERANCE_SECONDS = 300
DIGITS = re.compile(r'[0-9]+')
HEX_SHA512 = re.compile(r'[0-9a-f]{128}')
def verify_paystack_signature(raw_body, header, secrets, now=None):
"""Return the key id (kid) of the signature that matched, or None."""
if not isinstance(raw_body, bytes) or not header:
return None
t = None
entries = []
for part in header.split(','):
key, sep, value = part.partition('=')
if not sep:
continue
key, value = key.strip(), value.strip()
if key == 't':
if t is not None or not DIGITS.fullmatch(value):
return None
t = int(value)
elif key == 'v1':
kid, sep, hex_sig = value.partition(':')
if sep:
entries.append((kid, hex_sig))
if t is None or not entries:
return None
now = int(time.time()) if now is None else now
if abs(now - t) > TOLERANCE_SECONDS:
return None
for secret in secrets:
message = str(t).encode('ascii') + b'.' + raw_body
expected = hmac.new(secret.encode('utf-8'), message, hashlib.sha512).hexdigest()
for kid, hex_sig in entries:
if HEX_SHA512.fullmatch(hex_sig) and hmac.compare_digest(expected, hex_sig):
return kid
return None
app = Flask(__name__)
@app.post('/webhooks/paystack')
def paystack_webhook():
raw_body = request.get_data() # the exact bytes Paystack sent
secret = os.environ.get('PAYSTACK_WEBHOOK_SECRET') # whsec_...
if not secret:
abort(500)
if verify_paystack_signature(raw_body, request.headers.get('Paystack-Signature'), [secret]) is None:
abort(401)
event = json.loads(raw_body)
# handle event['event'] and event['data']
return '', 200
<?php
const PAYSTACK_TOLERANCE_SECONDS = 300;
// Returns the key id (kid) of the signature that matched, or null.
function verifyPaystackSignature(string $rawBody, ?string $header, array $secrets, ?int $now = null): ?string
{
if ($header === null || $header === '') {
return null;
}
$t = null;
$entries = [];
foreach (explode(',', $header) as $part) {
$pair = explode('=', $part, 2);
if (count($pair) !== 2) {
continue;
}
[$key, $value] = array_map('trim', $pair);
if ($key === 't') {
if ($t !== null || !preg_match('/^[0-9]+$/D', $value)) {
return null;
}
$t = (int) $value;
} elseif ($key === 'v1') {
$kidAndHex = explode(':', $value, 2);
if (count($kidAndHex) === 2) {
$entries[] = $kidAndHex;
}
}
}
if ($t === null || count($entries) === 0) {
return null;
}
$now = $now ?? time();
if (abs($now - $t) > PAYSTACK_TOLERANCE_SECONDS) {
return null;
}
foreach ($secrets as $secret) {
$expected = hash_hmac('sha512', $t . '.' . $rawBody, $secret);
foreach ($entries as [$kid, $hex]) {
if (preg_match('/^[0-9a-f]{128}$/D', $hex) && hash_equals($expected, $hex)) {
return $kid;
}
}
}
return null;
}
$rawBody = file_get_contents('php://input'); // the exact bytes Paystack sent
$secret = getenv('PAYSTACK_WEBHOOK_SECRET'); // whsec_...
$header = $_SERVER['HTTP_PAYSTACK_SIGNATURE'] ?? null;
if (!$secret) {
http_response_code(500);
exit;
}
if (verifyPaystackSignature($rawBody, $header, [$secret]) === null) {
http_response_code(401);
exit;
}
http_response_code(200);
$event = json_decode($rawBody, true);
// handle $event['event'] and $event['data']
Copy linkRotating your signing secret
To replace your signing secret, rotate it on the Dashboard and choose how long the current secret keeps working: 1 hour, 24 hours, 3 days, or 7 days. During that overlap, every webhook carries two v1 signatures, one for each secret. Deploy the new secret to your server before the overlap ends.
Copy linkIf your signing secret leaks
- Revoke it on the Dashboard. It stops signing within a minute, with no overlap.
- Generate a new secret and deploy it to your server. Remove the leaked secret from your server.
Webhooks that fail your check in between are retried, and each retry is signed with the new secret.
Copy linkX-Paystack-Signature (deprecated)
While your integration has a secret key, webhooks also carry X-Paystack-Signature. This header is deprecated: use Paystack-Signature once your webhooks carry it. If you keep your secret key, you can keep verifying X-Paystack-Signature as you do today.
Warning
If your webhooks don't carry Paystack-Signature yet, don't delete your secret key: Paystack will stop sending you webhooks. Before you delete it, confirm that your webhooks carry Paystack-Signature and that your endpoint verifies it. After you delete your secret key, X-Paystack-Signature is no longer sent.
X-Paystack-Signature is a hex HMAC-SHA512 of the raw request body, keyed with your secret key. It has no timestamp. To verify it:
const crypto = require('crypto');
const express = require('express');
const app = express();
// express.raw keeps req.body as the exact bytes Paystack sent.
app.post('/webhooks/paystack', express.raw({ type: 'application/json' }), (req, res) => {
const expected = crypto.createHmac('sha512', process.env.PAYSTACK_SECRET_KEY).update(req.body).digest();
const received = req.get('x-paystack-signature') || '';
const valid =
/^[0-9a-f]{128}$/.test(received) && crypto.timingSafeEqual(expected, Buffer.from(received, 'hex'));
if (!valid) return res.sendStatus(401);
res.sendStatus(200);
// handle JSON.parse(req.body.toString('utf8'))
});
Copy linkTroubleshooting
- The signature never matches. You're probably hashing a parsed and re-serialised body. Use the raw bytes (
express.raw,request.get_data(),php://input). Use the whole secret,whsec_included, and the test secret for test webhooks. - The timestamp is too old. Check that your server clock is synced (NTP).
- There's no
Paystack-Signatureheader. Your integration has no active signing secret for this mode. Generate one on the Dashboard. Until the header appears, verifyX-Paystack-Signature.
Copy linkReceive webhooks locally
Paystack can't send webhooks to localhost. To test your webhook handler on your machine, expose your local server through a tunnel such as ngrok or cloudflared.
- Start your server. This example assumes it listens on port 8080.
- Start the tunnel:
ngrok http 8080 - Copy the HTTPS forwarding URL the tunnel prints and add your webhook route, for example
https://<your-subdomain>.ngrok-free.app/webhooks/paystack. - Save that URL as your test webhook URL on the API configuration page.
- Make a payment with your test keys and the test payment details for your market.
- Check that your handler verifies the signature and returns
200 OK. Then call Verify Transaction for the same reference and confirm it matches the event you received.
Most tunnel URLs change each time you restart the tunnel, so update your test webhook URL when that happens. Your live webhook URL is a separate setting, so this doesn't affect live webhooks.
Copy linkIP allowlist
Paystack sends webhook requests from these IP addresses:
52.31.139.7552.49.173.16952.214.14.220
These IP addresses apply to both test and live environments.
Copy linkEvent types
| Event | Description |
|---|---|
charge.dispute.create | A dispute was logged against your business. |
charge.dispute.remind | A logged dispute has not been resolved. |
charge.dispute.resolve | A dispute has been resolved. |
charge.success | A successful charge was made. |
customeridentification.failed | Customer ID validation failed. |
customeridentification.success | Customer ID validation succeeded. |
dedicatedaccount.assign.failed | A Dedicated Virtual Account could not be assigned. |
dedicatedaccount.assign.success | A Dedicated Virtual Account was successfully assigned. |
invoice.create | An invoice was created for a subscription. |
invoice.payment_failed | An invoice payment failed. |
invoice.update | An invoice was updated after a charge attempt. |
paymentrequest.pending | A payment request was sent to a customer. |
paymentrequest.success | A payment request was paid. |
refund.failed | A refund could not be processed. |
refund.pending | A refund was initiated and is waiting for processor response. |
refund.processing | A refund has been received by the processor. |
refund.processed | A refund has been processed successfully. |
subscription.create | A subscription was created. |
subscription.disable | A subscription was disabled. |
subscription.expiring_cards | Information about subscriptions with cards expiring that month. |
subscription.not_renew | A subscription changed to non-renewing. |
transfer.failed | A transfer failed. |
transfer.success | A transfer completed successfully. |
transfer.reversed | A transfer was reversed. |
Copy linkInspecting and resending events
Every webhook delivery Paystack sends is logged as an event you can look up later. Use the Webhook Events API to check what was sent, confirm your endpoint's response, or recover from a delivery your server missed:
- List events to see recent deliveries, filtered by category, event type, status, resource id, or date.
- Look up an event by transaction id or event id when a customer reports a payment that didn't reach your webhook.
- Fetch a single event to see its full payload and the response your endpoint returned.
- Resend events by id, once you've fixed the issue on your end.
- Resend matching events to recover in bulk. Pass
preview=truefirst to confirm how many events match your filter before you resend them.
Resending isn't idempotent. If your endpoint already processed an event, resending it delivers a duplicate, so your handler must be able to ignore repeats.