Sign in

Payments

Build your first checkout

View as Markdown

In a nutshell

Initialize a transaction, open the Paystack Popup, verify the payment, and handle webhooks.

Use this tutorial to build a simple one-time checkout with Paystack Popup. Your server initializes the transaction, your frontend opens the checkout, and your server verifies and fulfills the payment.

Secure your account

Never use your Paystack secret key in frontend code. Initialize transactions, verify payments, and validate webhook signatures on your server only.

Copy link1. Prerequisites

Before you start, get your test keys, prepare a server, and expose a public webhook URL.

  • A Paystack test public key and secret key
  • Your test webhook signing secret (whsec_...)
  • A server that can call the Paystack API
  • A public POST webhook URL for Paystack events
  • A trusted amount stored on your server for the order you want to charge

In this tutorial, the order amount is 5000 KES = 500000 cents.

export PAYSTACK_PUBLIC_KEY=pk_test_xxx
export PAYSTACK_SECRET_KEY=sk_test_xxx
export PAYSTACK_WEBHOOK_SECRET=whsec_xxx
export PAYSTACK_WEBHOOK_URL=https://your-domain.com/webhooks/paystack

Testing locally

Your webhook URL must be publicly reachable over HTTPS. To receive webhooks on your local machine, expose your server through a tunnel such as ngrok. See Webhooks.

Copy link2. Initialize a transaction

Create the transaction on your server with the customer's email and the amount in cents, then return the authorization_url and access_code to your frontend.

import express from "express";
import crypto from "node:crypto";

const app = express();
const secretKey = process.env.PAYSTACK_SECRET_KEY;

const orders = new Map([
  [
    "order_123",
    {
      email: "[email protected]",
      amount: 500000,
      delivered: false,
      reference: null
    }
  ]
]);

function findOrderByReference(reference) {
  return [...orders.values()].find((order) => order.reference === reference);
}

app.post("/api/checkout/initialize", express.json(), async (req, res) => {
  const { orderId } = req.body;
  const order = orders.get(orderId);

  if (!order) {
    return res.status(404).json({ message: "Order not found" });
  }

  const reference = `order_${Date.now()}`;
  order.reference = reference;

  const paystackResponse = await fetch("https://api.paystack.co/transaction/initialize", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${secretKey}`,
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      email: order.email,
      amount: order.amount,
      reference
    })
  });

  const result = await paystackResponse.json();

  if (!paystackResponse.ok) {
    return res.status(paystackResponse.status).json(result);
  }

  res.json({
    reference: result.data.reference,
    authorization_url: result.data.authorization_url,
    access_code: result.data.access_code
  });
});

Warning

Do not calculate the final amount on the frontend. Look up the order on your server and send the trusted amount to Paystack.

Copy link3. Open the checkout

Call your initialize endpoint from the frontend, then open Paystack Popup with the returned access_code.

<button id="pay-button">Pay ₦5,000</button>

<script src="https://js.paystack.co/v2/inline.js"></script>
<script>
  const button = document.getElementById("pay-button");

  button.addEventListener("click", async () => {
    const response = await fetch("/api/checkout/initialize", {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({ orderId: "order_123" })
    });

    const { access_code } = await response.json();
    new PaystackPop().resumeTransaction(access_code);
  });
</script>

Copy link4. Verify the payment

After checkout, verify the transaction on your server with the transaction reference and only treat it as paid when data.status is success and the amount matches your order.

app.get("/api/checkout/verify/:reference", async (req, res) => {
  const { reference } = req.params;
  const order = findOrderByReference(reference);

  if (!order) {
    return res.status(404).json({ message: "Order not found" });
  }

  const paystackResponse = await fetch(
    `https://api.paystack.co/transaction/verify/${reference}`,
    {
      headers: {
        Authorization: `Bearer ${secretKey}`
      }
    }
  );

  const result = await paystackResponse.json();

  if (!paystackResponse.ok) {
    return res.status(paystackResponse.status).json(result);
  }

  const verified =
    result.data.status === "success" && result.data.amount === order.amount;

  if (verified && !order.delivered) {
    order.delivered = true;
  }

  res.json({
    ok: verified,
    reference: result.data.reference,
    status: result.data.status,
    amount: result.data.amount
  });
});

Danger

Do not deliver value just because the customer returned to your app. Always verify the transaction on your server first.

Copy link5. Handle it with a webhook

Use the charge.success webhook as your primary signal to fulfill orders, grant access, or update your database. The customer can close the page before your callback runs, but the webhook still arrives.

Add your webhook URL on the Paystack Dashboard, and verify the signature on every event with your webhook signing secret.

Then confirm the event, status, and amount before you deliver value.

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;
}

app.post(
  "/webhooks/paystack",
  express.raw({ type: "application/json" }),
  (req, res) => {
    const webhookSecret = process.env.PAYSTACK_WEBHOOK_SECRET; // whsec_...
    if (!webhookSecret) {
      return res.sendStatus(500);
    }

    const kid = verifyPaystackSignature(req.body, req.get("paystack-signature"), [webhookSecret]);
    if (!kid) {
      return res.status(401).send("Invalid signature");
    }

    const event = JSON.parse(req.body.toString("utf8"));

    res.sendStatus(200);

    if (event.event !== "charge.success") {
      return;
    }

    const order = findOrderByReference(event.data.reference);

    if (!order) {
      return;
    }

    if (event.data.status !== "success") {
      return;
    }

    if (event.data.amount !== order.amount) {
      return;
    }

    if (order.delivered) {
      return;
    }

    order.delivered = true;
  }
);

Info

Use the raw request body to compute the webhook signature. If your framework parses JSON before you hash the payload, the signature check can fail.

Copy link6. Test it

Run your app, start a checkout, and complete the test payment with Paystack's successful test card.

# card number: 4084 0840 8408 4081
# cvv: 408
# expiry: any future date

Use this flow in test mode first: initialize the transaction, open the popup, verify the reference on your server, and confirm that your webhook receives charge.success before you ship live.

Was this page helpful?

What's Next