InfinexpayInfinexpayDeveloper API Try the sandbox

One API to accept mobile money payments across Africa.

Collect STK Push and mobile money payments in 15 African countries, settle into one wallet, pay out to M-Pesa, and accept USDT. One JSON format, ready-made code and ZIP kits for 9 languages and frameworks, including a drag-and-drop Laravel kit.

KenyaNigeriaGhanaZambiaDR CongoSierra LeoneUgandaTanzaniaRwandaCameroonGabonCongo-BrazzavilleSenegalBeninCôte d'Ivoire

Introduction

The Infinexpay API lets you collect mobile money payments, run crypto checkouts and send payouts through one consistent JSON interface.

FeatureCoverage
Collections (STK Push / mobile money)15 countries. See Countries & currencies
Crypto deposits (USDT, TRC20)Any customer, any country
Wallet top-upKenya (M-Pesa)
PayoutsKenya (M-Pesa) today

Base URL

https://www.infinexpay.co.ke.gazelleusacompany.com/api/v2/

Response format

JSON
{
  "success": true | false,
  "message": "Descriptive message"
  // additional fields depend on the endpoint
}

Fees & balances

Your account holds two balances. The service wallet is money you can pay out. The service balance pays the processing fee on every collection, top-up and payout, so a payout recipient always receives exactly the amount you request.

OperationFeeCharged to
STK PushSet per country and provider. The exact fee is returned in fee_deductedService balance, in KES (converted for non-KES countries)
Wallet top-upSet per provider for Kenya. Returned in fee_deductedService balance, in KES. The full amount is credited to your wallet
PayoutSet per provider for Kenya. Returned in fee_deductedService balance. Wallet is debited the payout amount; recipient gets that full amount
Keep your service balance topped up

Requests are rejected with HTTP 402 if your service balance cannot cover the fee. STK Push returns the generic message Transaction failed. Please contact support.; top-up and payout state the shortfall.

Authentication

Every request is authenticated with an API key and secret sent as headers. Generate and rotate them from your merchant dashboard.

Required headers
X-API-Key: your_api_key
X-API-Secret: your_api_secret
Content-Type: application/json
Keep secrets server-side

Route all API calls through your backend. If a key is ever exposed, rotate it immediately.

Integration kits

Pick your language or framework, copy the files, or download a ready-made ZIP with your site URL already filled in. Edit the credentials (or .env for Laravel) and you are done.

  1. Create an account on the dashboard and complete KYC.
  2. Generate an API key and secret, and set up a payment account (note its ID).
  3. Choose your language below, download or copy, and add your credentials.
PHP kit · 4 files

Needs PHP 7+ with cURL. Edit config.php, then open pay.php via your checkout form.

⇩ Download PHP ZIP

config.php
PHP · config.php
<?php
return [
    'base_url' => 'https://www.infinexpay.co.ke.gazelleusacompany.com',
    'api_key' => 'your_api_key',
    'api_secret' => 'your_api_secret',
    'payment_account_id' => 14,
    'webhook_secret' => 'your_webhook_signing_secret',
];
Infinexpay.php
PHP · Infinexpay.php
<?php
class Infinexpay {
    private $c;
    private static $zero = ['UG','TZ','RW','CM','GA','CG','SN','BJ','CI'];
    function __construct($c = null) { $this->c = $c ?: require __DIR__ . '/config.php'; }

    private function req($m, $path, $body = null, $q = []) {
        $url = rtrim($this->c['base_url'], '/') . '/api/v2' . $path . ($q ? '?' . http_build_query($q) : '');
        $ch = curl_init($url);
        curl_setopt_array($ch, [CURLOPT_CUSTOMREQUEST => $m, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 60,
            CURLOPT_HTTPHEADER => ['X-API-Key: ' . $this->c['api_key'], 'X-API-Secret: ' . $this->c['api_secret'], 'Content-Type: application/json']]);
        if ($body !== null) curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
        $raw = curl_exec($ch); $err = curl_error($ch); curl_close($ch);
        if ($raw === false) return ['success' => false, 'status' => 'unknown', 'message' => "No response ($err). Check transactions before retrying."];
        return json_decode($raw, true) ?: ['success' => false, 'message' => 'Unexpected response'];
    }
    function collect($phone, $amount, $country, $ref = null, $desc = 'Payment') {
        $country = strtoupper($country);
        if (in_array($country, self::$zero, true)) $amount = (int) round($amount);
        return $this->req('POST', '/stkpush.php', ['payment_account_id' => (int) $this->c['payment_account_id'],
            'phone' => preg_replace('/\D/', '', $phone), 'amount' => $amount, 'reference' => $ref, 'description' => $desc, 'country' => $country]);
    }
    function status($id) { return $this->req('POST', '/status.php', ['transaction_id' => $id]); }
    function payout($phone, $amount, $name = null, $remarks = 'Payout') {
        return $this->req('POST', '/payout.php', ['phone' => $phone, 'amount' => (int) $amount, 'remarks' => $remarks, 'recipient_name' => $name]);
    }
    function payoutStatus($id) { return $this->req('GET', '/payout.php', null, ['transaction_id' => $id]); }
    function cryptoDeposit($usd, $orderId) { return $this->req('POST', '/crypto_deposit.php', ['amount' => $usd, 'order_id' => $orderId]); }
}
pay.php
PHP · pay.php
<?php
header('Content-Type: application/json');
require __DIR__ . '/Infinexpay.php';
$in = json_decode(file_get_contents('php://input'), true) ?: [];
$r = (new Infinexpay())->collect($in['phone'] ?? '', $in['amount'] ?? 0, $in['country'] ?? 'KE', 'ORD-' . uniqid());
echo json_encode($r); // if $r['action']==='redirect' send the customer to $r['redirect_url']
webhook.php
PHP · webhook.php
<?php
$cfg = require __DIR__ . '/config.php';
$body = file_get_contents('php://input');
$calc = 'sha256=' . hash_hmac('sha256', $body, $cfg['webhook_secret']);
if (!hash_equals($calc, $_SERVER['HTTP_X_WEBHOOK_SIGNATURE'] ?? '')) { http_response_code(401); exit; }
$data = json_decode($body, true) ?: [];
if (($data['status'] ?? '') === 'success') { /* mark $data['reference'] as paid; dedupe on X-Webhook-Id */ }
http_response_code(200); echo '{"message":"Acknowledged"}';
Laravel kit · 9 files

