DEV Community

Leke 🧒
Leke 🧒

Posted on Originally published at oyeleke.com.ng on

Paystack + Next.js: Payments You Can Actually Trust

 ---
title: "Paystack + Next.js: Payments You Can Actually Trust"
published: false
date: 2026-11-26 08:00:00 UTC
tags: Paystack,Nextjs,Payments,Security

canonical_url: https://oyeleke.com.ng/blog/paystack-nextjs-integration

Getting a Paystack checkout to open takes ten minutes. Getting it to be correct β€” every successful payment fulfilled exactly once, no fake confirmations, no orders stuck on "pending" because someone closed the tab β€” takes a bit more thought.

This is the pattern I use for Paystack in Next.js App Router projects, including online giving on the NWPM church platform. It has four parts:

  1. Initialize the transaction on the server, with a price the server decides.
  2. Complete it on Paystack's checkout.
  3. Verify it on the server before delivering anything.
  4. Listen for webhooks, so payments are fulfilled even when the browser never comes back.

The one rule

The browser can start a payment. Only your server, talking to Paystack, can decide that a payment happened.

Everything below follows from that. Never trust an amount the browser sends you, and never treat "the user landed on my success page" as proof of payment. Paystack's own docs say the same: visiting the callback URL doesn't prove the transaction succeeded.

Setup

Get your secret key from the Paystack dashboard ( Settings β†’ API Keys & Webhooks ) and generate a webhook signing secret under Developers β†’ API configuration. Use test keys locally.

# .env.local
PAYSTACK_SECRET_KEY=sk_test_xxx # server only, never NEXT_PUBLIC_
PAYSTACK_WEBHOOK_SECRET=whsec_xxx # webhook signing secret
NEXT_PUBLIC_SITE_URL=http://localhost:3000

Enter fullscreen mode Exit fullscreen mode

1. A tiny server-only Paystack client

// lib/paystack.ts
import "server-only";

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

async function paystack<T>(path: string, init?: RequestInit): Promise<T> {
  const res = await fetch(`${API}${path}`, {
    ...init,
    headers: {
      Authorization: `Bearer ${process.env.PAYSTACK_SECRET_KEY}`,
      "Content-Type": "application/json",
      ...init?.headers,
    },
    cache: "no-store",
  });
  const body = await res.json();
  if (!res.ok || !body.status) throw new Error(body.message ?? `Paystack error ${res.status}`);
  return body.data as T;
}

export function initializeTransaction(input: {
  email: string;
  amount: number; // in kobo (the currency's subunit)
  reference: string;
  callback_url: string;
  metadata?: Record<string, unknown>;
}) {
  return paystack<{ authorization_url: string; access_code: string; reference: string }>(
    "/transaction/initialize",
    { method: "POST", body: JSON.stringify(input) },
  );
}

export function verifyTransaction(reference: string) {
  return paystack<{ status: string; amount: number; currency: string; reference: string }>(
    `/transaction/verify/${encodeURIComponent(reference)}`,
  );
}

Enter fullscreen mode Exit fullscreen mode

The server-only import makes the build fail if this file is ever pulled into a client component, which is exactly what you want for anything holding your secret key.

2. Initialize on the server, with your price

The client sends what it wants to buy. The server decides how much it costs, creates a pending order, and asks Paystack for a checkout URL.

// app/api/checkout/route.ts
import { randomUUID } from "node:crypto";
import { initializeTransaction } from "@/lib/paystack";
import { db } from "@/lib/db"; // your database client

export async function POST(req: Request) {
  const { productId, email } = await req.json();

  const product = await db.product.findUnique({ where: { id: productId } });
  if (!product) return Response.json({ error: "Unknown product" }, { status: 400 });

  const reference = randomUUID();
  await db.order.create({
    data: { reference, productId, email, amountKobo: product.priceKobo, currency: "NGN", status: "pending" },
  });

  const { authorization_url } = await initializeTransaction({
    email,
    amount: product.priceKobo, // ₦5,000 β†’ 500000
    reference,
    callback_url: `${process.env.NEXT_PUBLIC_SITE_URL}/checkout/complete`,
    metadata: { productId },
  });

  return Response.json({ url: authorization_url });
}

