Skip to main content

APIs · Intermediate · 28 min

Accept card and bank payments with the Paystack API

By Padding · Updated 18 Nov 2026
Node.js 26.13 LTS · Express 5.3 · node:26 image

You will build a small Node.js 26 and Express 5.3 checkout that starts Paystack transactions from the server, prices everything in kobo, confirms each payment by verifying it with Paystack, accepts only correctly signed charge.success webhooks, and records every order as paid exactly once.

On this page

Paystack takes card and bank payments for businesses in several African countries, including Nigeria, Ghana, Kenya and South Africa. Its standard flow has three parts, and getting the order of trust right is most of the work:

  1. Your server asks Paystack to start a transaction, using your secret key. Paystack answers with an authorization_url.
  2. You send the customer to that URL. They pay on Paystack's checkout page, then Paystack sends them back to your callback URL.
  3. Paystack also posts a charge.success webhook to your server, signed with your secret key.

Neither the redirect nor the webhook body is proof of payment on its own. Anyone can type your callback URL into a browser with a made-up reference. So for both, your server asks Paystack directly, with GET /transaction/verify/:reference, and only marks the order paid when the status, amount and currency all match what it asked for. Because the callback and the webhook usually both arrive, the code that records a payment must also be safe to run twice.

You build this against a small local stand-in for the Paystack API that returns the documented response shapes, so you can run and break every part without an account. The last step points the same code at your own Paystack test keys.

Step 1 · Create the project and the env file

Make a folder, add Express 5.3 and mark the project as using ES modules:

Bash
mkdir -p ~/paystack-demo
cd ~/paystack-demo
npm init -y > /dev/null
npm pkg set type=module
npm install express@5.3.0

Settings go in a .env file that only you can read, created private with umask 077. For now the secret key is a made-up practice value and PAYSTACK_BASE_URL points at the stand-in you write next. Node loads the file with --env-file, so no extra package is needed:

Bash
cd ~/paystack-demo
(
  umask 077
  cat > .env <<EOF
PAYSTACK_SECRET_KEY=sk_test_practice_$(node -p "require('node:crypto').randomBytes(16).toString('hex')")
PAYSTACK_BASE_URL=http://127.0.0.1:4010
APP_URL=http://127.0.0.1:3000
MOCK_WEBHOOK_URL=http://127.0.0.1:3000/paystack/webhook
EOF
)
ls -l .env

The secret key never appears in your code, and the code never sends it to the browser. If the project is in Git, add .env to .gitignore before your first commit, as in keep secrets out of Git.

Check it worked

Bash
cd ~/paystack-demo
node -p "require('express/package.json').version"

The output is 5.3.0, and the ls -l line above starts with -rw-------.

Step 2 · Write a local stand-in for the Paystack API

The stand-in answers the two endpoints you use, with the same field names Paystack documents, and serves a one-button practice checkout page. When you press the button, it marks the transaction successful, redirects to your callback URL with trxref and reference in the query string, and then posts a signed charge.success event to your webhook, as Paystack does. It uses only Node's standard library:

Bash
cd ~/paystack-demo
cat > mock-paystack.js <<'JS'
// A local stand-in for two Paystack endpoints. For practice only.
import crypto from 'node:crypto';
import http from 'node:http';

const PORT = 4010;
const SECRET = process.env.PAYSTACK_SECRET_KEY;
const WEBHOOK_URL = process.env.MOCK_WEBHOOK_URL;
if (!SECRET || !WEBHOOK_URL) throw new Error('PAYSTACK_SECRET_KEY and MOCK_WEBHOOK_URL must be set');

const transactions = new Map(); // reference -> transaction
const references = new Map(); // access_code -> reference
let nextId = 4000001;

function send(res, status, body, headers = {}) {
  const isHtml = typeof body === 'string';
  res.writeHead(status, {
    'Content-Type': isHtml ? 'text/html; charset=utf-8' : 'application/json',
    ...headers,
  });
  res.end(isHtml ? body : JSON.stringify(body));
}

