Paystack Checkout: initialize, Popup or redirect, webhook, verify, refund

Accept cards, bank transfer, USSD and mobile money with Paystack: initialize on the server, open Popup or redirect, verify signed webhooks, confirm with the verify API and issue refunds.

Provider
Paystack
Level
Beginner
Stacks
Node.js (Express), Python (Django), PHP (Laravel), React, Flutter
Code maturity
Sandbox-ready
Last verified
25 Nov 2026

Introduction

Paystack is a payment gateway used widely in Nigeria, Ghana, South Africa and Kenya. Its standard integration is a hosted checkout: your server creates ("initializes") a transaction, the customer pays in Paystack's Popup or on a Paystack-hosted page, and your server confirms the result through a signed webhook and the verify endpoint.

This guide builds that loop end-to-end in test mode, plus refunds. Paystack's base URL is the same for test and live — your keys decide the mode.

What Paystack Checkout does

  • POST https://api.paystack.co/transaction/initialize returns an authorization_url (hosted page), an access_code (for Popup and mobile SDKs) and a reference.
  • The customer chooses a channel (card, bank, bank transfer, USSD, QR, mobile money, and more — depending on your country and settings) and pays.
  • Paystack sends a charge.success webhook and, for redirect checkouts, sends the customer to your callback_url with ?reference=....
  • Your server calls GET /transaction/verify/:reference and checks data.status, data.amount and data.currency before giving value.

Countries and currencies

Paystack's API reference lists these currencies (amounts are always sent in the subunit):

  • NGN (kobo) — Nigeria
  • GHS (pesewa) — Ghana
  • ZAR (cent) — South Africa
  • KES (cent) — Kenya
  • USD (cent) — for businesses in Kenya and Nigeria
  • XOF — Côte d'Ivoire; the docs say XOF has no subunit but you must still multiply by 100 (fractions are ignored).

Which channels you get (for example mobile money in Ghana/Kenya, EFT or Capitec Pay in South Africa) depends on your business country and what Paystack has enabled on your account.

Payment methods

The channels parameter on initialize accepts: card, bank, apple_pay, ussd, qr, mobile_money, bank_transfer, eft, capitec_pay, payattitude. Leave it out to show everything enabled on your account.

Other Paystack products (subscriptions via plan, split payments via split_code/subaccount, transfers/payouts, dedicated virtual accounts) build on the same initialize/verify pattern but are outside this guide.

When to use Paystack Checkout

  • Your business is registered in Nigeria, Ghana, South Africa, Kenya or Côte d'Ivoire and you want cards plus local methods from one integration.
  • You want Paystack to handle the card form (PCI scope stays mostly with Paystack).
  • You want a fast integration: one server call, one front-end call, one webhook.

When not to use it

  • Your business is not registered in a Paystack country — you cannot onboard as a merchant.
  • You need a deep M-Pesa-only experience in Kenya with STK Push under your own Paybill — the Daraja API gives more control.
  • You need a fully custom card form — that means the Charge API and more compliance work.

Real-world scenarios

  • Nigerian online store: NGN checkout with cards, bank transfer and USSD; amount 500000 = ₦5,000.
  • Ghanaian SaaS: GHS card and mobile-money payments; recurring billing later via plans.
  • Mobile app (Flutter): the app asks your backend for an access_code, then opens the Paystack Flutter SDK.
  • Event tickets: initialize with metadata holding the ticket ids; fulfil only after the webhook plus verify agree.

Registration and onboarding

  • Create a Paystack account. You immediately get test keys (Settings → API Keys & Webhooks).
  • Build and test with test keys.
  • Complete business verification (KYC) in the dashboard to activate live mode and get live keys. Requirements differ by country and business type.
  • Set your live webhook URL and callback URL — test and live can use different URLs.

Warning: Activation documents and timelines vary by country and business type and are not a fixed public list. Check the Paystack dashboard for your country before planning a launch.

Test mode

There is no separate sandbox host: https://api.paystack.co serves both modes and the test secret key puts requests in test mode. Test transactions never move real money and are shown in the dashboard's test view.

Paystack publishes test cards (any future expiry; the docs show 11/27):

  • 4084 0840 8408 4081, CVV 408 — succeeds with no extra validation.
  • 5078 5078 5078 5078 12, CVV 081, PIN 1111 — succeeds after PIN.
  • 5060 6666 6666 6666 666, CVV 123, PIN 1234, OTP 123456 — PIN + OTP.
  • 4084 0800 0000 5408, CVV 001 — declined.
  • 4084 0800 0067 1803, CVV 180 — payment succeeds but refund fails (useful for refund testing).

