Merchant API reference

GatePay Merchant REST API

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

HeaderValueRequiredDescription
Acceptapplication/jsonYesRequired on POST and GET.
Content-Typeapplication/jsonPOSTRequired on requests with a body.
X-Client-Idci_test_...Token requestMerchant application client ID. Only needed when requesting a token.
AuthorizationBearer eyJ...API callsAccess token from /v1/auth/token. Expires after 15 minutes; it is tied to your app and mode.
X-GatePay-Timestamp1763290000YesUnix time in seconds. Must be within 5 minutes of server time.
X-GatePay-Nonce9f2c7a1e...YesA random value, 16 to 64 characters (letters, digits, - and _). Each nonce can be used only once.
X-GatePay-Signature64 hex charactersYesLower-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"

200 OK

{
  "response": {
    "status": { "code": 200, "message": "Access token issued." },
    "records": {
      "code": "token_issued",
      "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
      "token_type": "Bearer",
      "expires_in": 900,
      "mode": "sandbox"
    }
  }
}
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

ModeClient IDClient secretData and processing
sandboxci_test_...cs_test_...Merchant application and payment records use the sandbox database. Provider outcomes are simulated and no wallet balance moves.
liveci_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 ruleRequired configurationCheckout behavior
Wallet, Mtn, Airtel, CybersourceCheckout 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 prerequisitesMTN 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 prerequisitesAirtel 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 walletNo 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 required Sandbox and live Active 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

FieldTypeRequiredDescription
modestringYessandbox or live.
amountstringYesPositive decimal with up to eight decimal places.
currencystringYesActive three-letter fiat currency code matching the currency assigned to the authenticated business.
referencestringYesYour unique reference, up to 100 characters.
success_urlURLYesReturn URL for success and pending outcomes.
webhook_urlURLYesPublic endpoint for payment lifecycle events.
cancel_urlURLYesReturn URL for failed and cancelled outcomes.
descriptionstringOptionalPayment description, up to 1000 characters.
metadataobjectOptionalUp 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"
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;

/** Headers that sign one request (path and query exactly as sent). */
function gatepaySignature(string $method, string $pathAndQuery, string $body): array
{
    $timestamp = (string) time();
    $nonce = Str::random(32);
    $canonical = implode("\n", [$method, $pathAndQuery, $timestamp, $nonce, hash('sha256', $body)]);

    return [
        'X-GatePay-Timestamp' => $timestamp,
        'X-GatePay-Nonce' => $nonce,
        'X-GatePay-Signature' => hash_hmac('sha256', $canonical, config('services.gatepay.client_secret')),
    ];
}

/** A cached access token (valid 15 minutes). */
function gatepayToken(string $mode): string
{
    return Cache::remember("gatepay-token-$mode", 840, function () use ($mode) {
        $body = json_encode(['mode' => $mode]);

        return Http::acceptJson()
            ->withHeaders(['X-Client-Id' => config('services.gatepay.client_id')] + gatepaySignature('POST', '/api/v1/auth/token', $body))
            ->withBody($body, 'application/json')
            ->post('https://uatstage.gatepay.co.zm/api/v1/auth/token')
            ->throw()
            ->json('response.records.access_token');
    });
}

$body = json_encode([
    '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'],
]);

$response = Http::acceptJson()
    ->withToken(gatepayToken('sandbox'))
    ->withHeaders(gatepaySignature('POST', '/api/v1/payments', $body))
    ->withBody($body, 'application/json')
    ->post('https://uatstage.gatepay.co.zm/api/v1/payments');

201 Created

{
  "response": {
    "status": {
      "code": 201,
      "message": "Payment link created successfully."
    },
    "records": {
      "code": "payment_link_created",
      "transaction_id": "01KXQBBN9Y1CN3T3NSQHZ15W4V",
      "reference": "ORDER-1001",
      "mode": "sandbox",
      "status": "PENDING",
      "amount": "100.00000000",
      "currency": "ZMW",
      "payment_methods": ["Mtn", "Airtel", "Cybersource"],
      "payment_url": "https://uatstage.gatepay.co.zm/pay/8fK2mQ7xN4vR9cT6pL3zWa",
      "expires_at": "2026-07-21T10:30:00+00:00",
      "metadata": {"order_id": "1001"}
    }
  }
}

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.

