N Stack Hero

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

POST /v1/stkpush
FieldRequiredDescription
account_idYesAccount ID of the linked till, paybill or bank
secret_keyYesSecret key for that account
phoneYesCustomer phone: 0712345678, 254712345678 or +254…
amountYesWhole shillings, 1 – 250,000
referenceYesYour order or invoice number (max 100 characters)
descriptionNoShort description (first 13 characters are sent to M-Pesa)
callback_urlNoHTTPS 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

POST /v1/tstatus
{
  "account_id": "NRVJZ4D3TJZS8",
  "secret_key": "sk_...",
  "transaction_request_id": "TRX260924LH9GZ2DQFR"
}
statusMeaning
pendingWaiting for the customer to enter their PIN
successPaid. mpesa_receipt and transaction_date are set
cancelledCustomer cancelled the prompt
timeoutCustomer did not respond in time
failedOther 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

POST /v1/webhook/resend

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" }
  }
}
HTTPcodeWhen
401invalid_credentialsWrong account_id or secret_key
403account_disabledThe linked account is disabled
403account_inactiveThe account has not paid its activation fee yet
402insufficient_tokensNot 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
404transaction_not_foundUnknown transaction_request_id for this account
422validation_errorMissing or invalid fields. See details
429rate_limitedToo many STK pushes in one minute
401invalid_credentialsWallet API: wrong wallet_id or secret_key
403wallet_disabled / wallet_deposits_offWallet API: the wallet is disabled, or new deposits are paused (balance and withdrawals still work)
404deposit_not_found / withdrawal_not_foundWallet API: unknown id for this wallet
422insufficient_balanceWallet API: withdrawal larger than the balance; details has balance and amount
429too_many_pendingWallet API: already 5 withdrawals waiting on this wallet
502mpesa_rejected / gateway_errorSafaricom 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.

StepWhat happensYou get
1. DepositPOST /v1/wallet/deposit sends the customer an M-Pesa prompttransaction_request_id
2. PaidThe customer pays; we confirm it with Safaricom and credit the full amountdeposit.success webhook with balance_after
3. WithdrawPOST /v1/wallet/withdraw takes the amount from the balancewithdrawal.requested webhook
4. Paid outWe send amount − fee to your payout numberwithdrawal.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)

POST /v1/wallet/deposit
FieldRequiredDescription
phoneYesCustomer phone: 0712345678, 254712345678 or +254…
amountYesWhole shillings, 1 – 250,000
referenceYesYour order or invoice number (max 100 characters)
descriptionNoShort description (first 13 characters are sent to M-Pesa)
callback_urlNoHTTPS 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

POST /v1/wallet/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

POST /v1/wallet/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

POST /v1/wallet/withdraw
FieldRequiredDescription
amountYesTaken from the balance. You receive amount − fee (fee 10%, rounded up to the next shilling)
referenceRecommendedYour 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

POST /v1/wallet/withdrawal/status
{ "wallet_id": "NRWK7M2Q9XA4", "secret_key": "wsk_...", "withdrawal_id": "WDR261109H7K2M9QX" }
statusMeaning
pendingWaiting to be paid. The amount has left the balance
paidSent. mpesa_receipt is the receipt of the payout
rejectedNot paid; the full amount is back in the wallet. note says why

Wallet transactions

POST /v1/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.

EventWhen
deposit.successA payment was confirmed and credited
deposit.failed / deposit.cancelled / deposit.timeoutThe customer did not pay; nothing was credited
withdrawal.requestedA withdrawal was asked for (portal or API)
withdrawal.paidThe payout was sent; has mpesa_receipt
withdrawal.rejectedNot paid; the amount is back in the wallet
wallet.testYou 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)
Email us WhatsApp