async function readJson(req) {
  const chunks = [];
  for await (const chunk of req) chunks.push(chunk);
  return JSON.parse(Buffer.concat(chunks).toString('utf8'));
}

function authorised(req) {
  const given = Buffer.from(req.headers.authorization ?? '');
  const expected = Buffer.from(`Bearer ${SECRET}`);
  return given.length === expected.length && crypto.timingSafeEqual(given, expected);
}

// The fields of a transaction that /transaction/verify and webhooks return.
function view(tx) {
  return {
    id: tx.id,
    domain: 'test',
    status: tx.status,
    reference: tx.reference,
    amount: tx.amount,
    gateway_response: tx.status === 'success' ? 'Successful' : 'The transaction was not completed',
    paid_at: tx.paid_at,
    created_at: tx.created_at,
    channel: 'card',
    currency: tx.currency,
    metadata: tx.metadata,
    customer: { email: tx.email },
  };
}

async function sendWebhook(tx) {
  const body = JSON.stringify({ event: 'charge.success', data: view(tx) });
  const signature = crypto.createHmac('sha512', SECRET).update(body).digest('hex');
  try {
    const res = await fetch(WEBHOOK_URL, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', 'x-paystack-signature': signature },
      body,
    });
    console.log(`webhook ${tx.reference}: ${res.status}`);
  } catch (err) {
    console.log(`webhook ${tx.reference}: failed (${err.message})`);
  }
}

const server = http.createServer(async (req, res) => {
  const url = new URL(req.url, `http://127.0.0.1:${PORT}`);

  if (req.method === 'POST' && url.pathname === '/transaction/initialize') {
    if (!authorised(req)) return send(res, 401, { status: false, message: 'Invalid key' });
    let input;
    try {
      input = await readJson(req);
    } catch {
      return send(res, 400, { status: false, message: 'Body must be JSON' });
    }
    const { email, amount, currency = 'NGN', callback_url, metadata = '' } = input;
    const reference = input.reference ?? crypto.randomBytes(5).toString('hex');
    if (typeof email !== 'string' || !email.includes('@')) {
      return send(res, 400, { status: false, message: 'email is required' });
    }
    if (!Number.isInteger(amount) || amount <= 0) {
      return send(res, 400, { status: false, message: 'amount must be a whole number of the smallest unit' });
    }
    if (!/^[A-Za-z0-9.=-]+$/.test(reference)) {
      return send(res, 400, { status: false, message: 'reference may only use -, ., = and letters and digits' });
    }
    if (transactions.has(reference)) {
      return send(res, 400, { status: false, message: 'Duplicate Transaction Reference' });
    }
    const accessCode = crypto.randomBytes(8).toString('hex');
    transactions.set(reference, {
      id: nextId++, reference, email, amount, currency, callback_url, metadata,
      status: 'abandoned', paid_at: null, created_at: new Date().toISOString(),
    });
    references.set(accessCode, reference);
    return send(res, 200, {
      status: true,
      message: 'Authorization URL created',
      data: {
        authorization_url: `http://127.0.0.1:${PORT}/checkout/${accessCode}`,
        access_code: accessCode,
        reference,
      },
    });
  }

  const verify = url.pathname.match(/^\/transaction\/verify\/([^/]+)$/);
  if (req.method === 'GET' && verify) {
    if (!authorised(req)) return send(res, 401, { status: false, message: 'Invalid key' });
    const tx = transactions.get(decodeURIComponent(verify[1]));
    if (!tx) return send(res, 404, { status: false, message: 'Entity not found' });
    return send(res, 200, { status: true, message: 'Verification successful', data: view(tx) });
  }

  const checkout = url.pathname.match(/^\/checkout\/([0-9a-f]+)(\/pay)?$/);
  const tx = checkout && transactions.get(references.get(checkout[1]));
  if (checkout && tx && req.method === 'GET' && !checkout[2]) {
    const price = (tx.amount / 100).toFixed(2);
    return send(res, 200, `<!doctype html><html lang="en"><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Practice checkout</title>
<body style="font-family:system-ui;max-width:28rem;margin:2rem auto;padding:0 1rem">
<h1>Practice checkout</h1>
<p>Local stand-in. No money moves.</p>
<p>${tx.currency} ${price} for ${tx.email.replace(/[<>&"']/g, '')}</p>
<form method="post" action="/checkout/${checkout[1]}/pay"><button>Pay with test card</button></form>
</body></html>`);
  }
  if (checkout && tx && req.method === 'POST' && checkout[2]) {
    if (tx.status !== 'success') {
      tx.status = 'success';
      tx.paid_at = new Date().toISOString();
      setTimeout(() => sendWebhook(tx), 300);
    }
    const back = new URL(tx.callback_url);
    back.searchParams.set('trxref', tx.reference);
    back.searchParams.set('reference', tx.reference);
    return send(res, 302, '', { Location: back.href });
  }

  send(res, 404, { status: false, message: 'Not found' });
});