Enter fullscreen mode Exit fullscreen mode

Two details that matter:

  • Amounts are in the subunit. ₦5,000 is 500000 kobo. Store prices in kobo as integers everywhere and you'll never fight floating-point rounding.
  • You own the reference. Generate it yourself and save it before calling Paystack. That reference is how every later step β€” verification, webhooks, retries β€” finds the order.

3. Send the customer to Paystack's checkout

The simplest flow that works everywhere, including flaky mobile browsers, is a redirect. Return the authorization_url from your route and send the customer there. When they finish, Paystack redirects them to your callback_url with the transaction reference in the query string.

The route in step 2 already returns that URL. The button just follows it:

// components/PayButton.tsx
"use client";

import { useState } from "react";

export function PayButton({ productId, email }: { productId: string; email: string }) {
  const [loading, setLoading] = useState(false);

  async function pay() {
    setLoading(true);
    const res = await fetch("/api/checkout", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ productId, email }),
    });
    if (!res.ok) return setLoading(false);
    const { url } = await res.json();
    window.location.assign(url);
  }

  return (
    <button onClick={pay} disabled={loading}>
      {loading ? "Opening checkout…" : "Pay with Paystack"}
    </button>
  );
}

Enter fullscreen mode Exit fullscreen mode

Prefer an in-page popup? Return the access_code instead and open it with Paystack's InlineJS library (npm i @paystack/inline-js): new Paystack().resumeTransaction(accessCode). The server-side parts below stay exactly the same. Whichever you choose, the browser finishing checkout only means "the customer says they paid". It doesn't mark anything as paid.

4. Fulfil once, from anywhere

Both the completion page and the webhook will call the same function. It verifies with Paystack, checks the amount and currency against your order, and flips the order from pending to paid exactly once.

// lib/orders.ts
import "server-only";
import { db } from "@/lib/db";
import { verifyTransaction } from "@/lib/paystack";

export async function fulfilOrder(reference: string) {
  const order = await db.order.findUnique({ where: { reference } });
  if (!order) return null;
  if (order.status === "paid") return order; // already done

  const tx = await verifyTransaction(reference);
  const valid = tx.status === "success" && tx.amount === order.amountKobo && tx.currency === order.currency;
  if (!valid) return order;

  // Conditional update: only one caller can win the pending β†’ paid transition.
  const { count } = await db.order.updateMany({
    where: { reference, status: "pending" },
    data: { status: "paid", paidAt: new Date() },
  });
  if (count === 1) {
    await sendReceipt(order); // deliver value exactly once
  }
  return { ...order, status: "paid" as const };
}

Enter fullscreen mode Exit fullscreen mode

Why so careful?

  • Check the amount. Paystack explicitly recommends it: if the amount doesn't match what you're delivering, don't deliver.
  • Make it idempotent. The callback page and the webhook will often arrive at nearly the same moment, and Paystack retries webhooks and lets you resend events. Without the conditional pending β†’ paid update, you'll send two receipts or ship two orders.

The completion page just calls it:

// app/checkout/complete/page.tsx
import { fulfilOrder } from "@/lib/orders";

export default async function CheckoutComplete({
  searchParams,
}: {
  searchParams: Promise<{ reference?: string; trxref?: string }>;
}) {
  const { reference, trxref } = await searchParams;
  const order = await fulfilOrder(reference ?? trxref ?? "");

  if (order?.status === "paid") return <h1>Payment received β€” thank you!</h1>;
  return <h1>We&apos;re confirming your payment. You&apos;ll get an email shortly.</h1>;
}

Enter fullscreen mode Exit fullscreen mode

The "still confirming" state isn't a failure. If verification hasn't settled yet, the webhook will finish the job.

5. Webhooks: the part most integrations skip

Users close tabs, lose network on the bus, or their phone dies right after paying. The callback page never loads β€” but Paystack still sends a charge.success event to your webhook URL. This is what makes your integration reliable.

Paystack now signs events with a Paystack-Signature header, using a webhook signing secret (whsec_…) you generate in the dashboard. It looks like this:

Paystack-Signature: t=1760270400,v1=whk_3f9a1c2e:9d1b...e47a

