API documentation
Base URL: https://stackhero.co.ke. Send JSON bodies and read JSON responses. Every response has success, and either data or error.
Authentication
Each linked till, paybill or bank has its own account_id and secret_key. You can find them under Linked accounts. Send them in the JSON body, or as the X-Account-Id and X-Secret-Key headers. Keep the secret key on your server and never put it in a website or mobile app.
Send an STK push
| Field | Required | Description |
|---|---|---|
account_id | Yes | Account ID of the linked till, paybill or bank |
secret_key | Yes | Secret key for that account |
phone | Yes | Customer phone: 0712345678, 254712345678 or +254… |
amount | Yes | Whole shillings, 1 – 250,000 |
reference | Yes | Your order or invoice number (max 100 characters) |
description | No | Short description (first 13 characters are sent to M-Pesa) |
callback_url | No | HTTPS URL for this payment's result. Overrides the account's webhook URL |
curl -X POST https://stackhero.co.ke/v1/stkpush \
-H "Content-Type: application/json" \
-d '{
"account_id": "NRVJZ4D3TJZS8",
"secret_key": "sk_...",
"phone": "0712345678",
"amount": 100,
"reference": "INV-1001",
"callback_url": "https://yourshop.co.ke/mpesa/result"
}'
{
"success": true,
"message": "STK push sent. The customer should enter their M-Pesa PIN.",
"data": {
"transaction_request_id": "TRX260924LH9GZ2DQFR",
"status": "pending",
"amount": 100,
"phone": "254712345678",
"reference": "INV-1001",
"transaction_type": "CustomerBuyGoodsOnline",
"party_b": "5123456",
"checkout_request_id": "ws_CO_24092026003133...",
"customer_message": "Success. Request accepted for processing"
}
}
Save transaction_request_id. You need it to check the status or ask for the webhook again.
Check transaction status
{
"account_id": "NRVJZ4D3TJZS8",
"secret_key": "sk_...",
"transaction_request_id": "TRX260924LH9GZ2DQFR"
}
| status | Meaning |
|---|---|
pending | Waiting for the customer to enter their PIN |
success | Paid. mpesa_receipt and transaction_date are set |
cancelled | Customer cancelled the prompt |
timeout | Customer did not respond in time |
failed | Other failure, e.g. insufficient funds. See result_desc |
Webhooks
When a payment finishes, we POST the result to the payment's callback_url, or to the webhook URL set on the account. Reply with any 2xx status. If your server does not answer, we retry after 1 min, 5 min, 15 min, 1 h and 6 h.
{
"event": "stkpush.success",
"delivery_id": 12,
"attempt": 1,
"sent_at": "2026-09-24T00:31:02+03:00",
"data": {
"transaction_request_id": "TRX260924LH9GZ2DQFR",
"status": "success",
"result_code": "0",
"result_desc": "The service request is processed successfully.",
"amount": 100,
"reference": "INV-1001",
"mpesa_receipt": "TIN4ABC123",
"transaction_date": "2026-09-24T00:31:00+03:00"
},
"safaricom": { "Body": { "stkCallback": { "...": "exactly what Safaricom sent" } } }
}
Events: stkpush.success, stkpush.failed, stkpush.cancelled, stkpush.timeout.
Verify the signature
Every webhook has X-StackHero-Timestamp and X-StackHero-Signature headers. Check them with the account's webhook secret:
<?php
$body = file_get_contents('php://input');
$timestamp = $_SERVER['HTTP_X_STACKHERO_TIMESTAMP'] ?? '';
$expected = 'sha256=' . hash_hmac('sha256', $timestamp . '.' . $body, 'whsec_your_secret');
if (!hash_equals($expected, $_SERVER['HTTP_X_STACKHERO_SIGNATURE'] ?? '')) {
http_response_code(401);
exit;
}
$event = json_decode($body, true);
// mark order $event['data']['reference'] as paid when $event['data']['status'] === 'success'
http_response_code(200);
Resend a webhook
Sends a completed payment's result again, right away. Add an optional callback_url to send it somewhere else.
{
"account_id": "NRVJZ4D3TJZS8",
"secret_key": "sk_...",
"transaction_request_id": "TRX260924LH9GZ2DQFR",
"callback_url": "https://yourshop.co.ke/mpesa/result"
}
Errors
{
"success": false,
"error": {
"code": "validation_error",
"message": "Some fields are missing or invalid",
"details": { "phone": "Provide a valid Safaricom number, e.g. 0712345678 or 254712345678" }
}
}
| HTTP | code | When |
|---|---|---|
| 401 | invalid_credentials | Wrong account_id or secret_key |
| 403 | account_disabled | The linked account is disabled |
| 403 | account_inactive | The account has not paid its activation fee yet |
| 402 | insufficient_tokens | Not enough tokens for a push of this amount (the cost depends on the amount); details has token_balance, tokens_required and amount. Buy tokens in the merchant portal |
| 404 | transaction_not_found | Unknown transaction_request_id for this account |
| 422 | validation_error | Missing or invalid fields. See details |
| 429 | rate_limited | Too many STK pushes in one minute |
| 401 | invalid_credentials | Wallet API: wrong wallet_id or secret_key |
| 403 | wallet_disabled / wallet_deposits_off | Wallet API: the wallet is disabled, or new deposits are paused (balance and withdrawals still work) |
| 404 | deposit_not_found / withdrawal_not_found | Wallet API: unknown id for this wallet |
| 422 | insufficient_balance | Wallet API: withdrawal larger than the balance; details has balance and amount |
| 429 | too_many_pending | Wallet API: already 5 withdrawals waiting on this wallet |
| 502 | mpesa_rejected / gateway_error | Safaricom refused the request or could not be reached |
Wallet API
A wallet holds money for you. Customers pay into it by M-Pesa STK push, and each payment is added to your balance as soon as Safaricom confirms it. You withdraw to M-Pesa whenever you like. Withdrawals are checked and paid by hand, minus a 10% fee (minimum withdrawal KES 100). If one cannot be paid, the full amount goes back to your wallet.
| Step | What happens | You get |
|---|---|---|
| 1. Deposit | POST /v1/wallet/deposit sends the customer an M-Pesa prompt | transaction_request_id |
| 2. Paid | The customer pays; we confirm it with Safaricom and credit the full amount | deposit.success webhook with balance_after |
| 3. Withdraw | POST /v1/wallet/withdraw takes the amount from the balance | withdrawal.requested webhook |
| 4. Paid out | We send amount − fee to your payout number | withdrawal.paid webhook with the M-Pesa receipt (or withdrawal.rejected and the money back) |
Authentication
Create a wallet under Wallet in the portal. Each wallet has a wallet_id (e.g. NRWK7M2Q9XA4), a secret_key (wsk_…, shown once) and a signing_key (wsig_…) for checking webhooks. Send wallet_id and secret_key in every JSON body, or as the X-Wallet-Id and X-Wallet-Secret headers. Keep the secret on your server only. All amounts are whole Kenyan shillings.
Deposit (receive a payment)
| Field | Required | Description |
|---|---|---|
phone | Yes | Customer phone: 0712345678, 254712345678 or +254… |
amount | Yes | Whole shillings, 1 – 250,000 |
reference | Yes | Your order or invoice number (max 100 characters) |
description | No | Short description (first 13 characters are sent to M-Pesa) |
callback_url | No | HTTPS URL for this deposit's webhook. Overrides the wallet's webhook URL |
curl -X POST https://stackhero.co.ke/v1/wallet/deposit \
-H "Content-Type: application/json" \
-H "X-Wallet-Id: NRWK7M2Q9XA4" \
-H "X-Wallet-Secret: wsk_..." \
-d '{ "phone": "0712345678", "amount": 500, "reference": "ORDER-1001" }'
{
"success": true,
"message": "STK push sent. The wallet is credited as soon as the customer pays.",
"data": {
"transaction_request_id": "TRX261109K3M8QZ2WPA",
"wallet_id": "NRWK7M2Q9XA4",
"status": "pending",
"amount": 500,
"phone": "254712345678",
"reference": "ORDER-1001",
"mpesa_receipt": null,
"credited": false,
"balance_after": null,
"customer_message": "Success. Request accepted for processing"
}
}
Deposits do not use tokens. Only a payment confirmed by Safaricom is credited, and each payment is credited exactly once.
Deposit status
{ "wallet_id": "NRWK7M2Q9XA4", "secret_key": "wsk_...", "transaction_request_id": "TRX261109K3M8QZ2WPA" }
Returns the same shape as the deposit. status is pending, success, cancelled, timeout or failed. When it is success, credited is true and balance_after is the wallet balance right after this payment. A pending deposit is checked with Safaricom when you ask.
Balance
{
"success": true,
"data": {
"wallet_id": "NRWK7M2Q9XA4",
"name": "My shop",
"status": "active",
"currency": "KES",
"balance": 12500,
"pending_withdrawals": { "count": 1, "amount": 2000 },
"total_deposited": 54500,
"total_withdrawn": 36000,
"payout_phone": "254712345678",
"withdrawal_fee_percent": 10,
"min_withdrawal": 100,
"max_withdrawal": 250000 }
}
balance is what you can withdraw now. Money in waiting withdrawals has already left it.
Withdraw
| Field | Required | Description |
|---|---|---|
amount | Yes | Taken from the balance. You receive amount − fee (fee 10%, rounded up to the next shilling) |
reference | Recommended | Your own id for this withdrawal (letters, numbers, . _ - :, max 64). Sending the same reference again returns the first request and never takes money twice, so retries are safe |
API withdrawals are always paid to the wallet's payout number, set in the portal under the wallet's Settings (changing it needs your password). They are paid by hand, usually the same day.
{ "wallet_id": "NRWK7M2Q9XA4", "secret_key": "wsk_...", "amount": 1000, "reference": "PAYOUT-2026-11-09" }
{
"success": true,
"message": "Withdrawal requested. It is paid by hand; you get a withdrawal.paid webhook with the M-Pesa receipt.",
"data": {
"withdrawal_id": "WDR261109H7K2M9QX",
"wallet_id": "NRWK7M2Q9XA4",
"status": "pending",
"amount": 1000,
"fee": 100,
"fee_percent": 10,
"payout": 900,
"phone": "254712345678",
"reference": "PAYOUT-2026-11-09",
"mpesa_receipt": null,
"wallet_balance": 11500,
"requested_at": "2026-11-09T10:15:00+03:00",
"decided_at": null
}
}
Withdrawal status
{ "wallet_id": "NRWK7M2Q9XA4", "secret_key": "wsk_...", "withdrawal_id": "WDR261109H7K2M9QX" }
| status | Meaning |
|---|---|
pending | Waiting to be paid. The amount has left the balance |
paid | Sent. mpesa_receipt is the receipt of the payout |
rejected | Not paid; the full amount is back in the wallet. note says why |
Wallet transactions
Every change to the balance, newest first. Optional limit (1–100, default 30). For the next page send before_id = the next_before_id you got.
{
"success": true,
"data": {
"wallet_id": "NRWK7M2Q9XA4",
"balance": 11500,
"entries": [
{ "id": 88, "type": "withdrawal", "amount": -1000, "balance_after": 11500, "withdrawal_id": "WDR261109H7K2M9QX", "created_at": "2026-11-09T10:15:00+03:00" },
{ "id": 87, "type": "deposit", "amount": 500, "balance_after": 12500, "transaction_request_id": "TRX261109K3M8QZ2WPA", "mpesa_receipt": "TKB4XY12AB", "created_at": "2026-11-09T09:58:12+03:00" }
],
"next_before_id": 87
}
}
type is deposit (+), withdrawal (−) or withdrawal_refund (+, a rejected withdrawal coming back).
Wallet webhooks
Set the wallet's webhook URL in the portal. We POST each event there (a deposit's own callback_url wins for that deposit). Reply with any 2xx status. If your server does not answer, we retry after 1 min, 5 min, 15 min, 1 h and 6 h. The wallet page lists every delivery, with Resend and Send test webhook buttons.
| Event | When |
|---|---|
deposit.success | A payment was confirmed and credited |
deposit.failed / deposit.cancelled / deposit.timeout | The customer did not pay; nothing was credited |
withdrawal.requested | A withdrawal was asked for (portal or API) |
withdrawal.paid | The payout was sent; has mpesa_receipt |
withdrawal.rejected | Not paid; the amount is back in the wallet |
wallet.test | You pressed "Send test webhook" |
POST https://yourshop.co.ke/wallet/webhook
X-StackHero-Event: deposit.success
X-StackHero-Timestamp: 1762671492
X-StackHero-Signature: sha256=5f0c…
{
"event": "deposit.success",
"delivery_id": 31,
"attempt": 1,
"sent_at": "2026-11-09T09:58:12+03:00",
"data": {
"transaction_request_id": "TRX261109K3M8QZ2WPA",
"wallet_id": "NRWK7M2Q9XA4",
"status": "success",
"amount": 500,
"reference": "ORDER-1001",
"mpesa_receipt": "TKB4XY12AB",
"credited": true,
"balance_after": 12500
}
}
Verify the signature
Compute HMAC-SHA256(timestamp + "." + raw_body, signing_key) and compare it with X-StackHero-Signature. Reject old timestamps (e.g. older than 5 minutes) and treat delivery_id you have already handled as a duplicate. The same payment is never credited twice on our side, but a webhook can arrive more than once.
Sample code
PHP
<?php
final class StackHeroWallet
{
public function __construct(
private string $walletId,
private string $secretKey,
private string $baseUrl = 'https://stackhero.co.ke'
) {}
public function deposit(string $phone, int $amount, string $reference): array
{
return $this->call('/v1/wallet/deposit', compact('phone', 'amount', 'reference'));
}
public function depositStatus(string $requestId): array
{
return $this->call('/v1/wallet/deposit/status', ['transaction_request_id' => $requestId]);
}
public function balance(): array
{
return $this->call('/v1/wallet/balance');
}
/** Use a unique $reference so a retry never withdraws twice. */
public function withdraw(int $amount, string $reference): array
{
return $this->call('/v1/wallet/withdraw', compact('amount', 'reference'));
}
public function withdrawalStatus(string $withdrawalId): array
{
return $this->call('/v1/wallet/withdrawal/status', ['withdrawal_id' => $withdrawalId]);
}
public function transactions(int $limit = 30, ?int $beforeId = null): array
{
return $this->call('/v1/wallet/transactions', array_filter(['limit' => $limit, 'before_id' => $beforeId]));
}
private function call(string $path, array $body = []): array
{
$ch = curl_init($this->baseUrl . $path);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 40,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'X-Wallet-Id: ' . $this->walletId,
'X-Wallet-Secret: ' . $this->secretKey,
],
CURLOPT_POSTFIELDS => json_encode($body),
]);
$response = json_decode((string) curl_exec($ch), true) ?? [];
if (empty($response['success'])) {
throw new RuntimeException($response['error']['message'] ?? 'Request failed');
}
return $response['data'];
}
}
$wallet = new StackHeroWallet('NRWK7M2Q9XA4', getenv('STACKHERO_WALLET_SECRET'));
$deposit = $wallet->deposit('0712345678', 500, 'ORDER-1001');
echo $deposit['transaction_request_id'];
echo $wallet->balance()['balance'];
PHP webhook receiver
<?php
$body = file_get_contents('php://input');
$timestamp = $_SERVER['HTTP_X_STACKHERO_TIMESTAMP'] ?? '';
$expected = 'sha256=' . hash_hmac('sha256', $timestamp . '.' . $body, getenv('STACKHERO_WALLET_SIGNING_KEY'));
if (!hash_equals($expected, $_SERVER['HTTP_X_STACKHERO_SIGNATURE'] ?? '') || abs(time() - (int) $timestamp) > 300) {
http_response_code(401);
exit;
}
$event = json_decode($body, true);
switch ($event['event']) {
case 'deposit.success':
// mark order $event['data']['reference'] as paid (once: check $event['data']['transaction_request_id'])
break;
case 'withdrawal.paid':
// $event['data']['mpesa_receipt'] is the M-Pesa receipt of your payout
break;
case 'withdrawal.rejected':
// $event['data']['note'] says why; the money is back in the wallet
break;
}
http_response_code(200);
Node.js
const crypto = require('crypto');
const BASE = 'https://stackhero.co.ke';
const HEADERS = {
'Content-Type': 'application/json',
'X-Wallet-Id': 'NRWK7M2Q9XA4',
'X-Wallet-Secret': process.env.STACKHERO_WALLET_SECRET,
};
async function wallet(path, body = {}) {
const res = await fetch(BASE + path, { method: 'POST', headers: HEADERS, body: JSON.stringify(body) });
const json = await res.json();
if (!json.success) throw new Error(json.error.message);
return json.data;
}
// Receive KES 500, then withdraw KES 1,000
const deposit = await wallet('/v1/wallet/deposit', { phone: '0712345678', amount: 500, reference: 'ORDER-1001' });
const payout = await wallet('/v1/wallet/withdraw', { amount: 1000, reference: 'PAYOUT-2026-11-09' });
// Webhook check (Express, with express.raw({ type: 'application/json' }))
function verify(req) {
const ts = req.get('X-StackHero-Timestamp');
const expected = 'sha256=' + crypto.createHmac('sha256', process.env.STACKHERO_WALLET_SIGNING_KEY)
.update(ts + '.' + req.body.toString('utf8')).digest('hex');
const given = req.get('X-StackHero-Signature') || '';
return given.length === expected.length && crypto.timingSafeEqual(Buffer.from(given), Buffer.from(expected));
}
Python
import hashlib, hmac, os, requests
BASE = "https://stackhero.co.ke"
HEADERS = {"X-Wallet-Id": "NRWK7M2Q9XA4", "X-Wallet-Secret": os.environ["STACKHERO_WALLET_SECRET"]}
def wallet(path, **body):
r = requests.post(BASE + path, json=body, headers=HEADERS, timeout=40).json()
if not r["success"]:
raise RuntimeError(r["error"]["message"])
return r["data"]
deposit = wallet("/v1/wallet/deposit", phone="0712345678", amount=500, reference="ORDER-1001")
print(wallet("/v1/wallet/balance")["balance"])
def verify(raw_body: bytes, timestamp: str, signature: str) -> bool:
key = os.environ["STACKHERO_WALLET_SIGNING_KEY"].encode()
expected = "sha256=" + hmac.new(key, timestamp.encode() + b"." + raw_body, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, signature)