server.listen(PORT, '127.0.0.1', () => console.log(`stand-in listening on http://127.0.0.1:${PORT}`));
JS

The stand-in checks the Authorization: Bearer header against your key, refuses an amount that is not a whole number, refuses a reused reference, and reports a transaction nobody has paid yet as abandoned. Its error messages are short and its own; the response shape (status, message, data) is the one Paystack uses.

Start it in a second terminal and leave it running:

Bash
cd ~/paystack-demo
node --env-file=.env mock-paystack.js

Check it worked

The second terminal prints stand-in listening on http://127.0.0.1:4010. Back in the first terminal, call it without a key:

Bash
curl -s -X POST http://127.0.0.1:4010/transaction/initialize

The answer is {"status":false,"message":"Invalid key"}, which is the message Paystack returns for an invalid key.

Step 3 · Call Paystack from the server and keep money in kobo

Paystack wants every amount in the smallest unit of the currency: kobo for naira, pesewas for cedis, cents for shillings, rand and dollars. ₦5,000 is 500000. Store prices that way from the start and keep them as integers. Floating-point naira values pick up rounding errors as soon as you add or multiply them (0.1 + 0.2 is 0.30000000000000004 in JavaScript), and the API has no way to express a fraction of a kobo.

Put the two API calls in one file. Every call sends the secret key as a bearer token, has a timeout, and throws unless Paystack answers with status: true:

Bash
cd ~/paystack-demo
cat > paystack.js <<'JS'
const BASE_URL = process.env.PAYSTACK_BASE_URL ?? 'https://api.paystack.co';
const SECRET_KEY = process.env.PAYSTACK_SECRET_KEY;
if (!SECRET_KEY) throw new Error('PAYSTACK_SECRET_KEY is not set');

async function call(path, init = {}) {
  const res = await fetch(`${BASE_URL}${path}`, {
    ...init,
    headers: { Authorization: `Bearer ${SECRET_KEY}`, 'Content-Type': 'application/json' },
    signal: AbortSignal.timeout(10_000),
  });
  const body = await res.json().catch(() => ({ status: false, message: `HTTP ${res.status}` }));
  if (!res.ok || body.status !== true) throw new Error(`Paystack ${path}: ${body.message}`);
  return body.data;
}

// fields: email, amount (smallest unit), currency, reference, callback_url, metadata
export function initializeTransaction(fields) {
  return call('/transaction/initialize', { method: 'POST', body: JSON.stringify(fields) });
}

export function verifyTransaction(reference) {
  return call(`/transaction/verify/${encodeURIComponent(reference)}`);
}
JS

Then the orders. In this tutorial they live in memory, which is enough to see the logic; a real shop keeps them in a database table. recordPayment is the single place that can mark an order paid, and it only does so once:

Bash
cd ~/paystack-demo
cat > orders.js <<'JS'
import crypto from 'node:crypto';

export const PRODUCT = { name: 'Workshop ticket', priceKobo: 500_000, currency: 'NGN' };

const orders = new Map(); // reference -> order. Use a database table in production.
const naira = new Intl.NumberFormat('en-NG', { style: 'currency', currency: 'NGN' });