https://uatstage.gatepay.co.zm/api/v1/payments/status?mode=sandbox&reference=ORDER-1001
Credentials required Merchant-scoped lookup No Content-Type required

Query parameters

ParameterRequiredDescription
modeYesMust match the credential prefixes and transaction environment.
referenceYesExact, case-sensitive merchant reference.
PATH_Q='/api/v1/payments/status?mode=sandbox&reference=ORDER-1001'
sign GET "$PATH_Q" ''
curl 'https://uatstage.gatepay.co.zm/api/v1/payments/status?mode=sandbox&reference=ORDER-1001' \
  --header 'Accept: application/json' \
  --header "Authorization: Bearer $ACCESS_TOKEN" \
  --header "X-GatePay-Timestamp: $TS" \
  --header "X-GatePay-Nonce: $NONCE" \
  --header "X-GatePay-Signature: $SIGNATURE"
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');

200 OK

{
  "response": {
    "status": {
      "code": 200,
      "message": "Transaction status retrieved successfully."
    },
    "records": {
      "code": "transaction_status_retrieved",
      "trx_reference": "01KXQBBN9Y1CN3T3NSQHZ15W4V",
      "reference": "ORDER-1001",
      "status": "SUCCESS",
      "mode": "sandbox",
      "amount": "100.00000000",
      "currency": "ZMW",
      "payment_method": "Cybersource"
    }
  }
}

Pay without redirect: integration guide

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 experienceCustomer 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.
ChannelsWallet, MTN MoMo, Airtel Money, Visa / MastercardMTN MoMo, Airtel Money
EndpointPOST /v1/paymentsPOST /v1/collections
Best forOnline shops, invoices, card paymentsMobile and USSD apps, ticketing, utilities, schools, server-to-server billing

Integration steps

  1. Get your sandbox Client ID and Client Secret from the merchant portal: Merchant → Business → Secret Codes (the gear icon).
  2. Optional but recommended: add your server's public IP addresses under Merchant → Business → Allowed sources (the shield icon).
  3. Collect the customer's phone number and amount in your own screen, then call POST /v1/collections with mode "sandbox" and a unique reference.
  4. 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.
  5. Receive the result on your callback_url (verify the signature), or check GET /v1/collections/{reference}. Only fulfil the order on SUCCESS.
  6. Test every outcome with the sandbox test numbers, then switch to live credentials and mode "live".

What happens after the prompt is sent

TimeWhat GatePay does
0 sSends the PIN prompt to the customer's phone and replies 202 PENDING (or waits, if wait_for_result is true).
5 – 30 sChecks MTN or Airtel every 5 seconds, up to 6 times.
SuccessRecords the payment, credits your wallet once and posts payment.status.success to your callback_url.
Failed, rejected or expiredUpdates the status and posts the matching event. Your wallet is not changed.
Still pending after 30 sScheduled 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 signature MTN MoMo, Airtel Money Idempotent by reference

How it works

  1. Your system sends provider, phone, amount, currency, reference and callback_url.
  2. GatePay replies 202 PENDING and the customer receives the PIN prompt on their phone.
  3. The customer approves with their PIN.
  4. 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

FieldRequiredDescription
modeYessandbox or live, matching your credentials.
providerYesmtn or airtel.
phoneYesCustomer's mobile money number: +260961234567, 260961234567 or 0961234567.
amountYesDecimal string, for example "250.00".
currencyYesISO code, for example ZMW.
referenceYesYour unique order or ticket reference (max 100). Sending the same reference again returns the existing payment and does not prompt the customer twice.
callback_urlYesWhere GatePay posts the result. Must be HTTPS in live mode.
descriptionNoShort text shown on the customer's prompt where the provider supports it (max 160).
metadataNoUp to 20 key-value pairs returned to you unchanged.
wait_for_resultNotrue 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_emailNoCustomer's email. Used only to also send a repeat-payment confirmation code (see below).
repeat_confirmation_tokenOnly after a 409The token from a 409 repeat_payment_confirmation_required response.
repeat_confirmation_codeOnly after a 409The 6-digit code the customer received by SMS (and email if given).