Test mobile money: 055 123 498 7 (MTN Ghana) and +254 710 000 000 (M-Pesa) complete without PIN/OTP.

Credentials you need

  • Secret key — server only. Authorizes every API call (Authorization: Bearer <secret>). In the legacy scheme it also signs webhooks.
  • Public key — safe in browsers and apps. Used by the Flutter SDK's initialize(); Popup's resumeTransaction only needs the access_code.
  • Webhook signing secret (whsec_...) — used by the newer Paystack-Signature header (see the webhooks section).

Security: Paystack's docs are explicit: initialize from your server only. A secret key in a React or Flutter bundle can be extracted and used to read and refund your transactions.

Environment configuration

Keep keys in .env (git-ignored) and commit only a .env.example with placeholders. Use test keys locally and live keys only on the production server.

.env.example · Node.js (Express)

# Paystack — copy to .env; values from Dashboard > Settings > API Keys & Webhooks
PAYSTACK_SECRET_KEY=sk_test_replace_me
PAYSTACK_PUBLIC_KEY=pk_test_replace_me
# Signing secret for the Paystack-Signature header (whsec_...). Leave empty to use
# the legacy x-paystack-signature check (HMAC-SHA512 with the secret key).
PAYSTACK_WEBHOOK_SECRET=
# Where Paystack sends the customer back after a redirect checkout
PAYSTACK_CALLBACK_URL=http://localhost:3000/payments/paystack/return
PORT=3000

Authentication and shared helpers

Paystack uses a static bearer token: Authorization: Bearer <secret key>. There is no token exchange.

The module below wraps API calls and implements both webhook signature schemes from the official webhooks page:

  • Paystack-Signature (current): format t=<unix seconds>,v1=<key id>:<signature>. Compute HMAC-SHA512 over t + "." + rawBody with your whsec_ secret, reject if t is more than 300 seconds away from your clock, and compare (constant time) against every v1 value — several appear during secret rotation.
  • x-paystack-signature (legacy): HMAC-SHA512 of the raw body keyed with your secret key, hex-encoded, no timestamp.

paystack.mjs — API helper + signature checks (Node 18+) · Node.js (Express)

import crypto from "node:crypto";

const BASE = "https://api.paystack.co";

export async function paystack(method, path, body) {
  const res = await fetch(BASE + path, {
    method,
    headers: {
      Authorization: "Bearer " + process.env.PAYSTACK_SECRET_KEY,
      "Content-Type": "application/json",
    },
    body: body ? JSON.stringify(body) : undefined,
  });
  const json = await res.json().catch(() => ({}));
  if (!res.ok || json.status !== true) {
    throw new Error("Paystack " + path + " failed: " + (json.message || res.status));
  }
  return json.data;
}

// Current scheme: Paystack-Signature: t=<seconds>,v1=<keyId>:<hex sig>[,v1=...]
export function validPaystackSignature(rawBody, header, whsec) {
  let t = null;
  const sigs = [];
  for (const part of String(header || "").split(",")) {
    const i = part.indexOf("=");
    if (i === -1) continue;
    const k = part.slice(0, i).trim();
    const v = part.slice(i + 1).trim();
    if (k === "t") t = Number(v);
    if (k === "v1" && v.indexOf(":") > 0) sigs.push(v.slice(v.indexOf(":") + 1));
  }
  if (!Number.isInteger(t) || sigs.length === 0) return false;
  if (Math.abs(Math.floor(Date.now() / 1000) - t) > 300) return false;
  const expected = crypto.createHmac("sha512", whsec).update(t + ".").update(rawBody).digest();
  return sigs.some((hex) => /^[0-9a-f]{128}$/.test(hex)
    && crypto.timingSafeEqual(expected, Buffer.from(hex, "hex")));
}

// Legacy scheme: x-paystack-signature = hex(HMAC-SHA512(rawBody, secretKey))
export function validLegacySignature(rawBody, header, secretKey) {
  const expected = crypto.createHmac("sha512", secretKey).update(rawBody).digest("hex");
  const given = String(header || "");
  return given.length === expected.length
    && crypto.timingSafeEqual(Buffer.from(given), Buffer.from(expected));
}

Backend: initialize, webhook, verify, idempotent fulfilment