// Display only. Never do arithmetic on the divided value.
export const formatKobo = (kobo) => naira.format(kobo / 100);

export function createOrder(email) {
  // Paystack references allow letters, digits, -, . and = only.
  const reference = `ord-${crypto.randomBytes(6).toString('hex')}`;
  const order = { reference, email, amountKobo: PRODUCT.priceKobo, currency: PRODUCT.currency, status: 'pending' };
  orders.set(reference, order);
  return order;
}

export const getOrder = (reference) => orders.get(reference);
export const forgetOrder = (reference) => orders.delete(reference);
export const listOrders = () =>
  [...orders.values()].map(({ reference, status, amountKobo, currency }) => ({ reference, status, amountKobo, currency }));

// tx is the data object from GET /transaction/verify/:reference.
// Returns 'paid', 'already-paid' or 'rejected'.
export function recordPayment(reference, tx, source) {
  const order = orders.get(reference);
  if (!order) {
    console.log(`unknown: ${reference} via ${source}`);
    return 'rejected';
  }
  if (tx.status !== 'success') {
    console.log(`not paid: ${reference} (${tx.status}) via ${source}`);
    return 'rejected';
  }
  if (tx.amount !== order.amountKobo || tx.currency !== order.currency) {
    console.log(`not paid: ${reference} (amount or currency mismatch) via ${source}`);
    return 'rejected';
  }
  if (order.status === 'paid') {
    console.log(`already paid: ${reference} via ${source}`);
    return 'already-paid';
  }
  order.status = 'paid';
  order.paidAt = tx.paid_at;
  console.log(`paid: ${reference} via ${source}`);
  // Fulfil here: send the ticket, grant access. This line runs once per order.
  return 'paid';
}
JS
  • Checking amount and currency against your own order, not against the request that brought the customer back, stops a payment for ₦50 unlocking a ₦5,000 order.
  • The if (order.status === 'paid') check runs straight after the last await, with nothing else in between, so in a single Node process two arrivals for one order cannot both pass it. With a database, get the same effect with a conditional update such as UPDATE orders SET status = 'paid' WHERE reference = $1 AND status = 'pending' and fulfil only when it changed one row.
  • The channels field of an initialise request limits which methods the checkout offers, such as card, bank or bank_transfer. Leave it out, as here, to show every method enabled for your Paystack business and its currency.

Check it worked

Start a transaction against the stand-in, verify it before anyone has paid, and try to record it:

Bash
cd ~/paystack-demo
cat > try-api.mjs <<'JS'
import { initializeTransaction, verifyTransaction } from './paystack.js';
import { PRODUCT, createOrder, formatKobo, recordPayment } from './orders.js';

console.log(formatKobo(PRODUCT.priceKobo));
const order = createOrder('ada@example.com');
const data = await initializeTransaction({
  email: order.email, amount: order.amountKobo, currency: order.currency,
  reference: order.reference, callback_url: 'http://127.0.0.1:3000/paystack/callback',
});
console.log(data.authorization_url);
const tx = await verifyTransaction(order.reference);
console.log(tx.status);
console.log(recordPayment(order.reference, tx, 'try'));
JS
node --env-file=.env try-api.mjs

The output is five lines: the price formatted as naira, something like ₦5,000.00; an address starting http://127.0.0.1:4010/checkout/; abandoned; then not paid: ord-… (abandoned) via try from the log and rejected. A transaction that has been started but not paid can never mark an order paid.

Step 4 · Check the webhook signature

Paystack signs each webhook body with your secret key and sends the result in the x-paystack-signature header: the hex HMAC-SHA512 of the exact bytes of the body. Recompute it and compare in constant time:

Bash
cd ~/paystack-demo
cat > webhook.js <<'JS'
import crypto from 'node:crypto';