Laravel 10, 11 or 12 (PHP 8.1+), no packages. Drag each file to the path shown above its code. Register the provider (bootstrap/providers.php on 11/12, config/app.php on 10), fill .env, run php artisan config:clear, then open /infinexpay/checkout.

⇩ Download Laravel ZIP

INSTALL.md
Laravel · INSTALL.md
# Infinexpay for Laravel (drag and drop)

Laravel 10, 11 and 12. PHP 8.1+. No composer packages.

## Install (3 steps)

1. Drag the files into your project at the same paths (merge folders when asked).
2. Register the provider:
   - Laravel 11/12: add `App\Providers\InfinexpayServiceProvider::class,` to `bootstrap/providers.php`
   - Laravel 10: add it to `providers` in `config/app.php`
3. Copy `.env.example` lines into `.env`, then run `php artisan config:clear`.

Open `/infinexpay/checkout` to test a payment.

## Use it in code

```php
use App\Infinexpay\Infinexpay;

$res = app(Infinexpay::class)->collect('254712345678', 100, 'KE', 'ORDER-1');
// $res['action'] === 'redirect' ? redirect($res['redirect_url']) : customer approves on phone
app(Infinexpay::class)->status($res['transaction_id']);
```

Methods: collect, status, transactions, payout, payoutStatus, topup, cryptoDeposit.
UGX, TZS, RWF, XAF and XOF amounts are rounded to whole numbers automatically.

## Webhooks

Set your webhook URL in Developer settings to `https://your-site.com/infinexpay/webhook`.
The signature is verified on the raw body and repeats are ignored. A verified event fires `App\Infinexpay\WebhookReceived`:

```php
Event::listen(\App\Infinexpay\WebhookReceived::class, function ($e) {
    if (($e->payload['status'] ?? '') === 'success') {
        // mark $e->payload['reference'] as paid
    }
});
```

## Rules that matter

- Keep the API secret in `.env`, server-side only.
- Never retry a payout after a timeout or a null transaction_id. Check payoutStatus() or transactions first.
- The payout route is off by default. To enable it set `payout_enabled` to true in config/infinexpay.php AND add 'auth' to `routes.middleware`.
- Keep your service balance funded: every fee comes from it (HTTP 402 otherwise).
.env.example
Laravel · .env.example
INFINEXPAY_BASE_URL=https://www.infinexpay.co.ke.gazelleusacompany.com
INFINEXPAY_API_KEY=your_api_key
INFINEXPAY_API_SECRET=your_api_secret
INFINEXPAY_ACCOUNT_ID=14
INFINEXPAY_WEBHOOK_SECRET=your_webhook_signing_secret
INFINEXPAY_COUNTRY=KE
config/infinexpay.php
Laravel · config/infinexpay.php
<?php

return [
    'base_url'           => env('INFINEXPAY_BASE_URL', 'https://www.infinexpay.co.ke.gazelleusacompany.com'),
    'api_key'            => env('INFINEXPAY_API_KEY'),
    'api_secret'         => env('INFINEXPAY_API_SECRET'),
    'payment_account_id' => (int) env('INFINEXPAY_ACCOUNT_ID'),
    'webhook_secret'     => env('INFINEXPAY_WEBHOOK_SECRET'),
    'default_country'    => env('INFINEXPAY_COUNTRY', 'KE'),
    'timeout'            => 60,

    // Built-in routes (set 'enabled' to false and use the Infinexpay class in your own routes)
    'routes' => [
        'enabled'        => true,
        'prefix'         => 'infinexpay',
        // Add 'auth' here to protect pay/payout endpoints. Never expose payouts publicly.
        'middleware'     => ['web'],
        'payout_enabled' => false,
    ],
];
app/Infinexpay/Infinexpay.php
Laravel · app/Infinexpay/Infinexpay.php
<?php

namespace App\Infinexpay;

use Illuminate\Http\Client\ConnectionException;
use Illuminate\Support\Facades\Http;

class Infinexpay
{
    /** Countries whose currency has no decimals: amounts must be whole numbers. */
    const ZERO_DECIMAL = ['UG', 'TZ', 'RW', 'CM', 'GA', 'CG', 'SN', 'BJ', 'CI'];

    protected function call(string $method, string $path, array $body = [], array $query = []): array
    {
        $c = config('infinexpay');
        try {
            $req = Http::withHeaders(['X-API-Key' => $c['api_key'], 'X-API-Secret' => $c['api_secret']])
                ->acceptJson()->timeout($c['timeout']);
            $url = rtrim($c['base_url'], '/') . '/api/v2' . $path;
            $res = $method === 'GET' ? $req->get($url, $query) : $req->asJson()->post($url, $body);
        } catch (ConnectionException $e) {
            // Never retry a payout after this. Check status/transactions first.
            return ['success' => false, 'status' => 'unknown',
                    'message' => 'No response from gateway. Check status before retrying.'];
        }
        return $res->json() ?? ['success' => false, 'message' => 'Unexpected response (HTTP ' . $res->status() . ')'];
    }

    /** Collect a payment (STK Push / mobile money). Amount in the customer's local currency. */
    public function collect(string $phone, float $amount, ?string $country = null, ?string $reference = null, string $description = 'Payment'): array
    {
        $country = strtoupper($country ?: config('infinexpay.default_country'));
        if (in_array($country, self::ZERO_DECIMAL, true)) {
            $amount = (int) round($amount);
        }
        return $this->call('POST', '/stkpush.php', [
            'payment_account_id' => config('infinexpay.payment_account_id'),
            'phone'       => preg_replace('/\D/', '', $phone),
            'amount'      => $amount,
            'country'     => $country,
            'reference'   => $reference,
            'description' => $description,
        ]);
    }

    public function status(string $transactionId): array
    {
        return $this->call('POST', '/status.php', ['transaction_id' => $transactionId]);
    }