The server owns the money logic:

  • Initialize with the amount from YOUR order (in subunits) and your own unique reference (allowed characters: letters, digits, -, ., =).
  • Webhook: verify the signature over the raw body (mount the raw parser on this route before any JSON parser), answer 200 quickly, then re-verify with the API and fulfil once.
  • Return URL: the customer's redirect is a hint only — call verify there too.

The Node demo stores orders in a Map. In production use a database with a unique index on reference and a conditional update (UPDATE ... WHERE reference = ? AND status = 'pending') so two concurrent webhook deliveries cannot both fulfil.

server.mjs — Express (npm i express dotenv) · Node.js (Express)

import "dotenv/config";
import express from "express";
import crypto from "node:crypto";
import { paystack, validPaystackSignature, validLegacySignature } from "./paystack.mjs";

const app = express();
const orders = new Map(); // demo store: use a DB with unique(reference)

async function settle(reference) {
  const order = orders.get(reference);
  if (!order || order.status !== "pending") return order; // idempotent
  const tx = await paystack("GET", "/transaction/verify/" + encodeURIComponent(reference));
  if (tx.status === "success" && tx.amount === order.amountMinor && tx.currency === order.currency) {
    order.status = "paid"; // in SQL: UPDATE ... WHERE reference=? AND status='pending'
    order.paystackId = tx.id;
  } else if (["failed", "abandoned", "reversed"].includes(tx.status)) {
    order.status = tx.status;
  }
  return order;
}

// Webhook FIRST, with a raw body parser, so the signature is checked on exact bytes.
app.post("/webhooks/paystack", express.raw({ type: "application/json", limit: "1mb" }), (req, res) => {
  const ok = process.env.PAYSTACK_WEBHOOK_SECRET
    ? validPaystackSignature(req.body, req.get("Paystack-Signature"), process.env.PAYSTACK_WEBHOOK_SECRET)
    : validLegacySignature(req.body, req.get("x-paystack-signature"), process.env.PAYSTACK_SECRET_KEY);
  if (!ok) return res.sendStatus(401);
  res.sendStatus(200); // acknowledge, then process
  const event = JSON.parse(req.body.toString("utf8"));
  if (event.event === "charge.success") {
    settle(event.data.reference).catch((e) => console.error("settle failed", e.message));
  }
});

app.use(express.json({ limit: "50kb" }));

app.post("/api/checkout", async (req, res) => {
  // Price comes from your catalogue, never from the client.
  const order = { reference: "ord_" + crypto.randomUUID(), amountMinor: 500000, currency: "NGN", status: "pending" };
  const email = String(req.body.email || "").trim();
  if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) return res.status(400).json({ error: "Valid email required" });
  orders.set(order.reference, order);
  try {
    const data = await paystack("POST", "/transaction/initialize", {
      email, amount: String(order.amountMinor), currency: order.currency,
      reference: order.reference, callback_url: process.env.PAYSTACK_CALLBACK_URL,
      metadata: JSON.stringify({ orderRef: order.reference }),
    });
    res.json({ reference: data.reference, accessCode: data.access_code, authorizationUrl: data.authorization_url });
  } catch (e) {
    console.error(e.message);
    res.status(502).json({ error: "Could not start payment" });
  }
});

// Redirect checkout lands here with ?reference=... — verify, never trust the query string.
app.get("/payments/paystack/return", async (req, res) => {
  const order = await settle(String(req.query.reference || "")).catch(() => null);
  res.redirect("/orders/" + encodeURIComponent(req.query.reference || "") + "?status=" + (order ? order.status : "unknown"));
});

app.get("/api/orders/:ref", async (req, res) => {
  const order = await settle(req.params.ref).catch(() => orders.get(req.params.ref));
  if (!order) return res.sendStatus(404);
  res.json({ reference: order.reference, status: order.status });
});

app.listen(process.env.PORT || 3000);

payments/views.py — Django initialize + webhook (pip install requests) · Python (Django)

import hashlib, hmac, json, os, uuid
import requests
from django.db import transaction
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from .models import Order  # fields: reference (unique), amount_minor, currency, email, status

API = "https://api.paystack.co"
HEADERS = {"Authorization": "Bearer " + os.environ["PAYSTACK_SECRET_KEY"]}

