Introduction
The Infinexpay API lets you collect mobile money payments, run crypto checkouts and send payouts through one consistent JSON interface.
| Feature | Coverage |
|---|---|
| Collections (STK Push / mobile money) | 15 countries. See Countries & currencies |
| Crypto deposits (USDT, TRC20) | Any customer, any country |
| Wallet top-up | Kenya (M-Pesa) |
| Payouts | Kenya (M-Pesa) today |
Base URL
https://infinexpay.co.ke.gazelleusacompany.com/api/v2/Response format
{
"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.
| Operation | Fee | Charged to |
|---|---|---|
| STK Push | Set per country and provider. The exact fee is returned in fee_deducted | Service balance, in KES (converted for non-KES countries) |
| Wallet top-up | Set per provider for Kenya. Returned in fee_deducted | Service balance, in KES. The full amount is credited to your wallet |
| Payout | Set per provider for Kenya. Returned in fee_deducted | Service 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.
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.
- Create an account on the dashboard and complete KYC.
- Generate an API key and secret, and set up a payment account (note its ID).
- 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.
<?php
return [
'base_url' => 'https://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',
];<?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]); }
}<?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']<?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.
# 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).INFINEXPAY_BASE_URL=https://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
<?php
return [
'base_url' => env('INFINEXPAY_BASE_URL', 'https://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,
],
];<?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);
}
}<?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) {}
}<?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']);
}
}<?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'));
}
}<?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');<!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
const crypto = require("crypto");
const CFG = { base: "https://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);
};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);import hmac, hashlib, requests
BASE = "https://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 "")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"), 200Ruby kit · 2 files
No gems for the client. Webhook sample needs: gem install sinatra
require "net/http"
require "json"
require "uri"
require "openssl"
module Infinexpay
BASE = "https://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
endrequire "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
endGo kit · 2 files
Standard library only. Put both files in one package, then: go run .
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"net/http"
"net/url"
"time"
)
const (
base = "https://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))
}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.
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://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());
}
}using System.Net.Http.Json;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
public static class Infinexpay
{
const string Base = "https://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 ?? ""));
}
}#!/bin/sh
KEY="your_api_key"; SECRET="your_api_secret"; BASE="https://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.
/stkpush.php| Parameter | Type | Required | Description |
|---|---|---|---|
payment_account_id | Integer | Yes | Your payment account ID |
phone | String | Yes | International format, no spaces or +, e.g. 254712345678 |
amount | Float | Yes | Amount in the local currency. Whole numbers for UGX, RWF, TZS, XAF, XOF |
country | String | No | ISO code. Detected from the phone prefix if omitted, defaulting to KE. Sending it is safer |
reference | String | No | Your internal reference |
description | String | No | Description shown in your records |
{
"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_idcarries the same value for backward compatibility.fee_deducted: processing fee in KES.action:prompt= customer approves on their phone;redirect= send them toredirect_url.
Example request body
{
"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.
/status.php| Parameter | Type | Required | Description |
|---|---|---|---|
transaction_id | String | Yes | The ID returned by STK Push, top-up or payout |
{
"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.
/transactions.php?page=1&limit=10| Parameter | Type | Required | Description |
|---|---|---|---|
page | Integer | No | Page number, default 1 |
limit | Integer | No | Items per page, max 500, default 100 |
{
"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.
/topup.php| Parameter | Type | Required | Description |
|---|---|---|---|
phone | String | Yes | Kenyan number (07…, +254… or 254…) |
amount | Float | Yes | KES, 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.
{
"success": true,
"status": "completed",
"transaction_id": "QGR45TX79K",
"amount_added": 100.00,
"fee_deducted": 1.50,
"message": "Deposit processed and credited successfully"
}{
"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
/payout.php| Parameter | Type | Required | Description |
|---|---|---|---|
phone | String | Yes | 0712345678, 712345678, +254712345678 or 254712345678. Normalised to 254XXXXXXXXX; must start with 7 or 1 after the prefix |
amount | Integer | Yes | Whole KES the recipient receives, 25 to 150,000. Decimals are rejected, not rounded |
recipient_name | String | No | Up to 100 characters |
remarks | String | No | Up to 100 characters. Default Withdrawal |
occasion | String | No | Up to 100 characters. Safaricom only |
command_id | String | No | BusinessPayment (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.
{
"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"
}{
"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.
{
"success": false,
"message": "Insufficient service balance to pay the withdrawal fee.",
"fee_required": 1.50,
"service_balance": 0.50,
"fee_source": "service_balance"
}{
"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
/payout.php?transaction_id=gw_1042{
"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
| HTTP | code | Meaning |
|---|---|---|
| 400 | invalid_json | Body is not a valid JSON object |
| 400 | invalid_phone | Not a valid Kenyan M-Pesa number |
| 400 | invalid_amount | Missing, not a number, or has decimals |
| 400 | amount_too_low | Below KES 25 (includes min) |
| 400 | amount_too_high | Above KES 150,000 (includes max) |
| 400 | invalid_command_id | Not an allowed value |
| 400 | missing_transaction_id | GET without transaction_id |
| 404 | not_found | Unknown transaction, or it belongs to another account |
| 413 | body_too_large | Body exceeds 10,000 bytes |
Accepts USDT deposits from customers anywhere and settles the KES-equivalent into your service wallet automatically.
/crypto_deposit.php| Parameter | Type | Required | Description |
|---|---|---|---|
amount | Float | Yes | Deposit amount in USD |
order_id | String | Yes | Unique identifier for this deposit |
{
"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.
| Country | Code | Currency | Dial | Decimals |
|---|---|---|---|---|
| Kenya | KE | KES | 254 | 2 |
| Nigeria | NG | NGN | 234 | 2 |
| Ghana | GH | GHS | 233 | 2 |
| Zambia | ZM | ZMW | 260 | 2 |
| DR Congo | CD | CDF | 243 | 2 |
| Sierra Leone | SL | SLE | 232 | 2 |
| Uganda | UG | UGX | 256 | 0 (whole numbers) |
| Tanzania | TZ | TZS | 255 | 0 (whole numbers) |
| Rwanda | RW | RWF | 250 | 0 (whole numbers) |
| Cameroon | CM | XAF | 237 | 0 (whole numbers) |
| Gabon | GA | XAF | 241 | 0 (whole numbers) |
| Congo-Brazzaville | CG | XAF | 242 | 0 (whole numbers) |
| Senegal | SN | XOF | 221 | 0 (whole numbers) |
| Benin | BJ | XOF | 229 | 0 (whole numbers) |
| Côte d'Ivoire | CI | XOF | 225 | 0 (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
httpsand be publicly reachable. - Reply with any
2xxwithin 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 aWebhookReceivedevent.
{
"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"
}| Header | Description |
|---|---|
X-Webhook-Event | Event name, e.g. payout.completed or test |
X-Webhook-Id | Unique delivery ID. Use it to ignore repeats |
X-Webhook-Signature | sha256= + 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
| Code | Meaning |
|---|---|
200 | Success |
400 | Bad request: invalid parameters, unsupported country, provider rejected |
401 | Missing or invalid API credentials |
402 | Insufficient service balance (fees) or wallet balance (payouts) |
403 | Account not verified: complete KYC first |
404 | Not found |
405 | Method not allowed |
413 | Request body too large (payout) |
500 | Internal server error |
502 | Payment provider could not be reached |
Common messages
Transaction failed. Please contact support.(402, STK Push): service balance can't cover the feeInsufficient Service Balance for processing fee (Need KES x.xx)(402, top-up)Insufficient wallet balance.(402, payout): wallet can't cover the amountInsufficient service balance to pay the withdrawal fee.(402, payout): includesfee_requiredandservice_balancePayout rejected: …(400) /Payment Gateway OAuth Handshake Failed.(502): both balances are restored automaticallyBridge Error(500, payout): check transactions and balances before retryingWithdrawals are not available for Kenya right now/Deposits are not available for Kenya right now: no provider activePayments are not available for this country right now.: country not enabledUGX amounts must be whole numbers: zero-decimal currencies reject decimalsFee conversion is unavailable for this currency: fee could not be converted to KESAccount 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'sFailed to generate Safaricom validation token(502) /Daraja STK Push Rejection: …(400): top-up prompt could not be sent; fee returnedTopup 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
pendingas in progress. Confirm via status, transactions or webhook before retrying anything. - Never resend a payout after a timeout or a
nulltransaction_iduntil 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
authmiddleware. - 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
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.