// rawBody must be the exact bytes that arrived, as a Buffer.
export function isFromPaystack(rawBody, signatureHeader, secretKey) {
  if (!Buffer.isBuffer(rawBody)) return false;
  const signature = String(signatureHeader ?? '').toLowerCase();
  if (!/^[0-9a-f]{128}$/.test(signature)) return false; // 64 bytes as hex
  const expected = crypto.createHmac('sha512', secretKey).update(rawBody).digest();
  return crypto.timingSafeEqual(expected, Buffer.from(signature, 'hex'));
}
JS
  • The body must be the raw bytes. Parsing the JSON and turning it back into text can change spacing or key order, and a genuine signature stops matching.
  • crypto.timingSafeEqual takes the same time wherever two values differ, so an attacker cannot learn a valid signature from response times. The length check first is needed because it throws on buffers of different lengths.
  • For the x-paystack-signature scheme, the signing key is your secret key, so anyone who has it can also sign webhooks. Guard it like a password. Paystack's documentation also describes a newer Paystack-Signature header for webhook endpoints that have their own whsec_ signing secret, with a timestamp in the signed text. If your dashboard shows a signing secret for your endpoint, follow that scheme instead; the raw-body and constant-time rules are the same, and verify webhook signatures in Node.js builds a timestamped check like it.

Check it worked

Bash
cd ~/paystack-demo
cat > try-webhook.mjs <<'JS'
import crypto from 'node:crypto';
import { isFromPaystack } from './webhook.js';

const key = 'sk_test_example';
const body = Buffer.from('{"event":"charge.success","data":{"reference":"ord-1"}}');
const sig = crypto.createHmac('sha512', key).update(body).digest('hex');

console.log('genuine:', isFromPaystack(body, sig, key));
console.log('changed body:', isFromPaystack(Buffer.from(body.toString().replace('ord-1', 'ord-2')), sig, key));
console.log('wrong key:', isFromPaystack(body, sig, 'sk_test_other'));
console.log('no header:', isFromPaystack(body, undefined, key));
JS
node try-webhook.mjs

The output is genuine: true, then false for the changed body, the wrong key and the missing header.

Step 5 · Write the shop server

The server has four routes for customers and Paystack, and one small status route:

  • POST /pay creates an order, initialises a transaction for it and redirects the browser to the authorization_url with 303 See Other.
  • GET /paystack/callback is where Paystack sends the customer back. It verifies the reference with Paystack before showing anything as paid.
  • POST /paystack/webhook checks the signature on the raw body, answers 200 straight away, then verifies the transaction and records it.
  • GET /orders lists references and statuses, so you can watch what happens. It shows no personal data, but in a real shop it belongs behind staff sign-in.
Bash
cd ~/paystack-demo
cat > server.js <<'JS'
import express from 'express';
import { initializeTransaction, verifyTransaction } from './paystack.js';
import { PRODUCT, createOrder, forgetOrder, formatKobo, getOrder, listOrders, recordPayment } from './orders.js';
import { isFromPaystack } from './webhook.js';

const SECRET_KEY = process.env.PAYSTACK_SECRET_KEY;
const APP_URL = process.env.APP_URL ?? 'http://127.0.0.1:3000';

const escape = (text) => String(text).replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
const page = (title, body) => `<!doctype html><html lang="en"><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"><title>${escape(title)}</title>
<body style="font-family:system-ui;max-width:28rem;margin:2rem auto;padding:0 1rem">
<h1>${escape(title)}</h1>${body}</body></html>`;

const app = express();

// The webhook route comes first, with a raw body parser of its own.
app.post('/paystack/webhook', express.raw({ type: 'application/json', limit: '100kb' }), async (req, res) => {
  if (!isFromPaystack(req.body, req.get('x-paystack-signature'), SECRET_KEY)) {
    console.log('webhook rejected: bad signature');
    return res.sendStatus(401);
  }
  res.sendStatus(200); // answer first, so the sender is not left waiting

  let event;
  try {
    event = JSON.parse(req.body.toString('utf8'));
  } catch {
    return;
  }
  if (event?.event !== 'charge.success' || typeof event.data?.reference !== 'string') return;
  const reference = event.data.reference;
  try {
    // Ask Paystack, rather than trusting the event's own amount and status.
    recordPayment(reference, await verifyTransaction(reference), 'webhook');
  } catch (err) {
    console.log(`webhook verify failed: ${reference}: ${err.message}`);
  }
});