@require_POST
def start_checkout(request):
    body = json.loads(request.body or b"{}")
    order = Order.objects.create(reference="ord_" + uuid.uuid4().hex, amount_minor=500000,
                                 currency="NGN", email=str(body.get("email", ""))[:254], status="pending")
    r = requests.post(API + "/transaction/initialize", headers=HEADERS, timeout=30, json={
        "email": order.email, "amount": str(order.amount_minor), "currency": order.currency,
        "reference": order.reference, "callback_url": os.environ["PAYSTACK_CALLBACK_URL"]})
    data = r.json()
    if r.status_code != 200 or not data.get("status"):
        return JsonResponse({"error": "Could not start payment"}, status=502)
    return JsonResponse({"accessCode": data["data"]["access_code"],
                         "authorizationUrl": data["data"]["authorization_url"], "reference": order.reference})

def settle(reference):
    tx = requests.get(API + "/transaction/verify/" + reference, headers=HEADERS, timeout=30).json().get("data") or {}
    with transaction.atomic():
        order = Order.objects.select_for_update().filter(reference=reference, status="pending").first()
        if order is None:
            return  # unknown or already settled: idempotent no-op
        if tx.get("status") == "success" and tx.get("amount") == order.amount_minor and tx.get("currency") == order.currency:
            order.status = "paid"
            order.save(update_fields=["status"])

@csrf_exempt
@require_POST
def paystack_webhook(request):
    raw = request.body  # exact bytes, before any JSON parsing
    expected = hmac.new(os.environ["PAYSTACK_SECRET_KEY"].encode(), raw, hashlib.sha512).hexdigest()
    if not hmac.compare_digest(expected, request.headers.get("x-paystack-signature", "")):
        return HttpResponse(status=401)
    event = json.loads(raw)
    if event.get("event") == "charge.success":
        settle(event["data"]["reference"])  # move to a task queue (Celery/RQ) in production
    return HttpResponse(status=200)

Security: Express's global express.json() consumes the body and re-serialising it changes bytes, so signatures stop matching. Register the webhook route with express.raw() before the JSON parser, as shown.

Tip: The Django example uses the legacy x-paystack-signature check for brevity. To use the newer Paystack-Signature header, port validPaystackSignature from the Node helper (HMAC-SHA512 over t + '.' + raw body with your whsec_ secret).

Frontend: Popup (React) and mobile (Flutter)

Web: install @paystack/inline-js (or load https://js.paystack.co/v2/inline.js). Get an access_code from your backend and call new PaystackPop().resumeTransaction(accessCode). Afterwards, ask your backend for the order status — the browser never decides that an order is paid.

Flutter: the official paystack_flutter_sdk package (marked beta by Paystack) takes your public key in initialize() and an access_code in launch(). Its result status is success, cancelled or failed; still confirm with your backend.

PaystackButton.jsx — Popup via access_code (npm i @paystack/inline-js) · React

import { useState } from "react";
import PaystackPop from "@paystack/inline-js";

export default function PaystackButton({ email }) {
  const [status, setStatus] = useState("");

  async function pay() {
    setStatus("Starting payment...");
    const res = await fetch("/api/checkout", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ email }), // no amount: the server prices the order
    });
    const data = await res.json();
    if (!res.ok) { setStatus(data.error || "Could not start payment"); return; }

    const popup = new PaystackPop();
    popup.resumeTransaction(data.accessCode);

    // Poll YOUR backend; it verifies with Paystack before reporting "paid".
    const started = Date.now();
    const timer = setInterval(async () => {
      const s = await fetch("/api/orders/" + encodeURIComponent(data.reference)).then((r) => r.json());
      if (s.status !== "pending" || Date.now() - started > 10 * 60 * 1000) {
        clearInterval(timer);
        setStatus(s.status === "paid" ? "Payment confirmed." : "Payment not completed (" + s.status + ").");
      }
    }, 3000);
  }

  return (
    <div>
      <button type="button" onClick={pay}>Pay with Paystack</button>
      <p role="status" aria-live="polite">{status}</p>
    </div>
  );
}

pay_with_paystack.dart — paystack_flutter_sdk (beta) + backend confirm · Flutter

import 'dart:convert';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
import 'package:paystack_flutter_sdk/paystack_flutter_sdk.dart';

const backend = 'https://your-backend.example.com';
// Public key only. Pass it at build time: --dart-define=PAYSTACK_PUBLIC_KEY=pk_test_...
const publicKey = String.fromEnvironment('PAYSTACK_PUBLIC_KEY');

final _paystack = Paystack();