Headers

HeaderRequiredDescription
Authorization, X-GatePay-Timestamp, X-GatePay-Nonce, X-GatePay-SignatureYesAccess token and request signature for the chosen mode. See Authentication.
X-Customer-IPNoThe end customer's IP address. Used by anti-money-laundering monitoring; send it when you have it.
X-Device-IdNoA 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.

ProviderTest numberOutcome
MTN+46733123450FAILED
MTN+46733123451PENDING
MTN+46733123452EXPIRED
MTN+46733123453SUCCESS
Airtel260970000050FAILED
Airtel260970000051PENDING
Airtel260970000052EXPIRED
Airtel260970000053SUCCESS

Errors

HTTPCodeMeaning
401invalid_credentialsClient ID or secret is wrong.
403credential_mode_mismatchSandbox credentials were used with mode "live", or the other way round.
403source_not_allowedThe call came from an IP address that is not on your Allowed sources list.
403merchant_not_activeYour business is not approved and active yet.
403merchant_deletedYour business has been deleted and can no longer accept payments.
422validation_errorA field is missing or invalid; see errors.
422provider_unavailableThe provider is not enabled for this currency on your account.
409reference_conflictThe reference was already used with different details.
409repeat_payment_confirmation_requiredThe 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.
422repeat_confirmation_invalidThe confirmation code is wrong, expired (5 minutes) or already used. After 5 wrong codes, start again.
502provider_request_failedMTN 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.

POST https://yourapp.co.zm/webhooks/gatepay
X-Event: payment.status.success
X-Delivery-Id: evt_01JD...
X-Timestamp: 1763276187
Content-Type: application/json

{
  "id": "evt_01JD...",
  "event": "payment.status.success",
  "created_at": "2026-11-16T06:36:29Z",
  "data": {
    "trx_reference": "01M7HH4GVN1MRMKZKGYMJSXNV9",
    "reference": "TRIP-10482",
    "status": "SUCCESS",
    "mode": "sandbox",
    "amount": "250.00",
    "currency": "ZMW",
    "payment_method": "Mtn",
    "metadata": { "channel": "direct_api", "provider": "mtn", "payer_phone": "+260961***567" }
  },
  "signature": "hex_hmac_sha256"
}
GET

Collection status

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.

https://uatstage.gatepay.co.zm/api/v1/collections/TRIP-10482?mode=sandbox

200 OK

{
  "response": {
    "status": { "code": 200, "message": "Transaction status retrieved successfully." },
    "records": {
      "code": "transaction_status_retrieved",
      "trx_reference": "01M7HH4GVN1MRMKZKGYMJSXNV9",
      "reference": "TRIP-10482",
      "status": "SUCCESS",
      "mode": "sandbox",
      "provider": "mtn",
      "channel": "direct_api",
      "payer_phone": "+260961***567",
      "amount": "250.00000000",
      "currency": "ZMW",
      "description": "Bus fare Lusaka to Kitwe",
      "created_at": "2026-11-16T06:36:27+00:00",
      "updated_at": "2026-11-16T06:36:27+00:00",
      "message": "The payment was completed."
    }
  }
}

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.

https://uatstage.gatepay.co.zm/api/v1/transactions?mode=live&status=SUCCESS&from=2026-11-01&to=2026-11-30&per_page=50
ParameterRequiredDescription
modeYessandbox or live.
statusNoSUCCESS, PENDING, FAILED, CANCELLED, EXPIRED, REFUNDED
providerNomtn or airtel
referenceNoMatches part of your reference.
from, toNoDates as YYYY-MM-DD.
page, per_pageNoPagination; per_page up to 100 (default 20).

200 OK

{
  "response": {
    "status": { "code": 200, "message": "Transactions retrieved successfully." },
    "records": {
      "code": "transactions_retrieved",
      "transactions": [
        {
          "trx_reference": "01M7HH4GVN1MRMKZKGYMJSXNV9",
          "reference": "TRIP-10482",
          "status": "SUCCESS",
          "mode": "sandbox",
          "provider": "mtn",
          "channel": "direct_api",
          "payer_phone": "+260961***567",
          "amount": "250.00000000",
          "currency": "ZMW",
          "description": "Bus fare Lusaka to Kitwe",
          "created_at": "2026-11-16T06:36:27+00:00",
          "updated_at": "2026-11-16T06:36:27+00:00"
        }
      ],
      "pagination": { "page": 1, "per_page": 20, "total": 7, "last_page": 1 }
    }
  }
}

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

