Create hosted payment links, or take MTN MoMo and Airtel Money without redirecting your customer, and follow every payment state through signed webhooks or status checks. Test everything in the sandbox first.
You are on the GatePay production service.
It accepts live credentials only (ci_live_ / cs_live_, mode "live"). Sandbox is a separate GatePay environment with its own site, merchant IDs and test credentials: build and test your integration there first.
When you are ready, register and complete onboarding on production (business details, identity verification and business verification) to receive new live merchant IDs and keys. Sandbox examples below work unchanged on the sandbox site.
Authentication
Every request is signed with your mode-matching client secret and, apart from the token request, carries a short-lived access token. Keep the secret on your server and send JSON explicitly.
Environment-aware API integration GatePay supports sandbox testing and live production processing through the same endpoints. Always complete payment, redirect, status, and webhook testing in sandbox before switching your server integration to live credentials.
Environment configuration
Sandbox mode
Use for: Development, integration testing, simulated provider outcomes, and webhook verification.
Request mode:sandbox
Credentials:ci_test_... and cs_test_...
Processing: Uses sandbox merchant and payment records. No real provider charge or wallet balance movement occurs.
Live mode
Use for: Production payment links, real gateway processing, and customer wallet payments.
Request mode:live
Credentials:ci_live_... and cs_live_...
Processing: Uses production merchant records and the payment gateways configured by the GatePay administrator.
01Choose the modesandbox uses the sandbox database. Live uses production services.02Match the credentialsci_test_ / cs_test_ or ci_live_ / cs_live_.03Send JSON headersUse JSON Accept on every request and JSON Content-Type on POST requests.
Signed requests with short-lived tokens
Your client secret never travels over the network. Instead, every request carries an HMAC-SHA256 signature made with the secret, and API calls also carry a short-lived JWT access token.
01Get a tokenPOST /v1/auth/token with X-Client-Id and a signature. The token is valid for 15 minutes; reuse it until it expires.02Sign each callSend Authorization: Bearer <token> plus a fresh timestamp, nonce and signature on every request.03Use HTTPSLive traffic must use HTTPS. Plain HTTP requests are refused with https_required.
Required headers
Header
Value
Required
Description
Accept
application/json
Yes
Required on POST and GET.
Content-Type
application/json
POST
Required on requests with a body.
X-Client-Id
ci_test_...
Token request
Merchant application client ID. Only needed when requesting a token.
Authorization
Bearer eyJ...
API calls
Access token from /v1/auth/token. Expires after 15 minutes; it is tied to your app and mode.
X-GatePay-Timestamp
1763290000
Yes
Unix time in seconds. Must be within 5 minutes of server time.
X-GatePay-Nonce
9f2c7a1e...
Yes
A random value, 16 to 64 characters (letters, digits, - and _). Each nonce can be used only once.
X-GatePay-Signature
64 hex characters
Yes
Lower-case hex HMAC-SHA256 of the canonical string, keyed with your client secret.
Canonical string
Join these five values with a newline (\n) and sign the result with HMAC-SHA256 using your client secret:
METHOD upper case, e.g. POST
PATH_AND_QUERY exactly as sent, e.g. /api/v1/transactions?mode=live&status=SUCCESS
TIMESTAMP the X-GatePay-Timestamp value
NONCE the X-GatePay-Nonce value
BODY_SHA256 lower-case hex SHA-256 of the raw body (of an empty string for GET)
Shell helper and token request
# Sign one request: sign METHOD PATH_AND_QUERY BODY
# PATH_AND_QUERY is the path exactly as sent, e.g. /api/v1/payments or /api/v1/transactions?mode=live
sign() {
TS=$(date +%s)
NONCE=$(openssl rand -hex 16)
BODY_HASH=$(printf '%s' "$3" | openssl dgst -sha256 -hex | sed 's/^.* //')
SIGNATURE=$(printf '%s\n%s\n%s\n%s\n%s' "$1" "$2" "$TS" "$NONCE" "$BODY_HASH" \
| openssl dgst -sha256 -hmac "$CLIENT_SECRET" -hex | sed 's/^.* //')
}
# 1. Get a 15-minute access token
BODY='{"mode":"sandbox"}'
sign POST /api/v1/auth/token "$BODY"
curl --request POST 'https://uatstage.gatepay.co.zm/api/v1/auth/token' \
--header 'Accept: application/json' \
--header 'Content-Type: application/json' \
--header "X-Client-Id: $CLIENT_ID" \
--header "X-GatePay-Timestamp: $TS" \
--header "X-GatePay-Nonce: $NONCE" \
--header "X-GatePay-Signature: $SIGNATURE" \
--data "$BODY"
Security notice Keep the client secret on your server only, never in a browser or mobile app. GatePay stores it encrypted and shows it only once, when it is generated; if it is lost, regenerate it from your merchant dashboard. Requests that send the secret in a header (X-Client-Secret) are refused. Live mode also requires an approved business verification (KYB).
Sample code
Complete, working examples that sign requests, get an access token, push a mobile money PIN prompt (no redirect) and handle the repeat-payment confirmation. Set GATEPAY_CLIENT_ID and GATEPAY_CLIENT_SECRET in the environment of your server; never put the secret in a browser or mobile app.
GatePayClient.cs · .NET 6 or later, no extra packages.
Download
// GatePay merchant API: C# (.NET 6 or later), no extra packages.
// Every call is signed with HMAC-SHA256; API calls also send a 15-minute bearer token.
// Keep the client secret on your server only.
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
public sealed class GatePayClient
{
private readonly HttpClient _http = new();
private readonly string _baseUrl;
private readonly string _clientId;
private readonly string _clientSecret;
private string? _token;
private DateTimeOffset _tokenExpires;
public GatePayClient(string baseUrl, string clientId, string clientSecret)
{
_baseUrl = baseUrl.TrimEnd('/');
_clientId = clientId;
_clientSecret = clientSecret;
}
private static string Hex(byte[] bytes) => Convert.ToHexString(bytes).ToLowerInvariant();
// canonical = METHOD \n PATH_AND_QUERY \n TIMESTAMP \n NONCE \n hex(SHA-256(body))
private HttpRequestMessage Signed(HttpMethod method, string path, string body)
{
var url = _baseUrl + path;
var pathAndQuery = new Uri(url).PathAndQuery;
var timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString();
var nonce = Guid.NewGuid().ToString("N");
var bodyHash = Hex(SHA256.HashData(Encoding.UTF8.GetBytes(body)));
var canonical = $"{method.Method.ToUpperInvariant()}\n{pathAndQuery}\n{timestamp}\n{nonce}\n{bodyHash}";
using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(_clientSecret));
var signature = Hex(hmac.ComputeHash(Encoding.UTF8.GetBytes(canonical)));
var request = new HttpRequestMessage(method, url);
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Headers.Add("X-GatePay-Timestamp", timestamp);
request.Headers.Add("X-GatePay-Nonce", nonce);
request.Headers.Add("X-GatePay-Signature", signature);
if (method != HttpMethod.Get)
{
request.Content = new StringContent(body, Encoding.UTF8, "application/json");
}
return request;
}
private async Task<string> AccessTokenAsync(string mode)
{
if (_token is not null && DateTimeOffset.UtcNow < _tokenExpires) return _token;
var request = Signed(HttpMethod.Post, "/v1/auth/token", JsonSerializer.Serialize(new { mode }));
request.Headers.Add("X-Client-Id", _clientId);
using var response = await _http.SendAsync(request);
using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
var records = json.RootElement.GetProperty("response").GetProperty("records");
if (!response.IsSuccessStatusCode) throw new InvalidOperationException("Token request failed: " + records.GetProperty("code"));
_token = records.GetProperty("access_token").GetString();
_tokenExpires = DateTimeOffset.UtcNow.AddSeconds(records.GetProperty("expires_in").GetInt32() - 60);
return _token!;
}
/// <summary>POST a JSON body to an API path such as "/v1/collections". Returns the HTTP status and the JSON reply.</summary>
public async Task<(int Status, JsonElement Body)> PostAsync(string mode, string path, object payload)
{
var token = await AccessTokenAsync(mode);
var request = Signed(HttpMethod.Post, path, JsonSerializer.Serialize(payload));
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
using var response = await _http.SendAsync(request);
using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
return ((int)response.StatusCode, json.RootElement.Clone());
}
}
public static class Program
{
public static async Task Main()
{
var gatepay = new GatePayClient(
Environment.GetEnvironmentVariable("GATEPAY_BASE_URL") ?? "https://uatstage.gatepay.co.zm/api",
Environment.GetEnvironmentVariable("GATEPAY_CLIENT_ID")!,
Environment.GetEnvironmentVariable("GATEPAY_CLIENT_SECRET")!);
// Push an MTN MoMo PIN prompt to the customer's phone (no redirect). +46733123453 is the sandbox test
// number that always succeeds; in live mode send the customer's own number, e.g. +260961234567.
var payload = new Dictionary<string, object>
{
["mode"] = "sandbox",
["provider"] = "mtn",
["phone"] = "+46733123453",
["amount"] = "25.00",
["currency"] = "ZMW",
["reference"] = "ORDER-" + DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
["callback_url"] = "https://merchant.example/webhooks/gatepay",
};
var (status, body) = await gatepay.PostAsync("sandbox", "/v1/collections", payload);
var records = body.GetProperty("response").GetProperty("records");
Console.WriteLine($"{status} {records.GetProperty("code")}");
// 409 repeat_payment_confirmation_required: the same phone paid you the same amount less than a minute ago.
// Ask the customer for the 6-digit code they received, then send the same request again with:
// payload["repeat_confirmation_token"] = records.GetProperty("repeat_confirmation_token").GetString();
// payload["repeat_confirmation_code"] = codeFromCustomer;
}
}
GatePayClient.java · Java 17 or later, standard library only.
Download
// GatePay merchant API: Java 17 or later, standard library only.
// Every call is signed with HMAC-SHA256; API calls also send a 15-minute bearer token.
// Keep the client secret on your server only. Use a JSON library (Jackson, Gson) in real code.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Instant;
import java.util.HexFormat;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class GatePayClient {
private final HttpClient http = HttpClient.newHttpClient();
private final String baseUrl;
private final String clientId;
private final String clientSecret;
private String token;
private long tokenExpiresAt;
public GatePayClient(String baseUrl, String clientId, String clientSecret) {
this.baseUrl = baseUrl.replaceAll("/+$", "");
this.clientId = clientId;
this.clientSecret = clientSecret;
}
private static String hex(byte[] bytes) {
return HexFormat.of().formatHex(bytes);
}
// canonical = METHOD \n PATH_AND_QUERY \n TIMESTAMP \n NONCE \n hex(SHA-256(body))
private HttpRequest.Builder signed(String method, String path, String body) throws Exception {
URI uri = URI.create(baseUrl + path);
String pathAndQuery = uri.getRawPath() + (uri.getRawQuery() != null ? "?" + uri.getRawQuery() : "");
String timestamp = String.valueOf(Instant.now().getEpochSecond());
String nonce = UUID.randomUUID().toString().replace("-", "");
String bodyHash = hex(MessageDigest.getInstance("SHA-256").digest(body.getBytes(StandardCharsets.UTF_8)));
String canonical = method + "\n" + pathAndQuery + "\n" + timestamp + "\n" + nonce + "\n" + bodyHash;
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(clientSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
String signature = hex(mac.doFinal(canonical.getBytes(StandardCharsets.UTF_8)));
return HttpRequest.newBuilder(uri)
.header("Accept", "application/json")
.header("Content-Type", "application/json")
.header("X-GatePay-Timestamp", timestamp)
.header("X-GatePay-Nonce", nonce)
.header("X-GatePay-Signature", signature)
.method(method, "GET".equals(method) ? HttpRequest.BodyPublishers.noBody() : HttpRequest.BodyPublishers.ofString(body));
}
/** Minimal field reader so the sample has no dependencies. */
static String field(String json, String name) {
Matcher m = Pattern.compile("\"" + name + "\"\\s*:\\s*\"?([^\",}]+)").matcher(json);
return m.find() ? m.group(1) : null;
}
/** The machine-readable result code inside "records" (e.g. collection_initiated, validation_error). */
static String resultCode(String json) {
int records = json.indexOf("\"records\"");
return records < 0 ? null : field(json.substring(records), "code");
}
private String accessToken(String mode) throws Exception {
if (token != null && Instant.now().getEpochSecond() < tokenExpiresAt) {
return token;
}
String body = "{\"mode\":\"" + mode + "\"}";
HttpResponse<String> response = http.send(
signed("POST", "/v1/auth/token", body).header("X-Client-Id", clientId).build(),
HttpResponse.BodyHandlers.ofString());
if (response.statusCode() != 200) {
throw new IllegalStateException("Token request failed: " + resultCode(response.body()));
}
token = field(response.body(), "access_token");
tokenExpiresAt = Instant.now().getEpochSecond() + Long.parseLong(field(response.body(), "expires_in")) - 60;
return token;
}
/** POST a JSON body to an API path such as "/v1/collections". */
public HttpResponse<String> post(String mode, String path, String jsonBody) throws Exception {
String bearer = accessToken(mode);
return http.send(signed("POST", path, jsonBody).header("Authorization", "Bearer " + bearer).build(),
HttpResponse.BodyHandlers.ofString());
}
public static void main(String[] args) throws Exception {
String baseUrl = System.getenv().getOrDefault("GATEPAY_BASE_URL", "https://uatstage.gatepay.co.zm/api");
GatePayClient gatepay = new GatePayClient(baseUrl, System.getenv("GATEPAY_CLIENT_ID"), System.getenv("GATEPAY_CLIENT_SECRET"));
// Push an MTN MoMo PIN prompt to the customer's phone (no redirect). +46733123453 is the sandbox test
// number that always succeeds; in live mode send the customer's own number, e.g. +260961234567.
String body = "{\"mode\":\"sandbox\",\"provider\":\"mtn\",\"phone\":\"+46733123453\",\"amount\":\"25.00\","
+ "\"currency\":\"ZMW\",\"reference\":\"ORDER-" + System.currentTimeMillis() + "\","
+ "\"callback_url\":\"https://merchant.example/webhooks/gatepay\"}";
HttpResponse<String> response = gatepay.post("sandbox", "/v1/collections", body);
System.out.println(response.statusCode() + " " + resultCode(response.body()));
// 409 repeat_payment_confirmation_required: the same phone paid you the same amount less than a minute ago.
// Ask the customer for the 6-digit code they received, then send the same body again with
// "repeat_confirmation_token" (from this response) and "repeat_confirmation_code" added.
}
}
gatepay_client.py · Python 3.9 or later with the requests package.
Download
# GatePay merchant API: Python 3.9 or later, with the "requests" package (pip install requests).
# Every call is signed with HMAC-SHA256; API calls also send a 15-minute bearer token.
# Keep the client secret on your server only.
import hashlib
import hmac
import json
import os
import secrets
import time
from urllib.parse import urlsplit
import requests
BASE_URL = os.environ.get("GATEPAY_BASE_URL", "https://uatstage.gatepay.co.zm/api").rstrip("/")
CLIENT_ID = os.environ["GATEPAY_CLIENT_ID"]
CLIENT_SECRET = os.environ["GATEPAY_CLIENT_SECRET"]
_token = {"value": None, "expires": 0.0}
def signed_headers(method, url, body):
"""canonical = METHOD \\n PATH_AND_QUERY \\n TIMESTAMP \\n NONCE \\n hex(SHA-256(body))"""
parts = urlsplit(url)
path_and_query = parts.path + (("?" + parts.query) if parts.query else "")
timestamp = str(int(time.time()))
nonce = secrets.token_hex(16)
body_hash = hashlib.sha256(body.encode("utf-8")).hexdigest()
canonical = "\n".join([method.upper(), path_and_query, timestamp, nonce, body_hash])
signature = hmac.new(CLIENT_SECRET.encode("utf-8"), canonical.encode("utf-8"), hashlib.sha256).hexdigest()
return {
"Accept": "application/json",
"Content-Type": "application/json",
"X-GatePay-Timestamp": timestamp,
"X-GatePay-Nonce": nonce,
"X-GatePay-Signature": signature,
}
def access_token(mode):
if _token["value"] and time.time() < _token["expires"]:
return _token["value"]
url = BASE_URL + "/v1/auth/token"
body = json.dumps({"mode": mode}, separators=(",", ":"))
headers = {**signed_headers("POST", url, body), "X-Client-Id": CLIENT_ID}
reply = requests.post(url, data=body.encode("utf-8"), headers=headers, timeout=30)
records = reply.json()["response"]["records"]
if reply.status_code != 200:
raise RuntimeError("Token request failed: " + str(records.get("code")))
_token.update(value=records["access_token"], expires=time.time() + records["expires_in"] - 60)
return _token["value"]
def post(mode, path, payload):
"""POST a JSON body to an API path such as "/v1/collections"; sign exactly the bytes sent."""
url = BASE_URL + path
body = json.dumps(payload, separators=(",", ":"))
headers = {**signed_headers("POST", url, body), "Authorization": "Bearer " + access_token(mode)}
return requests.post(url, data=body.encode("utf-8"), headers=headers, timeout=60)
if __name__ == "__main__":
# Push an MTN MoMo PIN prompt to the customer's phone (no redirect). +46733123453 is the sandbox test
# number that always succeeds; in live mode send the customer's own number, e.g. +260961234567.
payload = {
"mode": "sandbox",
"provider": "mtn",
"phone": "+46733123453",
"amount": "25.00",
"currency": "ZMW",
"reference": "ORDER-%d" % int(time.time() * 1000),
"callback_url": "https://merchant.example/webhooks/gatepay",
}
reply = post("sandbox", "/v1/collections", payload)
records = reply.json()["response"]["records"]
print(reply.status_code, records.get("code"))
# 409 repeat_payment_confirmation_required: the same phone paid you the same amount less than a minute ago.
# Ask the customer for the 6-digit code they received, then send the same request again:
if reply.status_code == 409 and records.get("code") == "repeat_payment_confirmation_required":
code = os.environ.get("GATEPAY_REPEAT_CODE") or input("Code the customer received: ")
payload.update(repeat_confirmation_token=records["repeat_confirmation_token"], repeat_confirmation_code=code)
reply = post("sandbox", "/v1/collections", payload)
print(reply.status_code, reply.json()["response"]["records"].get("code"))
gatepay_client.php · PHP 8.0 or later with the cURL extension, no framework.
Download
<?php
// GatePay merchant API: PHP 8.0 or later with the cURL extension, no framework.
// Every call is signed with HMAC-SHA256; API calls also send a 15-minute bearer token.
// Keep the client secret on your server only.
$baseUrl = rtrim(getenv('GATEPAY_BASE_URL') ?: 'https://uatstage.gatepay.co.zm/api', '/');
$clientId = (string) getenv('GATEPAY_CLIENT_ID');
$clientSecret = (string) getenv('GATEPAY_CLIENT_SECRET');
/** Send a signed request. canonical = METHOD \n PATH_AND_QUERY \n TIMESTAMP \n NONCE \n hex(SHA-256(body)) */
function gatepay_request(string $baseUrl, string $secret, string $method, string $path, string $body, array $extraHeaders = []): array
{
$url = $baseUrl.$path;
$parts = parse_url($url);
$pathAndQuery = $parts['path'].(isset($parts['query']) ? '?'.$parts['query'] : '');
$timestamp = (string) time();
$nonce = bin2hex(random_bytes(16));
$canonical = strtoupper($method)."\n".$pathAndQuery."\n".$timestamp."\n".$nonce."\n".hash('sha256', $body);
$headers = array_merge([
'Accept: application/json',
'Content-Type: application/json',
'X-GatePay-Timestamp: '.$timestamp,
'X-GatePay-Nonce: '.$nonce,
'X-GatePay-Signature: '.hash_hmac('sha256', $canonical, $secret),
], $extraHeaders);
$curl = curl_init($url);
curl_setopt_array($curl, [
CURLOPT_CUSTOMREQUEST => strtoupper($method),
CURLOPT_HTTPHEADER => $headers,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 60,
]);
if (strtoupper($method) !== 'GET') {
curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
}
$reply = curl_exec($curl);
$status = (int) curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
return [$status, json_decode((string) $reply, true) ?: []];
}
// 1. Access token (valid 15 minutes; cache it and reuse it).
[$status, $token] = gatepay_request($baseUrl, $clientSecret, 'POST', '/v1/auth/token', json_encode(['mode' => 'sandbox']), ['X-Client-Id: '.$clientId]);
if ($status !== 200) {
exit('Token request failed: '.($token['response']['records']['code'] ?? $status).PHP_EOL);
}
$accessToken = $token['response']['records']['access_token'];
// 2. Push an MTN MoMo PIN prompt to the customer's phone (no redirect). +46733123453 is the sandbox test
// number that always succeeds; in live mode send the customer's own number, e.g. +260961234567.
$payload = [
'mode' => 'sandbox',
'provider' => 'mtn',
'phone' => '+46733123453',
'amount' => '25.00',
'currency' => 'ZMW',
'reference' => 'ORDER-'.round(microtime(true) * 1000),
'callback_url' => 'https://merchant.example/webhooks/gatepay',
];
[$status, $result] = gatepay_request($baseUrl, $clientSecret, 'POST', '/v1/collections', json_encode($payload), ['Authorization: Bearer '.$accessToken]);
echo $status, ' ', $result['response']['records']['code'] ?? '', PHP_EOL;
// 409 repeat_payment_confirmation_required: the same phone paid you the same amount less than a minute ago.
// Ask the customer for the 6-digit code they received, then send the same request again.
if ($status === 409 && ($result['response']['records']['code'] ?? '') === 'repeat_payment_confirmation_required') {
$payload['repeat_confirmation_token'] = $result['response']['records']['repeat_confirmation_token'];
$payload['repeat_confirmation_code'] = getenv('GATEPAY_REPEAT_CODE') ?: trim((string) readline('Code the customer received: '));
[$status, $result] = gatepay_request($baseUrl, $clientSecret, 'POST', '/v1/collections', json_encode($payload), ['Authorization: Bearer '.$accessToken]);
echo $status, ' ', $result['response']['records']['code'] ?? '', PHP_EOL;
}
Quick start
A complete integration starts on your server and ends with webhook verification or a status lookup. The hosted checkout handles the customer-facing payment step.
01Generate credentialsGenerate sandbox or live credentials in the merchant dashboard and store the secret on your server (it is shown once).02Create the linkPOST payment information with the selected currency. Do not send payment_methods.03Redirect customerOpen the returned payment_url in the customer browser.04Process returnRead trx_reference and your original reference from the merchant URL.05Verify paymentUse the signed success webhook or poll by your merchant reference.06Handle idempotentlyDeduplicate webhook deliveries and safely handle repeated callbacks.
Merchant setup and credentials
The REST API is available through an Express merchant application. GatePay creates credentials for the merchant mode, while every request remains scoped to the authenticated application and its owning merchant.
Merchant dashboard
One Express merchant, mode-specific credentials
Open Merchant, select the Express merchant, and use App Info / Merchant Credentials to copy the client ID and secret. Credentials are server-side secrets and must never be exposed in browser or mobile application code.
Merchant typeExpress
Required statusApproved
Owner statusActive
Credential sourceApp Info
Register or create an Express merchantFrontend merchant registration creates the Express merchant application and its initial mode-specific credential pair.
Complete approvalThe Express merchant must be Approved, and its owning GatePay user must be Active in both sandbox and live requests.
Copy credentials securelyUse the client ID and client secret from App Info / Merchant Credentials only from your backend server.
Rotate when necessaryCredential regeneration requires verification. After rotation, the previous client ID and secret stop authenticating immediately.
Environment credential matrix
Mode
Client ID
Client secret
Data and processing
sandbox
ci_test_...
cs_test_...
Merchant application and payment records use the sandbox database. Provider outcomes are simulated and no wallet balance moves.
live
ci_live_...
cs_live_...
Merchant application and payment records use production data and configured live gateway processors.
Credential mode is enforced. The mode in the request body, both credential prefixes, and the database containing the merchant application must agree. Mixed or mode-incompatible credentials are rejected before payment data is stored.
Currency and gateway rules
GatePay derives payment methods from the selected currency. Do not send payment_methods in a create-payment request.
Requests containing payment_methods are rejected with HTTP 422. Existing unpaid links use current currency settings.
The response payment_methods array is a creation-time snapshot. Checkout rechecks availability before starting a payment.
Admin-managed availability. Checkout shows active supported methods enabled for Merchant payment in the selected currency.
Runtime decision order
01
Validate the currency
The currency code must exist, be Active, and have the Fiat type. Crypto currency records are not accepted as the payment currency.
02
Match the business currency
The payment currency must be the same currency assigned to the authenticated business. A different currency is rejected before a payment link is created.
03
Resolve currency payment methods
GatePay resolves all active payment methods with a supported REST API processor.
04
Apply Merchant payment activation
Checkout shows active supported methods enabled for Merchant payment in the selected currency.
05
Apply Wallet requirements
Wallet follows the Wallet payment flow. Live payments require an eligible payer wallet, while sandbox payments use demo wallet outcomes.
06
Calculate Merchant payment fees
Gateway percentage and fixed charges come from the Payment_Received transaction type shown as Merchant payment, then the merchant group fee and fee-bearer rule are applied.
Configuration matrix
Method or rule
Required configuration
Checkout behavior
Wallet, Mtn, Airtel, Cybersource
Checkout shows active supported methods enabled for Merchant payment in the selected currency.
Wallet requires an active logged-in payer with an eligible wallet. MTN and Airtel are guest, asynchronous mobile-money checkouts. Airtel Zambia accepts ZMW only. Cybersource uses Secure Acceptance Hosted Checkout and settles only after signature validation with decision=ACCEPT and reason_code=100.
Mtn provider prerequisites
MTN uses the administrator-configured provider mode and the credentials required by that mode; a public HTTPS callback URL and the MTN reconciliation scheduler are also required.
The REST payment remains pending after RequestToPay is accepted and becomes final through polling, callback verification, or scheduled reconciliation—even if the customer closes the tab.
Airtel provider prerequisites
Airtel must be activated for Merchant payment on ZMW. Live REST payments use the administrator-selected Airtel Collection environment and credentials, authenticated callback URL, and reconciliation scheduler.
The customer enters a Zambian Airtel number and approves on the phone. An accepted collection request remains pending until Airtel confirms success; only then is the merchant wallet credited once.
Merchant receiver wallet
No wallet check is performed when the payment link is created.
After a successful live payment, GatePay creates the merchant currency wallet if it does not already exist, then credits it once.
Availability is currency-based. GatePay excludes unavailable methods and returns payment_methods_unavailable only when no eligible methods remain.
POST
Create payment link
Creates a hosted checkout link for an approved merchant, active fiat currency, and payment methods enabled for merchant payment.
https://uatstage.gatepay.co.zm/api/v1/payments
Credentials requiredSandbox and liveActive fiat currency
Payment method selection. Payment methods are determined by the selected currency. Do not send payment_methods; requests containing it are rejected with HTTP 422. External gateways must be active for merchant payment and the selected currency. Airtel requires ZMW and Collection credentials for live-mode payments. Cybersource additionally requires active Payment Received fees and limits plus Secure Acceptance Hosted Checkout credentials (profile_id, access_key, secret_key, mode).
Request body
Field
Type
Required
Description
mode
string
Yes
sandbox or live.
amount
string
Yes
Positive decimal with up to eight decimal places.
currency
string
Yes
Active three-letter fiat currency code matching the currency assigned to the authenticated business.
reference
string
Yes
Your unique reference, up to 100 characters.
success_url
URL
Yes
Return URL for success and pending outcomes.
webhook_url
URL
Yes
Public endpoint for payment lifecycle events.
cancel_url
URL
Yes
Return URL for failed and cancelled outcomes.
description
string
Optional
Payment description, up to 1000 characters.
metadata
object
Optional
Up to 20 scalar key-value pairs.
Merchant ID is prohibited. GatePay derives the merchant from the authenticated application. Live URLs must use HTTPS, and callback_url is not accepted; use success_url.
# 2. Call the API with the token and a fresh signature
BODY='{"mode":"sandbox","amount":"100.00","currency":"ZMW","reference":"ORDER-1001","success_url":"https://merchant.example/payments/success","webhook_url":"https://merchant.example/webhooks/payments","cancel_url":"https://merchant.example/payments/cancel","description":"Payment for order 1001","metadata":{"order_id":"1001"}}'
sign POST /api/v1/payments "$BODY"
curl --request POST 'https://uatstage.gatepay.co.zm/api/v1/payments' \
--header 'Accept: application/json' \
--header 'Content-Type: application/json' \
--header "Authorization: Bearer $ACCESS_TOKEN" \
--header "X-GatePay-Timestamp: $TS" \
--header "X-GatePay-Nonce: $NONCE" \
--header "X-GatePay-Signature: $SIGNATURE" \
--data "$BODY"
Idempotency: Repeating the same reference with the identical payload returns the existing link with HTTP 200. Reusing it with changed data returns HTTP 409.
GET
Verify transaction status
Fetches the current public transaction status using the exact merchant reference supplied during link creation. A found transaction always returns HTTP 200.
use Illuminate\Support\Facades\Http;
// Sign the path and query exactly as they are sent.
$pathAndQuery = '/api/v1/payments/status?mode=sandbox&reference=ORDER-1001';
$response = Http::acceptJson()
->withToken(gatepayToken('sandbox'))
->withHeaders(gatepaySignature('GET', $pathAndQuery, ''))
->get('https://uatstage.gatepay.co.zm/api/v1/payments/status?mode=sandbox&reference=ORDER-1001');
Choose the integration that fits your product. Both use the same credentials, webhooks and sandbox.
Payment link (redirect)
Pay without redirect (direct mobile money)
Customer experience
Customer is sent to a GatePay checkout page and back.
Customer stays in your app, website, POS or call centre; the PIN prompt arrives on their phone.
Channels
Wallet, MTN MoMo, Airtel Money, Visa / Mastercard
MTN MoMo, Airtel Money
Endpoint
POST /v1/payments
POST /v1/collections
Best for
Online shops, invoices, card payments
Mobile and USSD apps, ticketing, utilities, schools, server-to-server billing
Integration steps
Get your sandbox Client ID and Client Secret from the merchant portal: Merchant → Business → Secret Codes (the gear icon).
Optional but recommended: add your server's public IP addresses under Merchant → Business → Allowed sources (the shield icon).
Collect the customer's phone number and amount in your own screen, then call POST /v1/collections with mode "sandbox" and a unique reference.
Show "Approve the payment on your phone" to the customer. In sandbox the result comes back at once; in live the customer has about 30 seconds to approve.
Receive the result on your callback_url (verify the signature), or check GET /v1/collections/{reference}. Only fulfil the order on SUCCESS.
Test every outcome with the sandbox test numbers, then switch to live credentials and mode "live".
What happens after the prompt is sent
Time
What GatePay does
0 s
Sends the PIN prompt to the customer's phone and replies 202 PENDING (or waits, if wait_for_result is true).
5 – 30 s
Checks MTN or Airtel every 5 seconds, up to 6 times.
Success
Records the payment, credits your wallet once and posts payment.status.success to your callback_url.
Failed, rejected or expired
Updates the status and posts the matching event. Your wallet is not changed.
Still pending after 30 s
Scheduled reconciliation keeps checking until the provider gives a final answer, then posts the event.
Your balance only moves on success. Pending, failed, cancelled and expired payments never change a wallet balance, so you can safely retry with a new reference.
POST
Mobile money collection (no redirect)
Use this when your own app or website collects the customer's phone number. GatePay sends the MTN MoMo or Airtel Money PIN prompt straight to the customer's phone; the customer never leaves your system and no checkout page is shown. The response returns immediately with status PENDING, and the final result is sent to your callback_url as a signed webhook.
https://uatstage.gatepay.co.zm/api/v1/collections
Bearer token and signatureMTN MoMo, Airtel MoneyIdempotent by reference
How it works
Your system sends provider, phone, amount, currency, reference and callback_url.
GatePay replies 202 PENDING and the customer receives the PIN prompt on their phone.
The customer approves with their PIN.
GatePay posts the final result (payment.status.success, payment.status.failed, payment.status.expired) to your callback_url. You can also check the status endpoint at any time.
Request body
Field
Required
Description
mode
Yes
sandbox or live, matching your credentials.
provider
Yes
mtn or airtel.
phone
Yes
Customer's mobile money number: +260961234567, 260961234567 or 0961234567.
amount
Yes
Decimal string, for example "250.00".
currency
Yes
ISO code, for example ZMW.
reference
Yes
Your unique order or ticket reference (max 100). Sending the same reference again returns the existing payment and does not prompt the customer twice.
callback_url
Yes
Where GatePay posts the result. Must be HTTPS in live mode.
description
No
Short text shown on the customer's prompt where the provider supports it (max 160).
metadata
No
Up to 20 key-value pairs returned to you unchanged.
wait_for_result
No
true to wait (about 30 seconds) for the customer to approve and get the final status in this response (201). Default false: reply 202 at once.
customer_email
No
Customer's email. Used only to also send a repeat-payment confirmation code (see below).
repeat_confirmation_token
Only after a 409
The token from a 409 repeat_payment_confirmation_required response.
repeat_confirmation_code
Only after a 409
The 6-digit code the customer received by SMS (and email if given).
Access token and request signature for the chosen mode. See Authentication.
X-Customer-IP
No
The end customer's IP address. Used by anti-money-laundering monitoring; send it when you have it.
X-Device-Id
No
A stable ID for the customer's device or app install (max 100). Also used for AML monitoring.
# BODY holds the JSON below; sign it with the helper from Authentication
sign POST /api/v1/collections "$BODY"
curl -X POST https://uatstage.gatepay.co.zm/api/v1/collections \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "X-GatePay-Timestamp: $TS" \
-H "X-GatePay-Nonce: $NONCE" \
-H "X-GatePay-Signature: $SIGNATURE" \
-d '{
"mode": "sandbox",
"provider": "mtn",
"phone": "0961234567",
"amount": "250.00",
"currency": "ZMW",
"reference": "TRIP-10482",
"callback_url": "https://yourapp.co.zm/webhooks/gatepay",
"description": "Bus fare Lusaka to Kitwe"
}'
202 Accepted (prompt sent, waiting for the customer)
{
"response": {
"status": { "code": 202, "message": "Collection request accepted." },
"records": {
"code": "collection_initiated",
"trx_reference": "01M7FED17WKZ1DZHYSR30AQZQ2",
"reference": "TRIP-10482",
"status": "PENDING",
"mode": "live",
"provider": "mtn",
"channel": "direct_api",
"payer_phone": "+260961***567",
"amount": "250.00000000",
"currency": "ZMW",
"message": "A payment prompt has been sent to the customer's phone. The result will be sent to your callback URL."
}
}
}
In sandbox mode the result is decided immediately by the test numbers below, so you receive 201 with SUCCESS, FAILED or PENDING. Any other number succeeds.
Provider
Test number
Outcome
MTN
+46733123450
FAILED
MTN
+46733123451
PENDING
MTN
+46733123452
EXPIRED
MTN
+46733123453
SUCCESS
Airtel
260970000050
FAILED
Airtel
260970000051
PENDING
Airtel
260970000052
EXPIRED
Airtel
260970000053
SUCCESS
Errors
HTTP
Code
Meaning
401
invalid_credentials
Client ID or secret is wrong.
403
credential_mode_mismatch
Sandbox credentials were used with mode "live", or the other way round.
403
source_not_allowed
The call came from an IP address that is not on your Allowed sources list.
403
merchant_not_active
Your business is not approved and active yet.
403
merchant_deleted
Your business has been deleted and can no longer accept payments.
422
validation_error
A field is missing or invalid; see errors.
422
provider_unavailable
The provider is not enabled for this currency on your account.
409
reference_conflict
The reference was already used with different details.
409
repeat_payment_confirmation_required
The same phone number paid you the same amount less than a minute ago (under another reference). A 6-digit code was sent to the customer; ask them for it and send the same request again with repeat_confirmation_token and repeat_confirmation_code. If it was a mistake, do nothing.
422
repeat_confirmation_invalid
The confirmation code is wrong, expired (5 minutes) or already used. After 5 wrong codes, start again.
502
provider_request_failed
MTN or Airtel rejected or could not receive the request. Safe to retry with a new reference.
Allowed sources (IP allow-list)
Lock your credentials to your own servers. In the merchant portal open Merchant → Business and click the shield icon, then add each public IP address (for example 41.72.100.15) or range (for example 41.72.100.0/24), up to 25 per business. While the list is empty, calls with valid credentials are accepted from any address; once it has entries, calls from anywhere else are refused with 403 source_not_allowed, even with the right secret. The page shows the address GatePay sees for you.
Result sent to your callback_url
When the payment reaches a final state GatePay posts a signed event to callback_url. Verify the signature as described under Webhooks, answer with any 2xx status, and treat the event id as a deduplication key. Failed deliveries are retried.
Returns the current status of any payment by your reference. If a mobile money payment is still pending, GatePay checks with MTN or Airtel before answering, so polling every 5 to 10 seconds gives a near real-time result. Webhooks remain the recommended way to receive results.
status is one of PENDING, SUCCESS, FAILED, CANCELLED, EXPIRED or REFUNDED. Only SUCCESS means the money was received. A reference that does not exist returns 404.
GET
List transactions
Returns your transactions for the given mode, newest first, including both checkout and direct mobile money payments.
channel is "direct_api" for payments without redirect and "checkout" for payment links, so one call covers both.
Checkout and merchant returns
Redirect the customer to the returned payment_url. Checkout resolves currently available payment methods for the transaction currency and validates the selected method again before processing.
SUCCESSReturns to success_url.PENDINGReturns to success_url while processing continues.FAILEDReturns to cancel_url.CANCELLEDReturns to cancel_url.EXPIREDUnstarted link passed its stored expiry.
Return URL data. GatePay preserves existing merchant query parameters and appends only trx_reference and reference. Treat browser returns as informational and use webhooks or status verification for fulfillment.
Webhooks
GatePay posts lifecycle events to the webhook_url stored on the payment link. Sandbox and live use the same contract, with delivery records stored in their originating environment.
Supported events
Event
Public status
Body signature
payment.status.created
PENDING
Yes
payment.status.success
SUCCESS
Yes
payment.status.failed
FAILED
Yes
payment.status.cancelled
CANCELLED
Yes
payment.status.expired
EXPIRED
Yes
Delivery headers
Header
Description
X-Event
Lifecycle event name.
X-Delivery-Id
Unique ID used to deduplicate at-least-once deliveries.
X-Timestamp
Unix timestamp used to verify the event signature.
Webhook signatures. Every event contains a signature field. It is HMAC-SHA256 of timestamp + "." + unsigned compact JSON body using the matching client secret. Reject timestamps older than five minutes.
Retry policy: Any 2xx response acknowledges delivery. GatePay retries connection failures, timeouts, 408, 429, and 5xx responses immediately, then after 1 minute, 5 minutes, 15 minutes, and 1 hour. Other 4xx responses and redirects are terminal.
Sandbox testing
Sandbox checkout never calls a real provider or changes a wallet balance. Select an enabled method and use one of the demo values below to produce a deterministic result.
Provider rules. MTN and Airtel use local phone simulators and require no provider credentials or network calls in REST sandbox mode. Airtel still requires ZMW. Cybersource uses the generic success, failed, pending, and cancelled simulator in API sandbox mode; live-mode links use Secure Acceptance Hosted Checkout like deposit and invoice.
Testing pay without redirect. Call POST /v1/collections with mode "sandbox" and your sandbox credentials. No prompt is sent to a real phone: the phone number decides the result straight away and you get 201 with the final status, the callback is sent as in live, and GET /v1/collections/{reference} and GET /v1/transactions return the payment. Use the MTN and Airtel numbers below for SUCCESS, FAILED or PENDING; any other valid number succeeds. Test an unknown reference (404), wrong-mode credentials (403 credential_mode_mismatch) and, if you use Allowed sources, a call from an unlisted IP (403 source_not_allowed). See the endpoint
Wallet
WLT-1000000001SUCCESS
WLT-1000000002FAILED
WLT-1000000003PENDING
WLT-1000000004CANCELLED
WLT-1000000005INSUFFICIENT BALANCE
MTN
46733123450FAILED
46733123451PENDING
46733123452EXPIRED
46733123453SUCCESS
Airtel
260970000050FAILED
260970000051PENDING
260970000052EXPIRED
260970000053SUCCESS
Cybersource
successSUCCESS
failedFAILED
pendingPENDING
cancelledCANCELLED
Sandbox & Go Live Checklist
Use this checklist before moving from simulated payments to live checkout. The same REST endpoints work in both environments; the request mode and the complete client credential pair must change together.
Sandbox readiness
Validate the complete integration without calling a real provider or moving wallet balances.
Send mode=sandbox with matching ci_test_... and cs_test_... credentials.
Test successful, failed, pending, cancelled, insufficient-balance, and expired outcomes where supported.
Confirm checkout returns, reference-based status polling, webhook signatures, deduplication, and retry handling.
Use only documented simulator values; sandbox never calls production gateway processors.
Live readiness
Enable real payment processing only after merchant access and production configuration are complete.
Send mode=live with matching ci_live_... and cs_live_... credentials.
The Express merchant must be Approved and its owning user must be Active.
Use an Active fiat currency and only methods enabled by the administrator for Merchant payment.
Configure production gateway credentials and public HTTPS success, webhook, and cancel URLs.
Pay without redirect: add your servers under Allowed sources, use an HTTPS callback_url, and send X-Customer-IP / X-Device-Id where you have them.
Production launch checks
Required before live traffic
Credentials and modeUse the live client ID and secret together with mode=live. Never mix test and live prefixes.
Merchant accessVerify the Express merchant is Approved and the merchant owner remains Active.
Currency and methodsCheckout shows active supported methods enabled for Merchant payment in the selected currency.
Gateway readinessConfigure production credentials and merchant-payment fees for every external gateway offered at checkout.
Wallet flowWallet payers need login, an eligible wallet, and enough balance. A missing merchant receiver wallet is created after successful settlement.
Secure merchant URLsUse public HTTPS success, webhook, and cancel URLs, and safely handle the two returned reference parameters.
Webhook receiverVerify every event HMAC with the matching client secret, reject stale timestamps, deduplicate delivery IDs, and return 2xx quickly.
Verification and operationsPoll status by the exact merchant reference, run webhook queue and scheduler or cron processing, and monitor failed delivery attempts.
Switch the complete environment together. Do not change only mode or one credential. Change mode, client ID, and client secret as one set, keep merchant_id out of the request, and complete a low-value live payment before opening general traffic.
Errors and limits
Every JSON response uses the existing GatePay response envelope. The HTTP status represents request handling; transaction outcomes returned from status verification still use HTTP 200.
HTTP
Machine code examples
Meaning
401
invalid_credentials
Unknown client ID, or the app is not active for this mode.
401
signature_required, signed_request_required
Signature headers missing, or the secret was sent in a header instead of signing.
401
invalid_signature
The signature does not match the method, path, timestamp, nonce or body.
Timestamp more than 5 minutes off, badly formed nonce, or a nonce that was already used.
401
invalid_token, token_expired
Access token altered, issued for another app or mode, or older than 15 minutes. Request a new one.
403
https_required
Live requests must use HTTPS.
403
business_verification_required
Live mode needs an approved business verification (KYB: PACRA, TPIN, directors).
403
credential_mode_mismatch
Credential mode mismatch or unavailable merchant access.
404
transaction_not_found
No transaction for this app and exact reference.
406
not_acceptable
Accept header does not allow JSON.
409
reference_conflict
Reference exists with a changed payload.
415
unsupported_media_type
POST request body is not JSON.
422
validation_error, business_currency_mismatch
Invalid payload, a payment currency different from the business currency, or unavailable payment configuration.
422
wallet_limit_exceeded
The payer's wallet limit for their KYC level would be exceeded (Bank of Zambia limits).
429
rate_limit_exceeded
Configured request limit was exceeded.
503
sandbox_unavailable
Requested sandbox service is unavailable.
Error response format
{
"response": {
"status": {
"code": 422,
"message": "The request payload is invalid."
},
"records": {
"code": "validation_error",
"errors": {
"currency": ["The selected currency is invalid."]
}
}
}
}
Admin-managed policies. The default rate limit is 60 requests per minute. New links use the current 15, 30, 45, or 60 minute expiry preference, while existing links retain their stored expiry.