Future<String> payWithPaystack(String email) async {
  final ready = await _paystack.initialize(publicKey, false);
  if (!ready) return 'Could not initialise Paystack';

  // 1. Your server initializes the transaction and returns the access code.
  final start = await http.post(Uri.parse('$backend/api/checkout'),
      headers: {'Content-Type': 'application/json'},
      body: jsonEncode({'email': email}));
  if (start.statusCode != 200) return 'Could not start payment';
  final body = jsonDecode(start.body) as Map<String, dynamic>;

  // 2. Show Paystack's payment UI.
  try {
    final result = await _paystack.launch(body['accessCode'] as String);
    if (result.status == 'cancelled') return 'Payment cancelled';
  } on PlatformException catch (e) {
    return e.message ?? 'Payment error';
  }

  // 3. Ask YOUR backend, which verifies with Paystack, before unlocking anything.
  final ref = Uri.encodeComponent(body['reference'] as String);
  final check = await http.get(Uri.parse('$backend/api/orders/$ref'));
  final status = (jsonDecode(check.body) as Map<String, dynamic>)['status'];
  return status == 'paid' ? 'Payment confirmed' : 'Payment pending or failed';
}

Warning: The InlineJS page documents resumeTransaction(accessCode) with a single argument; callbacks such as onSuccess are documented for newTransaction/checkout. This guide therefore polls the backend instead of relying on a client callback.

Initializing a transaction (raw request)

POST https://api.paystack.co/transaction/initialize — required: email and amount (string or number, in subunits). Useful optional fields: currency, reference, callback_url, metadata (stringified JSON), channels.

Response data: authorization_url, access_code, reference. Use authorization_url for a redirect checkout, access_code for Popup or the mobile SDKs.

Laravel: initialize and redirect · PHP (Laravel)

<?php
// app/Http/Controllers/CheckoutController.php
namespace App\Http\Controllers;

use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;

class CheckoutController extends Controller
{
    public function start(Request $request)
    {
        $data = $request->validate(['email' => 'required|email|max:254']);
        $order = Order::create([
            'reference' => 'ord_' . Str::uuid(),
            'amount_minor' => 500000,          // from your catalogue: 5,000.00 NGN in kobo
            'currency' => 'NGN',
            'email' => $data['email'],
            'status' => 'pending',
        ]);

        $res = Http::withToken(config('services.paystack.secret'))
            ->post('https://api.paystack.co/transaction/initialize', [
                'email' => $order->email,
                'amount' => (string) $order->amount_minor,
                'currency' => $order->currency,
                'reference' => $order->reference,
                'callback_url' => route('paystack.return'),
            ]);

        abort_unless($res->ok() && $res->json('status') === true, 502, 'Could not start payment');
        return redirect()->away($res->json('data.authorization_url'));
    }
}

Initialize with curl (test key) · Node.js (Express)

curl -s https://api.paystack.co/transaction/initialize \
  -H "Authorization: Bearer $PAYSTACK_SECRET_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "email": "[email protected]", "amount": "500000", "currency": "NGN",
        "reference": "ord_test_0001" }'
# => {"status":true,"message":"Authorization URL created",
#     "data":{"authorization_url":"https://checkout.paystack.com/...","access_code":"...","reference":"ord_test_0001"}}

Confirming the payment

Use GET https://api.paystack.co/transaction/verify/:reference from your server. Two different status fields matter:

  • top-level status: true — the API call worked;
  • data.status — the transaction result: success, failed, abandoned, ongoing, pending, processing, queued or reversed.

Give value only if data.status === "success", data.amount equals the order amount in subunits and data.currency matches. Store data.id and data.reference. For cards, data.authorization.authorization_code can charge a returning customer later (reusable authorizations only).

Warning: Landing on your callback_url does not prove payment. Paystack's docs say the redirect alone is not proof — always verify server-side.

Webhooks

Set your webhook URL in Dashboard → Settings → API Keys & Webhooks. Rules from the official webhooks page:

  • Verify the signature on the raw bytes before parsing: Paystack-Signature (timestamped HMAC-SHA512 with your whsec_ secret) or legacy x-paystack-signature (HMAC-SHA512 of the body with your secret key). Paystack stops sending the legacy header if you delete your secret key, so migrate to Paystack-Signature.
  • Return 200 OK to acknowledge (return 401 for a bad signature). Anything else is a failed delivery.
  • Retries: live — every 3 minutes for the first 4 tries, then hourly for 72 hours; test — hourly for 10 hours.
  • Webhooks come only from 52.31.139.75, 52.49.173.169 and 52.214.14.220 (test and live) — an optional extra filter.
  • Deduplicate: the same event can arrive more than once.