    public function transactions(int $page = 1, int $limit = 100): array
    {
        return $this->call('GET', '/transactions.php', [], ['page' => $page, 'limit' => $limit]);
    }

    /** Kenya M-Pesa payout. Whole KES, 25 to 150,000. NEVER retry on timeout or null transaction_id. */
    public function payout(string $phone, int $amount, ?string $name = null, string $remarks = 'Payout'): array
    {
        return $this->call('POST', '/payout.php', [
            'phone' => $phone, 'amount' => $amount, 'remarks' => $remarks, 'recipient_name' => $name,
        ]);
    }

    public function payoutStatus(string $transactionId): array
    {
        return $this->call('GET', '/payout.php', [], ['transaction_id' => $transactionId]);
    }

    /** Wallet top-up via M-Pesa (Kenya only). */
    public function topup(string $phone, float $amount): array
    {
        return $this->call('POST', '/topup.php', ['phone' => $phone, 'amount' => $amount]);
    }

    /** USDT (TRC20) checkout. Amount in USD. Returns checkout_url. */
    public function cryptoDeposit(float $usd, string $orderId): array
    {
        return $this->call('POST', '/crypto_deposit.php', ['amount' => $usd, 'order_id' => $orderId]);
    }

    /** Verify a webhook signature over the RAW request body. */
    public function verifySignature(string $rawBody, ?string $signature): bool
    {
        $calc = 'sha256=' . hash_hmac('sha256', $rawBody, (string) config('infinexpay.webhook_secret'));
        return hash_equals($calc, (string) $signature);
    }
}
app/Infinexpay/WebhookReceived.php
Laravel · app/Infinexpay/WebhookReceived.php
<?php

namespace App\Infinexpay;

use Illuminate\Foundation\Events\Dispatchable;

/** Fired once per unique, verified webhook. Listen to this to mark orders paid. */
class WebhookReceived
{
    use Dispatchable;

    public function __construct(public array $payload, public ?string $event, public ?string $deliveryId) {}
}
app/Http/Controllers/InfinexpayController.php
Laravel · app/Http/Controllers/InfinexpayController.php
<?php

namespace App\Http\Controllers;

use App\Infinexpay\Infinexpay;
use App\Infinexpay\WebhookReceived;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;

class InfinexpayController extends Controller
{
    public function checkout()
    {
        return view('infinexpay.checkout');
    }

    public function pay(Request $r, Infinexpay $ix)
    {
        $d = $r->validate([
            'phone'     => 'required|string',
            'amount'    => 'required|numeric|gt:0',
            'country'   => 'nullable|string|size:2',
            'reference' => 'nullable|string|max:100',
        ]);
        $res = $ix->collect($d['phone'], (float) $d['amount'], $d['country'] ?? null,
            $d['reference'] ?? 'ORD-' . Str::upper(Str::random(8)));
        // If $res['action'] === 'redirect', send the customer to $res['redirect_url'].
        return response()->json($res);
    }

    public function status(Request $r, Infinexpay $ix)
    {
        $id = $r->validate(['transaction_id' => 'required|string'])['transaction_id'];
        return response()->json($ix->status($id));
    }

    public function payout(Request $r, Infinexpay $ix)
    {
        abort_unless(config('infinexpay.routes.payout_enabled'), 404);
        $d = $r->validate([
            'phone'   => 'required|string',
            'amount'  => 'required|integer|min:25|max:150000',
            'name'    => 'nullable|string|max:100',
            'remarks' => 'nullable|string|max:100',
        ]);
        return response()->json($ix->payout($d['phone'], (int) $d['amount'], $d['name'] ?? null, $d['remarks'] ?? 'Payout'));
    }

    public function webhook(Request $r, Infinexpay $ix)
    {
        if (!$ix->verifySignature($r->getContent(), $r->header('X-Webhook-Signature'))) {
            return response()->json(['message' => 'Invalid signature'], 401);
        }
        $id = $r->header('X-Webhook-Id');
        // Idempotency: the same event can be delivered more than once.
        if ($id && !Cache::add('infinexpay:wh:' . $id, 1, now()->addDays(2))) {
            return response()->json(['message' => 'Acknowledged']);
        }
        WebhookReceived::dispatch($r->json()->all(), $r->header('X-Webhook-Event'), $id);
        return response()->json(['message' => 'Acknowledged']);
    }
}
app/Providers/InfinexpayServiceProvider.php
Laravel · app/Providers/InfinexpayServiceProvider.php
<?php

namespace App\Providers;

use App\Http\Controllers\InfinexpayController;
use App\Infinexpay\Infinexpay;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\ServiceProvider;

class InfinexpayServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->mergeConfigFrom(base_path('config/infinexpay.php'), 'infinexpay');
        $this->app->singleton(Infinexpay::class);
    }

    public function boot(): void
    {
        $cfg = config('infinexpay.routes');
        if (!($cfg['enabled'] ?? true)) return;

        // Webhook: no session, no CSRF. Public by design, protected by its signature.
        Route::middleware('api')->prefix($cfg['prefix'])
            ->post('webhook', [InfinexpayController::class, 'webhook'])->name('infinexpay.webhook');

        Route::middleware($cfg['middleware'])->prefix($cfg['prefix'])
            ->group(base_path('routes/infinexpay_routes.php'));
    }
}
routes/infinexpay_routes.php
Laravel · routes/infinexpay_routes.php
<?php

use App\Http\Controllers\InfinexpayController as C;
use Illuminate\Support\Facades\Route;