EventPublic statusBody signature
payment.status.createdPENDINGYes
payment.status.successSUCCESSYes
payment.status.failedFAILEDYes
payment.status.cancelledCANCELLEDYes
payment.status.expiredEXPIREDYes

Delivery headers

HeaderDescription
X-EventLifecycle event name.
X-Delivery-IdUnique ID used to deduplicate at-least-once deliveries.
X-TimestampUnix timestamp used to verify the event signature.
Content-Typeapplication/json

Successful payment event

{
  "id": "evt_01KX...",
  "event": "payment.status.success",
  "created_at": "2026-07-21T10:00:00+00:00",
  "data": {
    "trx_reference": "01KXQBBN9Y1CN3T3NSQHZ15W4V",
    "reference": "ORDER-1001",
    "status": "SUCCESS",
    "mode": "live",
    "amount": "100.00000000",
    "currency": "ZMW",
    "payment_method": "Cybersource",
    "metadata": {"order_id": "1001"}
  },
  "signature": "hex_hmac_sha256"
}
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.

Laravel signature verification

$timestamp = request()->header('X-Timestamp');
abort_unless(is_string($timestamp) && ctype_digit($timestamp), 401);

$now = time();
abort_if((int) $timestamp < $now - 300 || (int) $timestamp > $now + 300, 401);

$rawBody = request()->getContent();
try {
    $event = json_decode($rawBody, true, 512, JSON_THROW_ON_ERROR);
    abort_unless(is_array($event), 401);

    $receivedSignature = $event['signature'] ?? null;
    abort_unless(is_string($receivedSignature), 401);

    unset($event['signature']);

    $unsignedBody = json_encode(
        $event,
        JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR
    );
} catch (\JsonException) {
    abort(401);
}

$expectedSignature = hash_hmac(
    'sha256',
    $timestamp.'.'.$unsignedBody,
    config('services.gatepay.client_secret')
);

abort_unless(hash_equals($expectedSignature, $receivedSignature), 401);

return response()->noContent();

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-1000000001 SUCCESS
WLT-1000000002 FAILED
WLT-1000000003 PENDING
WLT-1000000004 CANCELLED
WLT-1000000005 INSUFFICIENT BALANCE

MTN

46733123450 FAILED
46733123451 PENDING
46733123452 EXPIRED
46733123453 SUCCESS

Airtel

260970000050 FAILED
260970000051 PENDING
260970000052 EXPIRED
260970000053 SUCCESS

Cybersource

success SUCCESS
failed FAILED
pending PENDING
cancelled CANCELLED

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.

HTTPMachine code examplesMeaning
401invalid_credentialsUnknown client ID, or the app is not active for this mode.
401signature_required, signed_request_requiredSignature headers missing, or the secret was sent in a header instead of signing.
401invalid_signatureThe signature does not match the method, path, timestamp, nonce or body.
401signature_expired, invalid_nonce, replayed_requestTimestamp more than 5 minutes off, badly formed nonce, or a nonce that was already used.
401invalid_token, token_expiredAccess token altered, issued for another app or mode, or older than 15 minutes. Request a new one.
403https_requiredLive requests must use HTTPS.
403business_verification_requiredLive mode needs an approved business verification (KYB: PACRA, TPIN, directors).
403credential_mode_mismatchCredential mode mismatch or unavailable merchant access.
404transaction_not_foundNo transaction for this app and exact reference.
406not_acceptableAccept header does not allow JSON.
409reference_conflictReference exists with a changed payload.
415unsupported_media_typePOST request body is not JSON.
422validation_error, business_currency_mismatchInvalid payload, a payment currency different from the business currency, or unavailable payment configuration.
422wallet_limit_exceededThe payer's wallet limit for their KYC level would be exceeded (Bank of Zambia limits).
429rate_limit_exceededConfigured request limit was exceeded.
503sandbox_unavailableRequested 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.