Key events here: charge.success, refund.pending, refund.processing, refund.processed, refund.failed. The verify page notes that Paystack currently sends webhooks only for successful transactions, so failed payments are seen through verify, not webhooks.

Laravel webhook: raw-body HMAC-SHA512 + idempotent update · PHP (Laravel)

<?php
// routes/api.php: Route::post('/webhooks/paystack', PaystackWebhookController::class);
namespace App\Http\Controllers;

use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;

class PaystackWebhookController extends Controller
{
    public function __invoke(Request $request)
    {
        $raw = $request->getContent(); // exact bytes
        $secret = (string) config('services.paystack.secret');
        $expected = hash_hmac('sha512', $raw, $secret);
        if ($secret === '' || ! hash_equals($expected, (string) $request->header('x-paystack-signature'))) {
            return response('', 401);
        }

        $event = json_decode($raw, true);
        if (($event['event'] ?? null) === 'charge.success') {
            $reference = (string) ($event['data']['reference'] ?? '');
            $tx = Http::withToken($secret)
                ->get('https://api.paystack.co/transaction/verify/' . rawurlencode($reference))
                ->json('data');

            DB::transaction(function () use ($reference, $tx) {
                $order = Order::where('reference', $reference)->lockForUpdate()->first();
                if (! $order || $order->status !== 'pending') {
                    return; // unknown or already processed
                }
                $ok = ($tx['status'] ?? null) === 'success'
                    && (int) ($tx['amount'] ?? -1) === (int) $order->amount_minor
                    && ($tx['currency'] ?? null) === $order->currency;
                $order->update(['status' => $ok ? 'paid' : 'review', 'paystack_id' => $tx['id'] ?? null]);
            });
        }
        return response('', 200);
    }
}

Security: Compare signatures with a constant-time function (crypto.timingSafeEqual, hash_equals, hmac.compare_digest), never with == or ===.

Status checks and reconciliation

Because failed payments do not trigger webhooks and deliveries can be delayed, run a periodic job that calls GET /transaction/verify/:reference for orders still pending after a few minutes, and stop after a sensible cut-off (for example 24 hours, then mark abandoned).

Verify by your reference. If you only have Paystack's numeric id, GET /transaction/:id fetches the transaction.

reconcile.mjs — verify stale pending orders · Node.js (Express)

import { paystack } from "./paystack.mjs";

// pendingOrders: [{ reference, amountMinor, currency }] older than ~5 minutes, from your DB.
export async function reconcile(pendingOrders, markPaid, markFailed) {
  for (const order of pendingOrders) {
    try {
      const tx = await paystack("GET", "/transaction/verify/" + encodeURIComponent(order.reference));
      if (tx.status === "success" && tx.amount === order.amountMinor && tx.currency === order.currency) {
        await markPaid(order.reference, tx.id); // conditional update: only if still pending
      } else if (["failed", "abandoned", "reversed"].includes(tx.status)) {
        await markFailed(order.reference, tx.status);
      } // ongoing / pending / processing / queued: check again later
    } catch (err) {
      console.error("verify failed for", order.reference, err.message);
    }
    await new Promise((r) => setTimeout(r, 200)); // be gentle with rate limits
  }
}

Refunds

POST https://api.paystack.co/refund with transaction (reference or id, required) and optional amount (subunits; omit for a full refund; cannot exceed the original), currency, customer_note, merchant_note and your own reference (8–64 chars: letters, digits, _, -).

The response says "Refund has been queued for processing" with refund status: "pending". Track it to processed through the refund.* webhooks or the refund fetch endpoint. A refund can end in needs-attention, which can be retried. Only refund from your back office, with staff authorization and an audit trail.

Partial refund with curl · Node.js (Express)

curl -s https://api.paystack.co/refund \
  -H "Authorization: Bearer $PAYSTACK_SECRET_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "transaction": "ord_test_0001", "amount": 100000,
        "merchant_note": "Item out of stock", "reference": "rfnd_ord_test_0001_1" }'

Tip: Pass your own refund reference derived from the order (for example rfnd_ _ ) so a retried request is recognisable and you never refund twice by accident.

Errors