app.use(express.urlencoded({ extended: false, limit: '10kb' }));

app.get('/', (req, res) => {
  res.send(page(PRODUCT.name, `<p>One seat at the Saturday workshop: ${formatKobo(PRODUCT.priceKobo)}</p>
<form method="post" action="/pay">
<p><label>Email <input type="email" name="email" required autocomplete="email"></label></p>
<p><button>Pay ${formatKobo(PRODUCT.priceKobo)}</button></p>
</form>`));
});

app.post('/pay', async (req, res) => {
  const email = String(req.body?.email ?? '').trim();
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
    return res.status(400).send(page('Check your email', '<p>Enter a valid email address. <a href="/">Back</a></p>'));
  }
  const order = createOrder(email);
  try {
    const data = await initializeTransaction({
      email,
      amount: order.amountKobo,
      currency: order.currency,
      reference: order.reference,
      callback_url: `${APP_URL}/paystack/callback`,
      metadata: { product: PRODUCT.name },
    });
    console.log(`created: ${order.reference}`);
    res.redirect(303, data.authorization_url);
  } catch (err) {
    console.log(err.message);
    forgetOrder(order.reference);
    res.status(502).send(page('Payment unavailable', '<p>We could not start the payment. Try again in a minute.</p>'));
  }
});

app.get('/paystack/callback', async (req, res) => {
  const reference = String(req.query.reference ?? '');
  const order = getOrder(reference);
  if (!order) return res.status(404).send(page('Order not found', '<p>We do not recognise that payment.</p>'));
  try {
    const result = recordPayment(reference, await verifyTransaction(reference), 'callback');
    if (result !== 'rejected') {
      return res.send(page('Payment received',
        `<p>Order <code>${escape(reference)}</code> is paid: ${formatKobo(order.amountKobo)}.</p>`));
    }
  } catch (err) {
    console.log(`callback verify failed: ${reference}: ${err.message}`);
  }
  res.send(page('Payment not confirmed', '<p>We have not received this payment. If you were charged, it will show here within a few minutes.</p>'));
});

app.get('/orders', (req, res) => res.json(listOrders()));

app.listen(3000, '127.0.0.1', () => console.log('shop listening on http://127.0.0.1:3000'));
JS

The page under "Payment not confirmed" is deliberate. A bank transfer or a slow card network can leave a payment pending when the customer comes back, and the webhook may confirm it a little later. The customer's phone may also lose its connection after paying and never load your callback at all, which happens often on prepaid mobile data. The webhook still arrives, so the order is still recorded.

Start the shop in a third terminal:

Bash
cd ~/paystack-demo
node --env-file=.env server.js

Check it worked

The third terminal prints shop listening on http://127.0.0.1:3000. From the first terminal, submit the form as a browser would, without following the redirect:

Bash
curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' -d 'email=ada@example.com' http://127.0.0.1:3000/pay

The output is 303 followed by an address starting http://127.0.0.1:4010/checkout/, and the shop logs created: ord-…. Nobody pays this one, so it stays pending. A bad email gets 400 and creates nothing.

Step 6 · Pay once and see it recorded once

Open http://127.0.0.1:3000 in your browser. Enter an email address and press the pay button. The browser moves to the practice checkout on port 4010. Press Pay with test card, and you land back on your shop.

Check it worked

The page heading is Payment received and the address bar ends /paystack/callback?trxref=ord-…&reference=ord-…. Within a second the shop terminal shows two lines for that reference, usually in this order:

Text
paid: ord-3f9c2a1b7d4e via callback
already paid: ord-3f9c2a1b7d4e via webhook

The stand-in's terminal shows webhook ord-3f9c2a1b7d4e: 200. Two confirmations arrived, both were verified with the API, and the order was recorded once. List the orders:

Bash
curl -s http://127.0.0.1:3000/orders

Your paid reference has "status":"paid" and the one from the previous step is still "pending".

Step 7 · Try to fool the webhook