Enter fullscreen mode Exit fullscreen mode

To verify it, per Paystack's docs:

  1. Read the raw body bytes before any JSON parsing.
  2. Take t and every v1 value (<key id>:<signature>).
  3. Reject events where t is more than 300 seconds from your server's time (replay protection).
  4. Compute HMAC-SHA512 of ${t}. + raw body, keyed with the whole whsec_… secret.
  5. Compare against each v1 signature in constant time.
// lib/paystack-webhook.ts
import "server-only";
import { createHmac, timingSafeEqual } from "node:crypto";

const TOLERANCE_SECONDS = 300;

export function verifyPaystackSignature(raw: Buffer, header: string | null, secret: string): boolean {
  if (!header) return false;

  let t: number | null = null;
  const signatures: string[] = [];
  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" && /^\d+$/.test(value)) t = Number(value);
    if (key === "v1") {
      const j = value.indexOf(":");
      if (j !== -1) signatures.push(value.slice(j + 1));
    }
  }
  if (t === null || signatures.length === 0) return false;
  if (Math.abs(Date.now() / 1000 - t) > TOLERANCE_SECONDS) return false;

  const expected = createHmac("sha512", secret).update(`${t}.`).update(raw).digest();
  return signatures.some((hex) => /^[0-9a-f]{128}$/.test(hex) && timingSafeEqual(expected, Buffer.from(hex, "hex")));
}

Enter fullscreen mode Exit fullscreen mode

And the route handler. In the App Router you get the raw body with req.arrayBuffer(); don't call req.json() first, because re-serialising parsed JSON changes the bytes and the signature will never match.

// app/api/paystack/webhook/route.ts
import { after } from "next/server";
import { fulfilOrder } from "@/lib/orders";
import { verifyPaystackSignature } from "@/lib/paystack-webhook";

export async function POST(req: Request) {
  const raw = Buffer.from(await req.arrayBuffer());
  const secret = process.env.PAYSTACK_WEBHOOK_SECRET;
  if (!secret) return new Response("Webhook secret not configured", { status: 500 });

  if (!verifyPaystackSignature(raw, req.headers.get("paystack-signature"), secret)) {
    return new Response("Invalid signature", { status: 401 });
  }

  const event = JSON.parse(raw.toString("utf8"));
  if (event.event === "charge.success") {
    // Acknowledge fast; do the work after the response is sent.
    after(() => fulfilOrder(event.data.reference));
  }
  return new Response(null, { status: 200 });
}

Enter fullscreen mode Exit fullscreen mode

A few production notes:

  • Return 200 quickly. Paystack retries anything that isn't a 200 OK β€” in live mode every 3 minutes for the first 4 tries, then hourly for 72 hours. Long work belongs after the response, which is what after() is for.
  • Return 200 for events you don't handle , too. Otherwise Paystack keeps retrying them.
  • Still verify inside fulfilOrder. The signature proves the event came from Paystack; the verify call and amount check prove it matches your order.
  • Older integrations may only receive the legacy x-paystack-signature header (HMAC-SHA512 of the raw body using your secret key, no timestamp). Paystack's advice is to keep verifying it until your events carry Paystack-Signature, and not to delete your secret key before then.

Testing it locally

Webhooks can't reach localhost. Expose your dev server with a tunnel (or the Paystack CLI), put that URL in the test webhook field in your dashboard, and make a payment with Paystack's test cards. Then deliberately close the tab right after paying: the order should still end up paid, by webhook. That one test catches most broken integrations.

The checklist

  • Secret key and webhook secret are server-only (no NEXT_PUBLIC_)
  • Prices come from your database, in kobo, never from the client
  • You generate and store the reference before initializing
  • Every fulfilment path verifies status, amount and currency
  • pending β†’ paid happens in one conditional update (idempotent)
  • Webhook verifies the signature on the raw body and returns 200 fast
  • Tested: pay, then close the tab β€” order still fulfilled

Payments are the one feature where "mostly works" means someone lost money. If you'd like a Paystack integration built or reviewed, that's one of the things I do β€” or just get in touch.

Sources: Paystack: Accept Payments Β· Paystack: Webhooks Β· Paystack: Verify Payments

Top comments (0)