Failed API calls return status: false and a message; the refund API lists HTTP 400 and 409 (conflict). Always log message and the HTTP status.

Commonly reported messages (not individually re-verified for this guide): *Invalid key* (wrong or missing secret key, or test/live mix-up), *Duplicate Transaction Reference* (a reference was reused), and validation messages about the amount or email.

On verify, data.gateway_response (for example Successful, Declined) explains the outcome; show customers a friendly message and keep the raw text for support.

Going to production

  • Activate your business, swap to live keys on the server only, and set the live webhook and callback URLs.
  • Your server must support TLS 1.2 to talk to Paystack (stated in the accept-payments docs).
  • Migrate webhooks to Paystack-Signature with a whsec_ secret, and support two v1 values during rotation.
  • Use a database with unique references and conditional updates; push webhook work to a queue.
  • Run the reconciliation job and compare daily against Paystack's transaction export.

Security checklist

  • Secret key and whsec_ secret only in server-side environment variables; public key only in clients.
  • Amount, currency and product come from your database; the client sends only an order id or cart id.
  • Webhook: raw-body signature check, 300-second timestamp window for Paystack-Signature, constant-time comparison, deduplication.
  • Fulfil only after verify confirms success with matching amount and currency.
  • Rate-limit checkout creation; never log full card data (you never receive it) or secrets.

Security: Never mark an order paid because the Popup closed, the Flutter SDK returned 'success', or the browser hit your callback URL. Those are client-side signals; only your server's verify call is authoritative.

Testing

  • Expose your local server with an HTTPS tunnel and set it as the test webhook URL.
  • Pay with 4084 0840 8408 4081 (success) and 4084 0800 0000 5408 (declined); check both paths.
  • Re-send a webhook from the dashboard (or replay a captured one) and confirm the second delivery changes nothing.
  • Send a request with a wrong signature and expect 401.
  • Refund a payment made with 4084 0800 0067 1803 to see a failing refund.

Send a correctly signed legacy test webhook to localhost · Node.js (Express)

BODY='{"event":"charge.success","data":{"reference":"ord_REPLACE_ME"}}'
SIG=$(printf "%s" "$BODY" | openssl dgst -sha512 -hmac "$PAYSTACK_SECRET_KEY" | sed 's/^.* //')
curl -s -X POST http://localhost:3000/webhooks/paystack \
  -H "Content-Type: application/json" -H "x-paystack-signature: $SIG" -d "$BODY" -w "%{http_code}\n"
# Expect 200; your handler then calls verify (which decides the real status).

Common mistakes

  • Sending the amount in main units: 5000 is ₦50.00, not ₦5,000. Multiply by 100 (also for XOF, per the docs).
  • Computing the HMAC over parsed-and-re-stringified JSON instead of the raw body — signatures fail intermittently.
  • Checking only the top-level status on verify; it means the API call succeeded, not the payment.
  • Using the callback URL as proof of payment.
  • Initializing from the browser or app with the secret key.
  • Reusing a reference, or using characters outside letters, digits, -, ., =.
  • CSRF middleware blocking the webhook in Django (@csrf_exempt) or Laravel (put it in routes/api.php).
  • Mixing test and live keys between frontend and backend.

Troubleshooting

  • 401 / Invalid key: check the secret key has no whitespace and matches the mode (test vs live) you expect.
  • Webhook signature never matches: you are hashing a re-serialised body, using the public key, or checking the legacy header while the dashboard sends only Paystack-Signature (or the reverse).
  • Paystack-Signature rejected despite correct secret: your server clock is off by more than 300 seconds — enable NTP.
  • No webhooks arriving: the URL is not public HTTPS, returns a redirect (3xx counts as failure), or it is set only for the other mode.
  • Customer not redirected back: no callback_url was set in the request or dashboard.
  • Verify shows abandoned: the customer opened checkout but never paid — not an error.
  • Flutter launch throws: on older Flutter versions the docs require FlutterFragmentActivity in MainActivity; Android min SDK 23, iOS 13.

Further reading

  • Paystack API reference — transactions, refunds, customers, plans, transfers.
  • InlineJS reference — Popup options and callbacks.
  • Test payments — full list of test cards, banks and mobile money numbers.
  • Related Metatron guides: Flutterwave Standard (pan-African alternative) and M-Pesa Daraja STK Push (Kenya).

Official documentation

Checked 2026-11-25.

Official documentation

Sources

More payment guides