Route::get('checkout', [C::class, 'checkout'])->name('infinexpay.checkout');
Route::post('pay', [C::class, 'pay'])->name('infinexpay.pay');
Route::post('status', [C::class, 'status'])->name('infinexpay.status');
Route::post('payout', [C::class, 'payout'])->name('infinexpay.payout');
resources/views/infinexpay/checkout.blade.php
Laravel · resources/views/infinexpay/checkout.blade.php
<!DOCTYPE html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="csrf-token" content="{{ csrf_token() }}"><title>Pay</title>
<style>body{font:15px system-ui;max-width:380px;margin:40px auto;padding:0 16px}input,select,button{width:100%;padding:10px;margin:6px 0;box-sizing:border-box}button{background:#1F5FD6;color:#fff;border:0;border-radius:8px}#msg{margin-top:12px;color:#55637A}</style>
</head><body>
<h3>Pay with mobile money</h3>
<select id="country">
@foreach(['KE'=>'Kenya','UG'=>'Uganda','TZ'=>'Tanzania','RW'=>'Rwanda','GH'=>'Ghana','NG'=>'Nigeria','ZM'=>'Zambia','CD'=>'DR Congo','SL'=>'Sierra Leone','CM'=>'Cameroon','GA'=>'Gabon','CG'=>'Congo-Brazzaville','SN'=>'Senegal','BJ'=>'Benin','CI'=>"Cote d'Ivoire"] as $c => $n)
<option value="{{ $c }}">{{ $n }}</option>
@endforeach
</select>
<input id="phone" placeholder="Phone, e.g. 254712345678">
<input id="amount" type="number" step="any" placeholder="Amount (local currency)">
<button id="go">Pay</button><div id="msg"></div>
<script>
const msg = t => document.getElementById('msg').textContent = t;
document.getElementById('go').onclick = async () => {
  msg('Sending...');
  const r = await fetch("{{ route('infinexpay.pay') }}", {method:'POST',
    headers:{'Content-Type':'application/json','Accept':'application/json','X-CSRF-TOKEN':document.querySelector('meta[name=csrf-token]').content},
    body:JSON.stringify({phone:phone.value,amount:amount.value,country:country.value})});
  const d = await r.json();
  if (!d.success) return msg(d.message || 'Failed');
  if (d.action === 'redirect' && d.redirect_url) return location.href = d.redirect_url;
  msg('Check your phone and enter your PIN.');
};
</script></body></html>
Node.js kit · 2 files

Node 18+, no packages for the client. Webhook sample needs: npm i express

⇩ Download Node.js ZIP

infinexpay.js
Node.js · infinexpay.js
const crypto = require("crypto");
const CFG = { base: "https://www.infinexpay.co.ke.gazelleusacompany.com/api/v2", key: "your_api_key", secret: "your_api_secret", account: 14, whSecret: "your_webhook_signing_secret" };
const ZERO = ["UG","TZ","RW","CM","GA","CG","SN","BJ","CI"];
const H = { "X-API-Key": CFG.key, "X-API-Secret": CFG.secret, "Content-Type": "application/json" };

async function call(method, path, body) {
  const res = await fetch(CFG.base + path, { method, headers: H, body: body ? JSON.stringify(body) : undefined });
  return res.json();
}
exports.collect = (phone, amount, country, reference, description = "Payment") =>
  call("POST", "/stkpush.php", { payment_account_id: CFG.account, phone: String(phone).replace(/\D/g, ""),
    amount: ZERO.includes(country) ? Math.round(amount) : amount, country, reference, description });
exports.status = (id) => call("POST", "/status.php", { transaction_id: id });
exports.payout = (phone, amount, name, remarks = "Payout") =>
  call("POST", "/payout.php", { phone, amount: Math.trunc(amount), remarks, recipient_name: name }); // never retry on timeout
exports.payoutStatus = (id) => call("GET", `/payout.php?transaction_id=${encodeURIComponent(id)}`);
exports.verify = (rawBody, sig) => {
  const calc = "sha256=" + crypto.createHmac("sha256", CFG.whSecret).update(rawBody).digest("hex");
  const a = Buffer.from(calc), b = Buffer.from(sig || "");
  return a.length === b.length && crypto.timingSafeEqual(a, b);
};
webhook.js
Node.js · webhook.js
const express = require("express");
const { verify } = require("./infinexpay");
const app = express();
app.post("/infinexpay/webhook", express.raw({ type: "*/*" }), (req, res) => {
  if (!verify(req.body, req.get("X-Webhook-Signature"))) return res.sendStatus(401);
  const data = JSON.parse(req.body.toString());
  if (data.status === "success") { /* mark data.reference as paid; dedupe on X-Webhook-Id */ }
  res.json({ message: "Acknowledged" });
});
app.listen(3000);
Python kit · 2 files

pip install requests flask

⇩ Download Python ZIP

infinexpay.py
Python · infinexpay.py
import hmac, hashlib, requests

BASE = "https://www.infinexpay.co.ke.gazelleusacompany.com/api/v2"
KEY, SECRET, ACCOUNT, WH_SECRET = "your_api_key", "your_api_secret", 14, "your_webhook_signing_secret"
HEADERS = {"X-API-Key": KEY, "X-API-Secret": SECRET, "Content-Type": "application/json"}
ZERO = {"UG", "TZ", "RW", "CM", "GA", "CG", "SN", "BJ", "CI"}

def _call(method, path, body=None, params=None):
    return requests.request(method, BASE + path, json=body, params=params, headers=HEADERS, timeout=60).json()

def collect(phone, amount, country, reference=None, description="Payment"):
    if country in ZERO:
        amount = int(round(amount))
    return _call("POST", "/stkpush.php", {"payment_account_id": ACCOUNT, "phone": "".join(c for c in phone if c.isdigit()),
                 "amount": amount, "country": country, "reference": reference, "description": description})

def status(tx_id):
    return _call("POST", "/status.php", {"transaction_id": tx_id})

def payout(phone, amount, name=None, remarks="Payout"):  # never retry on timeout
    return _call("POST", "/payout.php", {"phone": phone, "amount": int(amount), "remarks": remarks, "recipient_name": name})

def payout_status(tx_id):
    return _call("GET", "/payout.php", params={"transaction_id": tx_id})

def verify(raw_body: bytes, sig: str) -> bool:
    calc = "sha256=" + hmac.new(WH_SECRET.encode(), raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(calc, sig or "")
webhook.py
Python · webhook.py
from flask import Flask, request, jsonify
import infinexpay

app = Flask(__name__)

@app.post("/infinexpay/webhook")
def webhook():
    if not infinexpay.verify(request.get_data(), request.headers.get("X-Webhook-Signature")):
        return "", 401
    data = request.get_json()
    if data.get("status") == "success":
        pass  # mark data["reference"] as paid; dedupe on X-Webhook-Id
    return jsonify(message="Acknowledged"), 200
Ruby kit · 2 files

No gems for the client. Webhook sample needs: gem install sinatra

⇩ Download Ruby ZIP

infinexpay.rb
Ruby · infinexpay.rb
require "net/http"
require "json"
require "uri"
require "openssl"

module Infinexpay
  BASE = "https://www.infinexpay.co.ke.gazelleusacompany.com/api/v2"
  HEADERS = { "X-API-Key" => "your_api_key", "X-API-Secret" => "your_api_secret", "Content-Type" => "application/json" }
  ACCOUNT = 14
  WH_SECRET = "your_webhook_signing_secret"
  ZERO = %w[UG TZ RW CM GA CG SN BJ CI]

  def self.call(method, path, body = nil)
    uri = URI(BASE + path)
    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = uri.scheme == "https"
    http.read_timeout = 60
    res = method == :get ? http.get(uri.request_uri, HEADERS) : http.post(uri.request_uri, body.to_json, HEADERS)
    JSON.parse(res.body)
  end

  def self.collect(phone, amount, country, reference = nil, description = "Payment")
    amount = amount.round if ZERO.include?(country)
    call(:post, "/stkpush.php", { payment_account_id: ACCOUNT, phone: phone.gsub(/\D/, ""), amount: amount,
                                  country: country, reference: reference, description: description })
  end
  def self.status(id) = call(:post, "/status.php", { transaction_id: id })
  def self.payout(phone, amount, name = nil, remarks = "Payout") # never retry on timeout
    call(:post, "/payout.php", { phone: phone, amount: amount.to_i, remarks: remarks, recipient_name: name })
  end
  def self.payout_status(id) = call(:get, "/payout.php?transaction_id=#{URI.encode_www_form_component(id)}")
  def self.verify(raw, sig)
    Rack::Utils.secure_compare("sha256=" + OpenSSL::HMAC.hexdigest("SHA256", WH_SECRET, raw), sig.to_s)
  end
end
webhook.rb
Ruby · webhook.rb
require "sinatra"
require_relative "infinexpay"

post "/infinexpay/webhook" do
  body = request.body.read
  halt 401 unless Infinexpay.verify(body, request.env["HTTP_X_WEBHOOK_SIGNATURE"])
  data = JSON.parse(body)
  # if data["status"] == "success": mark data["reference"] as paid; dedupe on X-Webhook-Id
  content_type :json
  { message: "Acknowledged" }.to_json
end
Go kit · 2 files

Standard library only. Put both files in one package, then: go run .

⇩ Download Go ZIP

infinexpay.go
Go · infinexpay.go
package main

import (
	"bytes"
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"net/http"
	"net/url"
	"time"
)

const (
	base     = "https://www.infinexpay.co.ke.gazelleusacompany.com/api/v2"
	apiKey   = "your_api_key"
	apiSec   = "your_api_secret"
	account  = 14
	whSecret = "your_webhook_signing_secret"
)

var client = &http.Client{Timeout: 60 * time.Second}

type M = map[string]interface{}

func call(method, path string, body M) (M, error) {
	var buf bytes.Buffer
	if body != nil {
		json.NewEncoder(&buf).Encode(body)
	}
	req, _ := http.NewRequest(method, base+path, &buf)
	req.Header.Set("X-API-Key", apiKey)
	req.Header.Set("X-API-Secret", apiSec)
	req.Header.Set("Content-Type", "application/json")
	res, err := client.Do(req)
	if err != nil {
		return nil, err // do NOT retry payouts blindly
	}
	defer res.Body.Close()
	var out M
	json.NewDecoder(res.Body).Decode(&out)
	return out, nil
}

func Collect(phone string, amount float64, country, ref string) (M, error) {
	return call("POST", "/stkpush.php", M{"payment_account_id": account, "phone": phone, "amount": amount, "country": country, "reference": ref})
}
func Status(id string) (M, error) { return call("POST", "/status.php", M{"transaction_id": id}) }
func Payout(phone string, amount int, name string) (M, error) {
	return call("POST", "/payout.php", M{"phone": phone, "amount": amount, "recipient_name": name, "remarks": "Payout"})
}
func PayoutStatus(id string) (M, error) { return call("GET", "/payout.php?transaction_id="+url.QueryEscape(id), nil) }

func Verify(raw []byte, sig string) bool {
	m := hmac.New(sha256.New, []byte(whSecret))
	m.Write(raw)
	return hmac.Equal([]byte("sha256="+hex.EncodeToString(m.Sum(nil))), []byte(sig))
}
main.go
Go · main.go
package main

import (
	"io"
	"net/http"
)

func main() {
	http.HandleFunc("/infinexpay/webhook", func(w http.ResponseWriter, r *http.Request) {
		body, _ := io.ReadAll(r.Body)
		if !Verify(body, r.Header.Get("X-Webhook-Signature")) {
			w.WriteHeader(401)
			return
		}
		// parse body; if status == "success" mark reference as paid; dedupe on X-Webhook-Id
		w.Write([]byte(`{"message":"Acknowledged"}`))
	})
	http.ListenAndServe(":3000", nil)
}
Java kit · 1 file

Java 11+, no dependencies. Parse the JSON strings with Jackson, Gson or org.json.

⇩ Download Java ZIP

Infinexpay.java
Java · Infinexpay.java
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.*;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class Infinexpay {
    static final String BASE = "https://www.infinexpay.co.ke.gazelleusacompany.com/api/v2";
    static final String KEY = "your_api_key", SECRET = "your_api_secret", WH_SECRET = "your_webhook_signing_secret";
    static final int ACCOUNT = 14;
    static final HttpClient HTTP = HttpClient.newHttpClient();

    static String send(String method, String path, String json) throws Exception {
        HttpRequest.Builder b = HttpRequest.newBuilder(URI.create(BASE + path)).timeout(Duration.ofSeconds(60))
            .header("X-API-Key", KEY).header("X-API-Secret", SECRET).header("Content-Type", "application/json");
        b = json == null ? b.GET() : b.method(method, HttpRequest.BodyPublishers.ofString(json));
        return HTTP.send(b.build(), HttpResponse.BodyHandlers.ofString()).body();
    }

    public static String collect(String phone, long amount, String country, String ref) throws Exception {
        return send("POST", "/stkpush.php", String.format(
            "{\"payment_account_id\":%d,\"phone\":\"%s\",\"amount\":%d,\"country\":\"%s\",\"reference\":\"%s\"}",
            ACCOUNT, phone, amount, country, ref));
    }
    public static String status(String id) throws Exception {
        return send("POST", "/status.php", "{\"transaction_id\":\"" + id + "\"}");
    }
    public static String payout(String phone, int amount) throws Exception { // never retry on timeout
        return send("POST", "/payout.php", String.format("{\"phone\":\"%s\",\"amount\":%d,\"remarks\":\"Payout\"}", phone, amount));
    }
    public static String payoutStatus(String id) throws Exception {
        return send("GET", "/payout.php?transaction_id=" + URLEncoder.encode(id, StandardCharsets.UTF_8), null);
    }
    public static boolean verify(String rawBody, String sig) throws Exception {
        Mac m = Mac.getInstance("HmacSHA256");
        m.init(new SecretKeySpec(WH_SECRET.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        StringBuilder sb = new StringBuilder("sha256=");
        for (byte x : m.doFinal(rawBody.getBytes(StandardCharsets.UTF_8))) sb.append(String.format("%02x", x));
        return java.security.MessageDigest.isEqual(sb.toString().getBytes(), sig.getBytes());
    }
}
C# kit · 1 file

.NET 6+, no packages. Add Infinexpay.cs to your project.

⇩ Download C# ZIP

Infinexpay.cs
C# · Infinexpay.cs
using System.Net.Http.Json;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;

public static class Infinexpay
{
    const string Base = "https://www.infinexpay.co.ke.gazelleusacompany.com/api/v2";
    const string WhSecret = "your_webhook_signing_secret";
    const int Account = 14;
    static readonly HttpClient Http = Create();

    static HttpClient Create()
    {
        var c = new HttpClient { Timeout = TimeSpan.FromSeconds(60) };
        c.DefaultRequestHeaders.Add("X-API-Key", "your_api_key");
        c.DefaultRequestHeaders.Add("X-API-Secret", "your_api_secret");
        return c;
    }

    static async Task<JsonElement> Post(string path, object body) =>
        await (await Http.PostAsJsonAsync(Base + path, body)).Content.ReadFromJsonAsync<JsonElement>();

    public static Task<JsonElement> Collect(string phone, long amount, string country, string reference) =>
        Post("/stkpush.php", new { payment_account_id = Account, phone, amount, country, reference });

    public static Task<JsonElement> Status(string id) => Post("/status.php", new { transaction_id = id });

    // Never retry a payout on timeout. Check PayoutStatus first.
    public static Task<JsonElement> Payout(string phone, int amount, string? name = null) =>
        Post("/payout.php", new { phone, amount, remarks = "Payout", recipient_name = name });

    public static Task<JsonElement> PayoutStatus(string id) =>
        Http.GetFromJsonAsync<JsonElement>($"{Base}/payout.php?transaction_id={Uri.EscapeDataString(id)}")!;

    public static bool Verify(string rawBody, string sig)
    {
        using var h = new HMACSHA256(Encoding.UTF8.GetBytes(WhSecret));
        var calc = "sha256=" + Convert.ToHexString(h.ComputeHash(Encoding.UTF8.GetBytes(rawBody))).ToLower();
        return CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(calc), Encoding.UTF8.GetBytes(sig ?? ""));
    }
}
cURL kit · 1 file

Run in any terminal. Replace the credentials first.

⇩ Download cURL ZIP

examples.sh
cURL · examples.sh
#!/bin/sh
KEY="your_api_key"; SECRET="your_api_secret"; BASE="https://www.infinexpay.co.ke.gazelleusacompany.com/api/v2"

# Collect (STK Push)
curl -X POST "$BASE/stkpush.php" -H "X-API-Key: $KEY" -H "X-API-Secret: $SECRET" -H "Content-Type: application/json" \
  -d '{"payment_account_id":14,"country":"KE","phone":"254712345678","amount":100,"reference":"ORDER123"}'

# Check status
curl -X POST "$BASE/status.php" -H "X-API-Key: $KEY" -H "X-API-Secret: $SECRET" -H "Content-Type: application/json" \
  -d '{"transaction_id":"gw_1042"}'

# Payout (Kenya). Never retry on timeout.
curl -X POST "$BASE/payout.php" -H "X-API-Key: $KEY" -H "X-API-Secret: $SECRET" -H "Content-Type: application/json" \
  -d '{"phone":"254712345678","amount":150,"remarks":"Payout"}'

# Check payout
curl "$BASE/payout.php?transaction_id=gw_1042" -H "X-API-Key: $KEY" -H "X-API-Secret: $SECRET"

⇩ Download all languages (one ZIP)

Never retry a payout blindly

After a timeout or a null transaction_id, check the payout status or your transactions before sending again, or the recipient can be paid twice.


Endpoints

Six endpoints cover the money-movement lifecycle. Each returns the same shape for every country.

Prompts a customer's phone to approve a payment in any supported country, or redirects them to a hosted page when the response says so.

POST/stkpush.php
ParameterTypeRequiredDescription
payment_account_idIntegerYesYour payment account ID
phoneStringYesInternational format, no spaces or +, e.g. 254712345678
amountFloatYesAmount in the local currency. Whole numbers for UGX, RWF, TZS, XAF, XOF
countryStringNoISO code. Detected from the phone prefix if omitted, defaulting to KE. Sending it is safer
referenceStringNoYour internal reference
descriptionStringNoDescription shown in your records
Success · 200 OK
{
  "success": true,
  "message": "STK push initiated",
  "transaction_id": "gw_1042",
  "checkout_request_id": "gw_1042",
  "fee_deducted": 1.50,
  "action": "prompt",
  "redirect_url": null
}
  • transaction_id: an opaque string used to check status. checkout_request_id carries the same value for backward compatibility.
  • fee_deducted: processing fee in KES.
  • action: prompt = customer approves on their phone; redirect = send them to redirect_url.

Example request body

Uganda · UGX
{
  "payment_account_id": 14,
  "country": "UG",
  "phone": "256772123456",
  "amount": 10000,
  "reference": "ORDER123"
}

Checks any payment (collection, top-up or payout) by transaction_id. For payouts you can also use GET /payout.php.

POST/status.php
ParameterTypeRequiredDescription
transaction_idStringYesThe ID returned by STK Push, top-up or payout
Success · 200 OK
{
  "success": true,
  "status": "completed",
  "transaction_id": "ws_CO_20260101120000_abc123",
  "amount": 100,
  "fee": 1.5,
  "currency": "KES",
  "phone": "254712345678",
  "transaction_code": "ABC123DEF456",
  "created_at": "2026-01-01 12:00:00"
}

transaction_code is the mobile money receipt when available, otherwise null.

pending in progress  ·  completed funds received or sent  ·  failed cancelled, rejected or timed out

Your transactions, newest first (collections and payouts). Also useful to confirm the final state of a pending payout.

GET/transactions.php?page=1&limit=10
ParameterTypeRequiredDescription
pageIntegerNoPage number, default 1
limitIntegerNoItems per page, max 500, default 100
Success · 200 OK
{
  "success": true,
  "data": {
    "summary": { "total_transactions": 150, "successful": 120, "pending": 5, "failed": 25,
                 "successful_amount": 54000.00, "successful_payout_amount": 12000.00 },
    "pagination": { "total_records": 150, "current_page": 1, "per_page": 10, "total_pages": 15 },
    "transactions": [{
      "reference": "ABC123DEF456", "gateway": "mpesa", "amount": 100.00, "fee": 1.50,
      "phone": "254712345678", "status": "success", "direction": "collection",
      "created_at": "2026-01-01 12:00:00", "source": "API"
    }]
  }
}

status is success, pending or failed. direction is collection or payout.

Deposits funds into your service wallet via STK Push. Kenyan numbers and KES only.

POST/topup.php
ParameterTypeRequiredDescription
phoneStringYesKenyan number (07…, +254… or 254…)
amountFloatYesKES, must be > 0. May be rounded up, so use the returned amount/amount_added

The fee is charged to your service balance in KES and the full amount is credited to your wallet. If the prompt can't be sent, the fee is returned. When status is completed, transaction_id is the M-Pesa receipt; when pending, it is the checkout ID. Handle both.

Completed
{
  "success": true,
  "status": "completed",
  "transaction_id": "QGR45TX79K",
  "amount_added": 100.00,
  "fee_deducted": 1.50,
  "message": "Deposit processed and credited successfully"
}
Pending
{
  "success": true,
  "status": "pending",
  "transaction_id": "ws_CO_18052026023512345678",
  "action": "prompt",
  "redirect_url": null,
  "amount": 100.00,
  "fee_deducted": 1.50,
  "message": "STK Push popup sent successfully. Complete PIN entry on your handset."
}
Insufficient service balance

HTTP 402 with a message such as Insufficient Service Balance for processing fee (Need KES 1.50).

Sends money from your service wallet to an M-Pesa number. The recipient gets exactly the amount you request. Kenyan numbers and KES only; the provider is chosen automatically. Try it in the sandbox.

Send a payout

POST/payout.php
ParameterTypeRequiredDescription
phoneStringYes0712345678, 712345678, +254712345678 or 254712345678. Normalised to 254XXXXXXXXX; must start with 7 or 1 after the prefix
amountIntegerYesWhole KES the recipient receives, 25 to 150,000. Decimals are rejected, not rounded
recipient_nameStringNoUp to 100 characters
remarksStringNoUp to 100 characters. Default Withdrawal
occasionStringNoUp to 100 characters. Safaricom only
command_idStringNoBusinessPayment (default), SalaryPayment or PromotionPayment. Safaricom only
  • Your wallet is debited amount; the fee is debited from your service balance.
  • Both balances are checked and debited together. If either is too low, nothing is debited and you get HTTP 402.
  • If the provider rejects the payout, both balances are restored automatically.
  • Body must be valid JSON, at most 10,000 bytes.
Completed · 200 OK
{
  "success": true,
  "status": "completed",
  "message": "Payout successful",
  "transaction_id": "SLK1A2B3C4",
  "conversation_id": "AG_20260101_000012345",
  "amount_sent": 150,
  "fee_deducted": 1.5,
  "fee_source": "service_balance",
  "total_debited": 150,
  "currency": "KES"
}
Pending, confirmation delayed · 200 OK
{
  "success": true,
  "status": "pending",
  "message": "Submission is being confirmed. Check status later.",
  "transaction_id": null,
  "local_reference": 4821,
  "amount_sent": 150,
  "fee_deducted": 1.5,
  "currency": "KES"
}
If transaction_id is null, do not retry

The provider may already have accepted the payout. Resending can pay the recipient twice. Wait for your webhook or find the payout in your transactions list. The same applies if your request times out.

Insufficient service balance · 402
{
  "success": false,
  "message": "Insufficient service balance to pay the withdrawal fee.",
  "fee_required": 1.50,
  "service_balance": 0.50,
  "fee_source": "service_balance"
}
Validation error · 400
{
  "success": false,
  "message": "Minimum payout amount is KES 25.",
  "code": "amount_too_low",
  "min": 25
}

status is completed if finished within about 8 seconds, otherwise pending. transaction_id is an opaque string (M-Pesa receipt when completed, conversation ID while pending, or gw_…). local_reference is only returned when transaction_id is null; quote it to support. fee_source is always service_balance and currency always KES.

Check a payout

GET/payout.php?transaction_id=gw_1042
Completed
{
  "success": true,
  "status": "completed",
  "transaction_id": "AG_20260101_000012345",
  "receipt": "SLK1A2B3C4",
  "amount_sent": 150,
  "fee_deducted": 1.5,
  "currency": "KES"
}

Poll every 3 to 5 seconds for a couple of minutes, then rely on your webhook. A final failed means your wallet and fee were refunded. Treat completed as done, failed as refunded and pending as still working; only resend after confirming failed.

Payout error codes

HTTPcodeMeaning
400invalid_jsonBody is not a valid JSON object
400invalid_phoneNot a valid Kenyan M-Pesa number
400invalid_amountMissing, not a number, or has decimals
400amount_too_lowBelow KES 25 (includes min)
400amount_too_highAbove KES 150,000 (includes max)
400invalid_command_idNot an allowed value
400missing_transaction_idGET without transaction_id
404not_foundUnknown transaction, or it belongs to another account
413body_too_largeBody exceeds 10,000 bytes

Accepts USDT deposits from customers anywhere and settles the KES-equivalent into your service wallet automatically.

POST/crypto_deposit.php
ParameterTypeRequiredDescription
amountFloatYesDeposit amount in USD
order_idStringYesUnique identifier for this deposit
Success · 200 OK
{
  "success": true,
  "checkout_url": "https://infinexpay.co.ke/checkout/crypto/secure_frame"
}
Network restriction

USDT on TRON (TRC20) only. Deposits sent via Ethereum (ERC20) or BSC (BEP20) cannot be recovered.


Countries & currencies

A country only works while the administrator has enabled deposits for it; otherwise you get Payments are not available for this country right now. Amounts are always in the customer's local currency, phone numbers in international format. Fees are charged to your service balance in KES. Payouts and top-ups are Kenya only.

CountryCodeCurrencyDialDecimals
KenyaKEKES2542
NigeriaNGNGN2342
GhanaGHGHS2332
ZambiaZMZMW2602
DR CongoCDCDF2432
Sierra LeoneSLSLE2322
UgandaUGUGX2560 (whole numbers)
TanzaniaTZTZS2550 (whole numbers)
RwandaRWRWF2500 (whole numbers)
CameroonCMXAF2370 (whole numbers)
GabonGAXAF2410 (whole numbers)
Congo-BrazzavilleCGXAF2420 (whole numbers)
SenegalSNXOF2210 (whole numbers)
BeninBJXOF2290 (whole numbers)
Côte d'IvoireCIXOF2250 (whole numbers)

Webhooks

When a payout or deposit settles, Infinexpay posts the result to your webhooks (up to 5 URLs in Developer settings). You can also poll /status.php.

  • URLs must use https and be publicly reachable.
  • Reply with any 2xx within 10 seconds.
  • Use Send test event in Developer settings and check the delivery log.
  • Make your handler idempotent: the same event can arrive more than once.
  • Laravel: your webhook URL is https://your-site.com/infinexpay/webhook. The kit verifies the signature and fires a WebhookReceived event.
Webhook payload
{
  "status": "success",
  "transaction_id": "OP_PAY_881272",
  "mpesa_receipt": "RBC9982XX",
  "amount": 150.00,
  "phone": "254712345678",
  "reference": "ORDER_9921",
  "timestamp": "2026-03-20 10:15:00"
}
HeaderDescription
X-Webhook-EventEvent name, e.g. payout.completed or test
X-Webhook-IdUnique delivery ID. Use it to ignore repeats
X-Webhook-Signaturesha256= + HMAC-SHA256 of the raw body using that webhook's signing secret

Always verify the signature over the raw body before parsing JSON. Every kit above includes a ready verification function.


Error handling

CodeMeaning
200Success
400Bad request: invalid parameters, unsupported country, provider rejected
401Missing or invalid API credentials
402Insufficient service balance (fees) or wallet balance (payouts)
403Account not verified: complete KYC first
404Not found
405Method not allowed
413Request body too large (payout)
500Internal server error
502Payment provider could not be reached

Common messages

  • Transaction failed. Please contact support. (402, STK Push): service balance can't cover the fee
  • Insufficient Service Balance for processing fee (Need KES x.xx) (402, top-up)
  • Insufficient wallet balance. (402, payout): wallet can't cover the amount
  • Insufficient service balance to pay the withdrawal fee. (402, payout): includes fee_required and service_balance
  • Payout rejected: … (400) / Payment Gateway OAuth Handshake Failed. (502): both balances are restored automatically
  • Bridge Error (500, payout): check transactions and balances before retrying
  • Withdrawals are not available for Kenya right now / Deposits are not available for Kenya right now: no provider active
  • Payments are not available for this country right now.: country not enabled
  • UGX amounts must be whole numbers: zero-decimal currencies reject decimals
  • Fee conversion is unavailable for this currency: fee could not be converted to KES
  • Account not verified. Complete KYC verification first. (403)
  • Missing API credentials / Invalid or inactive API credentials (401)
  • Invalid JSON body / payment_account_id, phone and amount are required / Payment account not found (400/404)
  • Transaction not found (404): unknown ID or another account's
  • Failed to generate Safaricom validation token (502) / Daraja STK Push Rejection: … (400): top-up prompt could not be sent; fee returned
  • Topup Bridge Error / Server error (500)

Going live

  • Switch the Safaricom gateway from sandbox to production and use production credentials.
  • Make the B2C result and timeout URLs reachable over public HTTPS, or payouts stay pending.
  • Fund your service balance: every fee comes from it.
  • Confirm each country you sell in is enabled, and test one small payment per country.
  • Treat pending as in progress. Confirm via status, transactions or webhook before retrying anything.
  • Never resend a payout after a timeout or a null transaction_id until you've checked its status.
  • Send whole numbers for UGX, TZS, RWF, XAF, XOF, and whole KES for payouts.
  • Verify webhook signatures and make handlers idempotent.
  • Keep your API secret server-side, never in HTML or browser JavaScript.
  • Laravel: keep the payout route disabled unless it sits behind auth middleware.
  • Start with a small real payout and check the receipt, both balances and the transaction row.

Live sandbox

These are real requests against your own credentials. Production sends real money; a sandbox gateway does not.

Collection test

Results appear here.

Test a payout (Kenya)

Real money warning

In production a successful payout sends real KES. To test safely use a sandbox gateway and Safaricom's test number 254708374149. The validation checks never reach the provider.

Payout results appear here.