A webhook endpoint is a public URL. Write a small script that sends charge.success events the way an attacker, or a confused retry, might. It looks up your latest paid and pending orders through /orders, so you do not have to copy references:

Bash
cd ~/paystack-demo
cat > send-webhook.mjs <<'JS'
import crypto from 'node:crypto';

const scenario = process.argv[2] ?? 'forged';
const orders = await (await fetch('http://127.0.0.1:3000/orders')).json();
const latest = (status) => orders.filter((o) => o.status === status).at(-1)?.reference ?? 'ord-none';

// forged:  claims a pending order is paid, signed with a key that is not yours
// replay:  a correctly signed copy of an event for an order already paid
// unpaid:  correctly signed, claims success for an order nobody paid
const reference = scenario === 'replay' ? latest('paid') : latest('pending');
const key = scenario === 'forged' ? 'sk_test_not_your_key' : process.env.PAYSTACK_SECRET_KEY;

const body = JSON.stringify({
  event: 'charge.success',
  data: { reference, status: 'success', amount: 500000, currency: 'NGN' },
});
const signature = crypto.createHmac('sha512', key).update(body).digest('hex');
const res = await fetch('http://127.0.0.1:3000/paystack/webhook', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json', 'x-paystack-signature': signature },
  body,
});
console.log(`${scenario} ${reference}: ${res.status}`);
JS
for s in forged replay unpaid; do node --env-file=.env send-webhook.mjs "$s"; done

Check it worked

The script prints forged ord-…: 401, then replay ord-…: 200 and unpaid ord-…: 200. The shop terminal explains each one:

  • webhook rejected: bad signature for the forged event.
  • already paid: ord-… via webhook for the replay. Treat a repeat of an event you have already handled as normal: record nothing new and still answer 200.
  • not paid: ord-… (abandoned) via webhook for the unpaid one. Its signature was valid, but the body claimed a success that Paystack's own record does not show. Verifying with the API before you fulfil is what catches a mistaken or replayed event, or one signed with a key that has leaked.

Run curl -s http://127.0.0.1:3000/orders again: nothing changed.

Step 8 · Switch to your Paystack test keys

The shop code does not change. Only the settings do.

  1. In your Paystack dashboard, make sure Test Mode is on, and open the API keys and webhooks section of the settings. Copy the test secret key, which starts with sk_test_. The public key (pk_test_) is for browser libraries and is not used here.
  2. Open ~/paystack-demo/.env in your editor. Replace the practice value of PAYSTACK_SECRET_KEY with your test key, and delete the PAYSTACK_BASE_URL and MOCK_WEBHOOK_URL lines, so paystack.js uses https://api.paystack.co. Editing the file keeps the key out of your shell history.
  3. Paystack must reach your webhook over public HTTPS. Put the shop behind a reverse proxy on a server, as in nginx as a reverse proxy for a Node app, set APP_URL to its https:// address, and enter https://<your-domain>/paystack/webhook as the test webhook URL in the dashboard. Replace <your-domain> with your own.
  4. Stop the stand-in with Ctrl+C, restart the shop, and pay with one of the test cards on Paystack's test payments page (paystack.com/docs/payments/test-payments).
Bash
cd ~/paystack-demo
node --env-file=.env server.js

Live mode works the same way with the sk_live_ key, once Paystack has activated your business. Keep live keys only on the server that needs them, never in a repository or a chat message.

Check it worked

After a test payment, the shop logs paid: ord-… via callback and, once Paystack's webhook arrives, already paid: ord-… via webhook. The transaction shows as successful under Transactions in the dashboard, with the same reference. If the webhook line never appears, the dashboard's webhook URL is wrong or not reachable over HTTPS; if every webhook is rejected, check that the key in .env is the test key of the same Paystack business.

Step 9 · Stop the servers and clean up

Press Ctrl+C in the shop terminal and, if it is still running, in the stand-in terminal. Then delete the folder, which holds your key:

Bash
cd ~
rm -rf ~/paystack-demo

If you used a real test key and no longer need it, and it may have been copied anywhere else, replace it from the API keys section of the dashboard settings.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.