Pesapal API 3.0: hosted checkout, IPN and transaction status
Accept cards and mobile money through Pesapal's hosted payment page: request a token, register an IPN URL, submit an order, verify every notification with GetTransactionStatus, and request refunds.
- Provider
- Pesapal
- Level
- Intermediate
- Stacks
- Node.js (Express), PHP (Laravel), Python (Django)
- Code maturity
- Sandbox-ready
- Last verified
- 25 Nov 2026
Introduction
Pesapal is an East African payment gateway. With API 3.0 (JSON over REST) you create an order on your server, Pesapal returns a redirect_url to its hosted payment page, and the customer pays there with a card or mobile money. Pesapal then tells your server that something changed through an IPN (Instant Payment Notification), and you ask Pesapal for the real status with GetTransactionStatus.
This guide builds that loop in the sandbox: token, IPN registration, order submission, IPN handling with an idempotent order update, status checks and refunds.
Tip: Pesapal API 2.0 (XML/OAuth 1.0) is a different, older API with different parameter names. Do not mix examples from the two versions.
What the API does
POST /api/Auth/RequestToken— exchange your consumer key and secret for a short-lived bearer token.POST /api/URLSetup/RegisterIPN— register the URL Pesapal will notify; returns anipn_id.GET /api/URLSetup/GetIpnListlists registered IPNs.POST /api/Transactions/SubmitOrderRequest— create an order; returnsorder_tracking_idandredirect_url.GET /api/Transactions/GetTransactionStatus?orderTrackingId=...— the authoritative payment status.POST /api/Transactions/RefundRequest— ask for a refund of a completed payment.
Pesapal also documents recurring payments and order cancellation endpoints; they are out of scope here.
Countries and currencies
Pesapal's sandbox demo-keys file (linked from the Authentication page) lists demo merchants for Kenya, Uganda, Tanzania, Malawi, Rwanda, Zambia and Zimbabwe. Which countries, currencies and payment methods your own merchant account can use depends on your contract with Pesapal — check with them.
currency in SubmitOrderRequest is an ISO currency code (for example KES, UGX, TZS), and amount is a decimal in major units (for example 100.00), not cents.
Warning: The per-country method list (which wallets and card schemes are enabled) is not published in the API 3.0 pages we checked. Confirm it for your account before promising a method to customers.
Payment methods
The customer chooses the method on Pesapal's hosted page, so you integrate once. The GetTransactionStatus sample in the docs shows payment_method values such as card brands (e.g. Visa) and mobile money; refund rules in the docs mention cards and mobile money explicitly.
Because the page is hosted by Pesapal, card data never touches your servers, which greatly reduces your PCI DSS scope.
When to use Pesapal
- You sell to customers in East or Southern Africa and want cards and mobile money from a single integration.
- You prefer a hosted payment page (redirect or iframe) over collecting card details yourself.
- You want one settlement relationship instead of separate contracts with each mobile-money operator.
When not to use it
- You only need M-Pesa in Kenya and want the lowest cost and direct control — Daraja STK Push may fit better.
- You need a fully custom, embedded card form with your own UI (Pesapal's flow is hosted).
- Your customers are mostly outside the countries your Pesapal account supports.
Real-world scenarios
- Online shop in Kenya or Uganda: cart → your server submits the order → customer pays on the Pesapal page (card or mobile money) → IPN → you verify and ship.
- School or event fees: use the invoice or ticket number as your merchant reference (
id) so finance can reconcile. - Mobile app: your app opens the
redirect_urlin a web view; your backend handles IPN and status. The app never sees API keys.
Registration and onboarding
- Start in the sandbox with the demo keys Pesapal publishes (see the sandbox section).
- To go live, open a Pesapal business (merchant) account. The Authentication page states that production consumer key and secret are emailed to the merchant email address when the business account is opened.
- Register your production IPN URL against the production base URL — sandbox IPN ids do not work in production.
Warning: Business documents, review times and fees for merchant accounts are not part of the API docs. Ask Pesapal directly; do not rely on third-party summaries.
Sandbox environment
- Sandbox base URL:
https://cybqa.pesapal.com/pesapalv3 - Production base URL:
https://pay.pesapal.com/v3
All endpoints in this guide are appended to the base, e.g. https://cybqa.pesapal.com/pesapalv3/api/Auth/RequestToken.
Pesapal publishes demo consumer keys for sandbox merchants in several countries in a text file linked from the Authentication page. Copy the pair for your country into .env.
Tip: The docs pages we checked do not list sandbox test card numbers or test phone numbers. Use the options the sandbox payment page offers, and ask Pesapal support if you need specific test cases.
Credentials you need
- Consumer key and consumer secret — used only to obtain tokens.
- IPN id (
notification_id) — a GUID returned by RegisterIPN; not secret, but environment-specific.
Keep the key and secret on the server in environment variables or a secrets manager.
Security: Never put the consumer secret in frontend or mobile code. Anyone holding it can create orders and request refunds as your business.
Environment configuration
Commit a .env.example with placeholders and keep the real .env out of version control. Register the IPN once (script in the authentication section) and store the returned id in PESAPAL_IPN_ID.
# Pesapal API 3.0 — copy to .env
PESAPAL_ENV=sandbox # sandbox | production
PESAPAL_CONSUMER_KEY=replace-me
PESAPAL_CONSUMER_SECRET=replace-me
# GUID returned by RegisterIPN for THIS environment
PESAPAL_IPN_ID=replace-after-registering
# Public HTTPS URLs (use a tunnel such as ngrok in development)
PESAPAL_IPN_URL=https://your-public-host.example.com/pesapal/ipn
PESAPAL_CALLBACK_URL=https://your-public-host.example.com/checkout/return
PORT=3000Authentication (RequestToken) and IPN registration
POST {base}/api/Auth/RequestToken with headers Accept: application/json and Content-Type: application/json and body { "consumer_key": ..., "consumer_secret": ... }. The response contains token, expiryDate (UTC), error, status and message. The docs state the token is valid for up to 5 minutes, so cache it briefly and refresh.
Every other call sends Authorization: Bearer <token>.
Register your IPN once per environment with POST {base}/api/URLSetup/RegisterIPN, body { "url": "https://.../pesapal/ipn", "ipn_notification_type": "GET" } (or "POST"). Save the returned ipn_id.
// pesapal.mjs — shared helpers for Pesapal API 3.0. Node 18+ (global fetch).
export const BASE_URL = process.env.PESAPAL_ENV === "production"
? "https://pay.pesapal.com/v3"
: "https://cybqa.pesapal.com/pesapalv3";
const JSON_HEADERS = { Accept: "application/json", "Content-Type": "application/json" };
let cache = { token: null, expiresAt: 0 };
export async function getToken() {
if (cache.token && Date.now() < cache.expiresAt) return cache.token;
const res = await fetch(BASE_URL + "/api/Auth/RequestToken", {
method: "POST",
headers: JSON_HEADERS,
body: JSON.stringify({
consumer_key: process.env.PESAPAL_CONSUMER_KEY,
consumer_secret: process.env.PESAPAL_CONSUMER_SECRET,
}),
});
const body = await res.json().catch(() => ({}));
if (!res.ok || !body.token) {
throw new Error("Pesapal token failed: " + (body.error?.message || body.message || res.status));
}
// Docs: token valid for up to 5 minutes. Refresh after 4 to stay safe.
cache = { token: body.token, expiresAt: Date.now() + 4 * 60 * 1000 };
return cache.token;
}
export async function pesapal(method, path, payload) {
const res = await fetch(BASE_URL + path, {
method,
headers: { ...JSON_HEADERS, Authorization: "Bearer " + (await getToken()) },
body: payload ? JSON.stringify(payload) : undefined,
});
const body = await res.json().catch(() => ({}));
// Errors come back as { error: { error_type, code, message }, status }
if (!res.ok || (body.error && body.error.code)) {
const err = new Error(body.error?.message || "Pesapal HTTP " + res.status);
err.code = body.error?.code;
throw err;
}
return body;
}
// One-off: node -e "import('./pesapal.mjs').then(m => m.registerIpn()).then(console.log)"
export function registerIpn() {
return pesapal("POST", "/api/URLSetup/RegisterIPN", {
url: process.env.PESAPAL_IPN_URL,
ipn_notification_type: "GET",
}); // => { url, created_date, ipn_id, ipn_status, ... }
}
export function listIpns() {
return pesapal("GET", "/api/URLSetup/GetIpnList");
}Warning: The token lives for minutes, not hours. Long-running jobs (reconciliation, refunds) must refresh it; reusing a token from an earlier request is a common cause of 401 errors.
Backend: create the order, handle IPN, update once
The backend does three things:
- Create: read the order from YOUR database (amount, currency), submit it to Pesapal with a unique merchant reference, save
order_tracking_id, and returnredirect_urlto the browser. - IPN: when Pesapal calls your IPN URL, ignore the notification's content except the ids, call GetTransactionStatus, check reference, amount and currency, then update the order once. Reply with the JSON acknowledgement Pesapal documents.
- Return page: when the customer lands on your
callback_url, call GetTransactionStatus again and show the result — never mark paid from the redirect alone.
The Node example stores orders in a Map so it runs without a database. In production use a unique index on the merchant reference and on order_tracking_id, and make state transitions conditional (WHERE status = 'PENDING').
import "dotenv/config";
import express from "express";
import { pesapal } from "./pesapal.mjs";
const app = express();
app.use(express.json({ limit: "50kb" }));
// Demo store. Production: DB with unique(merchantRef), unique(trackingId).
const orders = new Map([["ORD-1001", { ref: "ORD-1001", amount: 100.0, currency: "KES", status: "PENDING" }]]);
const STATUS = { 1: "PAID", 2: "FAILED", 3: "REVERSED", 0: "INVALID" };
app.post("/api/orders/:ref/checkout", async (req, res) => {
const order = orders.get(req.params.ref);
if (!order || order.status !== "PENDING") return res.status(404).json({ error: "Order not payable" });
try {
const out = await pesapal("POST", "/api/Transactions/SubmitOrderRequest", {
id: order.ref, // unique, max 50 chars, letters/digits/-_.:
currency: order.currency,
amount: order.amount, // decimal major units, from YOUR record
description: "Order " + order.ref, // max 100 chars
callback_url: process.env.PESAPAL_CALLBACK_URL,
notification_id: process.env.PESAPAL_IPN_ID,
billing_address: { email_address: req.body.email || "", phone_number: req.body.phone || "" },
});
order.trackingId = out.order_tracking_id;
res.json({ redirectUrl: out.redirect_url });
} catch (err) {
console.error("SubmitOrderRequest failed", err.code, err.message);
res.status(502).json({ error: "Could not start Pesapal checkout" });
}
});
// Verify with Pesapal and apply the result idempotently.
async function syncOrder(trackingId) {
const s = await pesapal("GET", "/api/Transactions/GetTransactionStatus?orderTrackingId=" + encodeURIComponent(trackingId));
const order = orders.get(s.merchant_reference);
if (!order || order.trackingId !== trackingId) return null;
const next = STATUS[s.status_code];
const amountOk = Number(s.amount) === order.amount && s.currency === order.currency;
if (next === "PAID" && order.status === "PENDING") {
order.status = amountOk ? "PAID" : "REVIEW";
order.confirmationCode = s.confirmation_code; // needed later for refunds
} else if (next === "FAILED" && order.status === "PENDING") {
order.status = "FAILED";
} else if (next === "REVERSED" && order.status === "PAID") {
order.status = "REVERSED";
} // anything else: no change (duplicate or out-of-order notification)
return order;
}
// Registered with ipn_notification_type GET; POST is handled the same way.
app.all("/pesapal/ipn", async (req, res) => {
const src = req.method === "GET" ? req.query : req.body;
const ack = {
orderNotificationType: String(src.OrderNotificationType || ""),
orderTrackingId: String(src.OrderTrackingId || ""),
orderMerchantReference: String(src.OrderMerchantReference || ""),
};
try {
await syncOrder(ack.orderTrackingId);
res.json({ ...ack, status: 200 });
} catch (err) {
console.error("IPN processing failed", err.message);
res.json({ ...ack, status: 500 }); // tells Pesapal processing did not complete
}
});
app.get("/checkout/return", async (req, res) => {
const order = await syncOrder(String(req.query.OrderTrackingId || "")).catch(() => null);
res.send(order ? "Order " + order.ref + ": " + order.status : "We are confirming your payment.");
});
app.listen(process.env.PORT || 3000, () => console.log("listening"));import os, time
import requests
from django.db import transaction
from django.http import JsonResponse, HttpResponseNotFound
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from .models import Order # fields: ref (unique), amount (Decimal), currency, status, tracking_id (unique, null), confirmation_code
BASE = "https://pay.pesapal.com/v3" if os.getenv("PESAPAL_ENV") == "production" else "https://cybqa.pesapal.com/pesapalv3"
HEADERS = {"Accept": "application/json", "Content-Type": "application/json"}
_tok = {"value": None, "exp": 0.0}
def token():
if _tok["value"] and time.time() < _tok["exp"]:
return _tok["value"]
r = requests.post(f"{BASE}/api/Auth/RequestToken", headers=HEADERS, timeout=30, json={
"consumer_key": os.environ["PESAPAL_CONSUMER_KEY"], "consumer_secret": os.environ["PESAPAL_CONSUMER_SECRET"]})
r.raise_for_status()
_tok.update(value=r.json()["token"], exp=time.time() + 240) # docs: valid up to 5 minutes
return _tok["value"]
def api(method, path, payload=None):
r = requests.request(method, BASE + path, json=payload, timeout=30,
headers={**HEADERS, "Authorization": f"Bearer {token()}"})
body = r.json()
if r.status_code != 200 or (body.get("error") or {}).get("code"):
raise RuntimeError((body.get("error") or {}).get("message") or f"Pesapal HTTP {r.status_code}")
return body
@csrf_exempt
@require_POST
def checkout(request, ref):
order = Order.objects.filter(ref=ref, status="PENDING").first()
if not order:
return HttpResponseNotFound()
out = api("POST", "/api/Transactions/SubmitOrderRequest", {
"id": order.ref, "currency": order.currency, "amount": float(order.amount),
"description": f"Order {order.ref}", "callback_url": os.environ["PESAPAL_CALLBACK_URL"],
"notification_id": os.environ["PESAPAL_IPN_ID"],
"billing_address": {"email_address": request.user.email if request.user.is_authenticated else ""},
})
Order.objects.filter(pk=order.pk).update(tracking_id=out["order_tracking_id"])
return JsonResponse({"redirectUrl": out["redirect_url"]})
def sync_order(tracking_id):
s = api("GET", f"/api/Transactions/GetTransactionStatus?orderTrackingId={tracking_id}")
with transaction.atomic():
order = Order.objects.select_for_update().filter(ref=s.get("merchant_reference"), tracking_id=tracking_id).first()
if not order:
return None
code = s.get("status_code")
if code == 1 and order.status == "PENDING":
ok = float(s.get("amount", -1)) == float(order.amount) and s.get("currency") == order.currency
order.status, order.confirmation_code = ("PAID" if ok else "REVIEW"), s.get("confirmation_code")
order.save(update_fields=["status", "confirmation_code"])
elif code == 2 and order.status == "PENDING":
order.status = "FAILED"
order.save(update_fields=["status"])
return order
@csrf_exempt
def ipn(request):
src = request.GET if request.method == "GET" else request.POST or {}
ack = {"orderNotificationType": src.get("OrderNotificationType", ""),
"orderTrackingId": src.get("OrderTrackingId", ""),
"orderMerchantReference": src.get("OrderMerchantReference", "")}
try:
sync_order(ack["orderTrackingId"])
return JsonResponse({**ack, "status": 200})
except Exception:
return JsonResponse({**ack, "status": 500})Security: The amount and currency come from your database. The browser only sends the order reference; it can never set the price.
Tip: If you registered the IPN as POST, Pesapal sends a JSON body; parse it with json.loads(request.body) in Django instead of request.POST.
Frontend: redirect or iframe
Your page calls your own backend (POST /api/orders/:ref/checkout) and receives redirectUrl. Then either:
- Redirect the whole window to
redirectUrl(simplest, best on mobile), or - Embed it in an
iframeso the customer stays on your site. The docs'redirect_modefield (TOP_WINDOW, the default, orPARENT_WINDOW) controls where yourcallback_urlloads after payment.
After payment Pesapal sends the customer to your callback_url with OrderTrackingId, OrderMerchantReference and OrderNotificationType=CALLBACKURL in the query string. Your return page must ask your backend for the verified status; show "confirming..." until it is final.
Security: Landing on the callback URL does not mean the customer paid — anyone can open that URL with made-up parameters. Only GetTransactionStatus, called from your server, decides.
SubmitOrderRequest in detail
POST {base}/api/Transactions/SubmitOrderRequest with a bearer token. Required fields per the docs:
id— your unique merchant reference, max 50 characters; letters, digits,-,_,.,:. Must be unique for every order request.currency— ISO code;amount— decimal.description— max 100 characters.callback_url— where the customer is redirected after payment.notification_id— theipn_idfrom RegisterIPN.billing_address— object;email_addressorphone_numberis required (one of them). Optional:country_code(2 letters), names,line_1,line_2,city,state(max 3),postal_code,zip_code.
Optional: cancellation_url, branch, redirect_mode. The response contains order_tracking_id, merchant_reference, redirect_url, error and status ("200" on success).
<?php
// app/Services/PesapalService.php
namespace App\Services;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
class PesapalService
{
private function base(): string
{
return config('services.pesapal.env') === 'production'
? 'https://pay.pesapal.com/v3' : 'https://cybqa.pesapal.com/pesapalv3';
}
private function token(): string
{
// Docs: token is valid for up to 5 minutes.
return Cache::remember('pesapal_token', now()->addMinutes(4), function () {
return Http::acceptJson()->post($this->base() . '/api/Auth/RequestToken', [
'consumer_key' => config('services.pesapal.key'),
'consumer_secret' => config('services.pesapal.secret'),
])->throw()->json('token');
});
}
private function client()
{
return Http::acceptJson()->withToken($this->token())->timeout(30);
}
public function submitOrder(string $ref, float $amount, string $currency, string $email): array
{
return $this->client()->post($this->base() . '/api/Transactions/SubmitOrderRequest', [
'id' => $ref,
'currency' => $currency,
'amount' => $amount,
'description' => 'Order ' . $ref,
'callback_url' => config('services.pesapal.callback_url'),
'notification_id' => config('services.pesapal.ipn_id'),
'billing_address' => ['email_address' => $email],
])->throw()->json(); // order_tracking_id, merchant_reference, redirect_url
}
public function status(string $trackingId): array
{
return $this->client()->get($this->base() . '/api/Transactions/GetTransactionStatus', [
'orderTrackingId' => $trackingId,
])->throw()->json();
}
public function refund(string $confirmationCode, string $amount, string $username, string $remarks): array
{
return $this->client()->post($this->base() . '/api/Transactions/RefundRequest', [
'confirmation_code' => $confirmationCode,
'amount' => $amount,
'username' => $username,
'remarks' => $remarks,
])->throw()->json();
}
}Confirming the payment
The docs are explicit: the callback URL and the IPN calls do NOT carry the payment status "for security reasons". You must call GET {base}/api/Transactions/GetTransactionStatus?orderTrackingId=....
Key response fields: status_code (0 INVALID, 1 COMPLETED, 2 FAILED, 3 REVERSED), payment_status_description, amount, currency, merchant_reference, confirmation_code (keep it — refunds need it), payment_method, payment_account (masked) and description.
Mark an order paid only if status_code is 1, merchant_reference is your order, and amount and currency match your record.
{
"payment_method": "Visa",
"amount": 100,
"created_date": "2022-04-30T07:41:09.763",
"confirmation_code": "6513008693186320103009",
"payment_status_description": "Failed",
"description": "Unable to Authorize Transaction.Kindly contact your bank for assistance",
"message": "Request processed successfully",
"payment_account": "476173**0010",
"call_back_url": "https://test.com/?OrderTrackingId=7e6b62d9-883e-440f-a63e-e1105bbfadc3&OrderMerchantReference=1515111111",
"status_code": 2,
"merchant_reference": "1515111111",
"payment_status_code": "",
"currency": "KES",
"error": { "error_type": null, "code": null, "message": null, "call_back_url": null },
"status": "200"
}IPN (webhooks) and how to trust them
Pesapal calls your registered IPN URL whenever a payment's status changes, with OrderTrackingId, OrderMerchantReference and OrderNotificationType=IPNCHANGE — as query parameters if you registered GET, or in the body if you registered POST.
IPNs are not signed, so treat them only as a *hint*: take the OrderTrackingId, call GetTransactionStatus from your server, and act on that answer. A forged IPN then achieves nothing except an extra status lookup.
Reply with JSON confirming receipt, per the docs: {"orderNotificationType":"IPNCHANGE","orderTrackingId":"...","orderMerchantReference":"...","status":200}. Use status: 500 if you received the IPN but could not finish processing.
The IPN URL must be publicly reachable. The docs say to whitelist calls from Pesapal's domain if you filter traffic, and warn that IP whitelisting is not feasible because their IPs may change without notice.
<?php
// routes/api.php: Route::match(['get', 'post'], '/pesapal/ipn', PesapalIpnController::class);
namespace App\Http\Controllers;
use App\Models\Order;
use App\Services\PesapalService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class PesapalIpnController extends Controller
{
public function __invoke(Request $request, PesapalService $pesapal)
{
$ack = [
'orderNotificationType' => (string) $request->input('OrderNotificationType'),
'orderTrackingId' => (string) $request->input('OrderTrackingId'),
'orderMerchantReference' => (string) $request->input('OrderMerchantReference'),
];
try {
// Never trust the IPN itself: ask Pesapal for the real status.
$s = $pesapal->status($ack['orderTrackingId']);
DB::transaction(function () use ($s, $ack) {
$order = Order::where('ref', $s['merchant_reference'] ?? null)
->where('tracking_id', $ack['orderTrackingId'])
->lockForUpdate()->first();
if (! $order || $order->status !== 'pending') {
return; // unknown, or already final: idempotent no-op
}
$code = (int) ($s['status_code'] ?? 0);
if ($code === 1) {
$ok = (float) $s['amount'] === (float) $order->amount && $s['currency'] === $order->currency;
$order->update(['status' => $ok ? 'paid' : 'review', 'confirmation_code' => $s['confirmation_code']]);
} elseif ($code === 2) {
$order->update(['status' => 'failed']);
}
});
return response()->json($ack + ['status' => 200]);
} catch (\Throwable $e) {
report($e);
return response()->json($ack + ['status' => 500]);
}
}
}Security: Because IPNs carry no signature, the GetTransactionStatus call is your verification step. Skipping it means anyone who learns your IPN URL can mark orders as paid.
Status checks and reconciliation
Call GetTransactionStatus in three places: in the IPN handler, on your return (callback) page, and in a scheduled job for orders still PENDING after some minutes (in case an IPN never arrived).
status_code 0 (INVALID) usually means the customer has not completed payment yet or the tracking id is wrong — keep the order pending and retry later rather than failing it immediately.
import { pesapal } from "./pesapal.mjs";
// pendingOrders: [{ ref, trackingId, createdAt }] from your DB, older than ~5 minutes.
export async function reconcile(pendingOrders, applyStatus) {
for (const o of pendingOrders) {
if (!o.trackingId) continue;
try {
const s = await pesapal(
"GET",
"/api/Transactions/GetTransactionStatus?orderTrackingId=" + encodeURIComponent(o.trackingId)
);
// Same idempotent function the IPN handler uses.
await applyStatus(o.ref, s);
} catch (err) {
console.warn("status check failed for", o.ref, err.message);
}
}
}Refunds
POST {base}/api/Transactions/RefundRequest (bearer token) with body fields confirmation_code (from GetTransactionStatus), amount, username (who requested it) and remarks.
Rules from the docs:
- Only payments with status COMPLETED can be refunded, in the original currency, and not more than the amount collected.
- Partial refunds are allowed for card payments only; mobile-money payments can only be refunded in full.
- Only one refund per payment.
- A
200response means the request was received; the merchant must approve it and Pesapal's finance team processes it, so the money is not returned instantly.
import { pesapal } from "./pesapal.mjs";
export async function requestRefund(order, amount, staffUsername, reason) {
if (order.status !== "PAID" || !order.confirmationCode) throw new Error("Only completed payments can be refunded");
if (amount > order.amount) throw new Error("Refund exceeds amount collected");
const out = await pesapal("POST", "/api/Transactions/RefundRequest", {
confirmation_code: order.confirmationCode,
amount: amount.toFixed(2),
username: staffUsername,
remarks: String(reason).slice(0, 100),
});
// Received, not yet paid out: track it as REFUND_REQUESTED until Pesapal completes it.
order.refundStatus = "REQUESTED";
return out;
}Warning: The RefundRequest page does not state the HTTP method in text and its sample response uses status where the field table says error. POST is used here because the endpoint takes a JSON body; confirm with a sandbox call.
Errors
API errors come back as an error object with error_type, code and message, plus a status. Always log error.code and error.message with your order reference.
- 401 / invalid token — expired token (they last up to 5 minutes) or keys from the other environment.
- Validation errors on SubmitOrderRequest — duplicate
id, invalid characters inid, description over 100 characters, missing both email and phone inbilling_address, unknownnotification_id. - RefundRequest rejected (500) — the message explains why (e.g. not COMPLETED, already refunded, partial refund on mobile money).
Tip: The API 3.0 pages do not publish a complete error-code table. Handle errors generically and surface error.message to your logs, not to customers.
Going to production
- Switch the base URL to
https://pay.pesapal.com/v3and use the production key/secret emailed to your merchant account. - Register the IPN again against production and update
PESAPAL_IPN_ID. - Use stable HTTPS URLs on your own domain for IPN and callback (no tunnels).
- Persist orders in a database with unique merchant references and atomic, conditional status updates.
- Schedule reconciliation for stale pending orders, and alert on repeated 500 acknowledgements.
Security checklist
- Consumer key/secret only in server-side environment variables or a secrets manager.
- Amount, currency and reference come from your database.
- IPNs and callback redirects are untrusted hints; GetTransactionStatus from your server is the only source of truth.
- Check
merchant_reference,amountandcurrencybefore fulfilling; route mismatches to manual review. - Idempotent updates: only
PENDINGorders move toPAID/FAILED; duplicates are no-ops. - Restrict refund endpoints to authorised staff and audit who requested each refund (
username).
Security: Do not show 'Payment successful' because the customer returned to your site. Show 'confirming' until your server has a COMPLETED status.
Testing
- Load sandbox demo keys, expose your server with an HTTPS tunnel, and register the IPN with the tunnel URL.
- Create an order, open the
redirect_url, and complete a sandbox payment; confirm the IPN arrives and the order becomesPAID. - Replay the same IPN with curl and confirm nothing changes.
- Send an IPN with a made-up tracking id and confirm no order changes.
- Stop your server during a payment, restart, and confirm the reconciliation job completes the order.
# Replay: use a real OrderTrackingId saved on your order; repeat it to test idempotency
curl -s "http://localhost:3000/pesapal/ipn?OrderTrackingId=REPLACE_WITH_TRACKING_ID&OrderMerchantReference=ORD-1001&OrderNotificationType=IPNCHANGE"
# Forged: unknown tracking id must not change any order
curl -s "http://localhost:3000/pesapal/ipn?OrderTrackingId=00000000-0000-0000-0000-000000000000&OrderMerchantReference=ORD-1001&OrderNotificationType=IPNCHANGE"Common mistakes
- Trusting the callback redirect or the IPN as proof of payment — neither contains the status.
- Caching the token for an hour — it lasts up to 5 minutes.
- Using a sandbox
notification_idin production (or the reverse). - Reusing the same
idfor a retry — every order request needs a unique merchant reference; create a new attempt id (e.g.ORD-1001-2) and map it back to the order. - Not answering the IPN with the JSON acknowledgement, or answering 200 before processing finished.
- Sending amounts in cents — Pesapal expects decimal major units.
- Mixing API 2.0 (XML) and API 3.0 (JSON) examples.
Troubleshooting
- 401 on every call: token expired or wrong environment; print
BASE_URLand confirm the key pair belongs to it. - IPN never arrives: confirm it was registered for this environment (
GetIpnList), that it is public HTTPS, and that firewalls/WAFs or CSRF middleware are not blocking Pesapal. Your reconciliation job should still complete orders. status_codestays 0 (INVALID): the customer has not finished paying, or you passed the merchant reference instead oforderTrackingId.- Order found but amount mismatch: you changed the cart after submitting the order; submit a new order request with a new reference.
- iframe shows a blank page or the callback opens inside the iframe: set
redirect_modetoPARENT_WINDOWor use a full redirect.
Tip: Laravel and Django protect POST routes with CSRF checks. Exclude the IPN route (routes/api.php in Laravel, @csrf_exempt in Django) or Pesapal's POST IPNs will be rejected.
Further reading
- API 3.0 reference — also lists recurring payments and order cancellation.
- GetIpnList — check which IPN URLs are registered.
- Related Metatron guides: M-Pesa Daraja STK Push (direct M-Pesa) and Flutterwave / Paystack for other African markets.
Official documentation
Checked 2026-11-25.
Official documentation
Sources
More payment guides
- Pesapal provider profile
- Adyen Checkout: Sessions flow, Drop-in and HMAC webhooks
- Airtel Money Collections: USSD Push with the Airtel Africa Open API
- Flutterwave Checkout (Standard): hosted payment page, webhooks, verify and refunds
- M-Pesa Daraja STK Push (Lipa na M-Pesa Online)
- MTN MoMo Collections: Request to Pay with the MoMo Open API
- Mercado Pago Checkout Pro: preferences, back URLs and signed webhooks
- Mollie Payments API: hosted checkout, webhooks and refunds
- PayHero Kenya: M-Pesa STK Push via the PayHero API