Sign in

Developer Tools

Webhooks

View as Markdown

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": {}
}
FieldTypeDescription
eventstringEvent name, such as charge.success or refund.processed.
dataobjectEvent-specific resource payload. Its structure depends on the event type.

Copy linkHow to set up and verify webhooks

  1. Create a public POST endpoint
    Add a server endpoint that accepts JSON and returns 200 OK quickly.
  2. Add the endpoint in the Paystack Dashboard
    Go to Developers > API configuration and save your webhook URL.
  3. Verify the signature before processing the event
    Webhooks signed with a signing secret carry a Paystack-Signature header. 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 the X-Paystack-Signature header. This header is deprecated. If your webhooks don't carry Paystack-Signature yet, generate a signing secret on the Dashboard and keep verifying X-Paystack-Signature until they do. See X-Paystack-Signature (deprecated).
  4. Allowlist Paystack IP addresses if required by your infrastructure
    Restrict access to the three published webhook IP addresses where possible.
  5. Acknowledge immediately
    Return 200 OK before starting long-running work such as database updates, emails, or provisioning.
  6. Process the event by event name
    Switch on event and handle the resource inside data.
  7. Test delivery
    Trigger test payments and confirm that your endpoint receives JSON correctly, verifies the signature, and returns 200 OK.
  8. 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
  • t is the time Paystack signed the webhook, in unix seconds.
  • Each v1 is <key id>:<signature>. The key id starts with whk_. 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

  1. Read the raw request body as bytes, before any JSON parsing.
  2. Split the header on ,. Take the one t value and every v1 value. Split each v1 value on its first : into the key id and the signature.
  3. Reject the webhook if t is more than 300 seconds before or after your server's time. This stops an old webhook from being replayed.
  4. Compute HMAC-SHA512 over t, then ., then the raw body, using your whole signing secret (whsec_ included) as the key.
  5. Compare your result with each v1 signature using a constant-time comparison. The webhook is genuine if any of them matches.
  6. Return 401 if nothing matches. If it matches, return 200 quickly, 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

  1. Revoke it on the Dashboard. It stops signing within a minute, with no overlap.
  2. 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-Signature header. Your integration has no active signing secret for this mode. Generate one on the Dashboard. Until the header appears, verify X-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.

  1. Start your server. This example assumes it listens on port 8080.
  2. Start the tunnel:
    ngrok http 8080
    
  3. Copy the HTTPS forwarding URL the tunnel prints and add your webhook route, for example https://<your-subdomain>.ngrok-free.app/webhooks/paystack.
  4. Save that URL as your test webhook URL on the API configuration page.
  5. Make a payment with your test keys and the test payment details for your market.
  6. 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.75
  • 52.49.173.169
  • 52.214.14.220

These IP addresses apply to both test and live environments.

Copy linkEvent types

EventDescription
charge.dispute.createA dispute was logged against your business.
charge.dispute.remindA logged dispute has not been resolved.
charge.dispute.resolveA dispute has been resolved.
charge.successA successful charge was made.
customeridentification.failedCustomer ID validation failed.
customeridentification.successCustomer ID validation succeeded.
dedicatedaccount.assign.failedA Dedicated Virtual Account could not be assigned.
dedicatedaccount.assign.successA Dedicated Virtual Account was successfully assigned.
invoice.createAn invoice was created for a subscription.
invoice.payment_failedAn invoice payment failed.
invoice.updateAn invoice was updated after a charge attempt.
paymentrequest.pendingA payment request was sent to a customer.
paymentrequest.successA payment request was paid.
refund.failedA refund could not be processed.
refund.pendingA refund was initiated and is waiting for processor response.
refund.processingA refund has been received by the processor.
refund.processedA refund has been processed successfully.
subscription.createA subscription was created.
subscription.disableA subscription was disabled.
subscription.expiring_cardsInformation about subscriptions with cards expiring that month.
subscription.not_renewA subscription changed to non-renewing.
transfer.failedA transfer failed.
transfer.successA transfer completed successfully.
transfer.reversedA 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=true first 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.

Was this page helpful?