PayHero Kenya: M-Pesa STK Push via the PayHero API
Collect M-Pesa payments into your Till, Paybill or bank account through PayHero: Basic-auth API key, payment channel, STK Push request, callback handling and transaction status.
- Provider
- PayHero Kenya
- Level
- Beginner
- Stacks
- Node.js (Express), PHP
- Code maturity
- Simplified
- Last verified
- 25 Nov 2026
Introduction
PayHero is a Kenyan payments aggregator. You link your own M-Pesa Till, Paybill or bank account to a PayHero account as a *payment channel*, then call one PayHero endpoint to send an M-Pesa STK Push. PayHero handles the Daraja side and posts the result to your callback URL.
This guide covers the API key, finding your channel_id, sending the STK Push, handling the callback idempotently, and checking status.
Warning: PayHero does not document a separate sandbox. Requests run on your live account and consume service-wallet credit; the docs say new developer accounts can request up to KES 300 of test credits from PayHero support. Code here is labelled 'simplified' because it could only be checked against the docs, not executed.
What the API does
POST https://backend.payhero.co.ke/api/v2/payments— send an STK Push to a customer's phone; money lands in the payment channel you choose.GET /api/v2/payment_channels— list your channels (find theidto use aschannel_id).GET /api/v2/transaction-status?reference=...— status of a payment (QUEUED,SUCCESS,FAILED).- A callback POST to your
callback_urlwith the M-Pesa result.
PayHero also documents a payment button, Lipwa payment links, wallet balance/top-up and a WooCommerce plugin; they are not covered here.
Countries and currency
PayHero's documentation is about Kenyan M-Pesa Tills, Paybills and bank paybills, so payments are in KES from M-Pesa customers. amount is an integer in shillings (the docs example is 100), not cents.
Payment methods
- M-Pesa STK Push (
provider: "m-pesa") — covered here. - Settlement to your linked Till, Paybill or bank account via the chosen payment channel.
- The docs also mention integrations with other third-party wallets and a "global payments" page; those were not reviewed for this guide.
When to use PayHero
- You want STK Push without going through Daraja go-live yourself, or you want payments routed to a bank account paybill.
- You are a small business or developer who wants one simple API key and a dashboard.
- You already have a Till/Paybill and want quick automation (or a WooCommerce plugin).
When not to use it
- You need a free sandbox for automated tests — there is none documented.
- You need cards, multi-country or refunds by API — none of these are documented for the STK API.
- You need signed webhooks — PayHero callbacks are not documented as signed.
- You process high volume and want the lowest cost: compare PayHero's published transaction fees with a direct Daraja integration.
Real-world scenarios
- Small online shop: customer enters phone → STK Push → callback marks the order paid → goods dispatched.
- Pay into a bank account: register a bank paybill as a payment channel so customer payments settle to the bank.
- Invoices: use the invoice number as
external_reference; it comes back asExternalReferencein the callback.
Registration and onboarding
- Sign up at app.payhero.co.ke (per the Creating Account page).
- Link your Till, Paybill or bank account and register it as a payment channel (dashboard: Payment Channels → My Payment Channels, or
POST /api/v2/payment_channels). - Create an API key: API Keys → Add new API Key → Create API Key, then copy the Basic Authorization token.
- Make sure your service wallet has credit — PayHero charges per transaction from it.
Warning: KYC/business-document requirements for PayHero accounts are not described in the developer docs. Ask PayHero support before launch.
Sandbox and test credit
No sandbox base URL is documented — all calls go to https://backend.payhero.co.ke. The docs' Introduction offers up to KES 300 in test service credits to new developer accounts on request (via PayHero support on WhatsApp).
Test with KES 1–10 payments to your own phone, and avoid repeated cancelled prompts (see the abuse-protection rules in the errors section).
Credentials you need
- Basic Authorization token — copied from the dashboard's API Keys page; sent as
Authorization: Basic <token>. channel_id— the numeric id of your payment channel (not secret).- Optional
credential_id— only if you register your own Daraja credentials with PayHero.
Security: The Basic token gives full API access to your account. Keep it in server environment variables, rotate it regularly (the docs recommend this), and never put it in browser or mobile code.
Environment configuration
PAYHERO_CALLBACK_TOKEN is a random value you generate and append to the callback URL, because PayHero callbacks are not signed.
# PayHero — copy to .env
PAYHERO_BASIC_TOKEN=replace-with-basic-auth-token-from-dashboard
PAYHERO_CHANNEL_ID=replace-with-numeric-channel-id
# Public HTTPS URL for callbacks (tunnel such as ngrok in development)
PAYHERO_CALLBACK_URL=https://your-public-host.example.com/payhero/callback
# Long random value, e.g. from: openssl rand -hex 24
PAYHERO_CALLBACK_TOKEN=replace-with-random-hex
PORT=3000Authentication
PayHero uses HTTP Basic authentication with a ready-made token from the dashboard. Send it on every request: Authorization: Basic YOUR_AUTH_TOKEN plus Content-Type: application/json. There is no token exchange step.
A quick way to test the key is to list your payment channels, which also gives you the channel_id.
curl -s "https://backend.payhero.co.ke/api/v2/payment_channels?is_active=true" \
-H "Authorization: Basic $PAYHERO_BASIC_TOKEN" \
-H "Content-Type: application/json"
# => { "payment_channels": [ { "id": 26703032, "channel_type": "bank", "short_code": "522522", ... } ], "pagination": {...} }Backend: STK Push, callback, idempotent update
Same pattern as any STK integration: the server takes the amount from the order, sends the request with your own external_reference, stores the returned reference and CheckoutRequestID, and lets the callback move the order from PENDING to PAID/FAILED exactly once.
The example keeps orders in a Map; in production use a database with unique indexes on external_reference, PayHero reference and MpesaReceiptNumber.
import "dotenv/config";
import express from "express";
import crypto from "node:crypto";
const API = "https://backend.payhero.co.ke/api/v2";
const auth = { Authorization: "Basic " + process.env.PAYHERO_BASIC_TOKEN, "Content-Type": "application/json" };
const app = express();
app.use(express.json({ limit: "50kb" }));
// Demo store. Production: DB with unique(ref), unique(payheroRef), unique(receipt).
const orders = new Map([["INV-1001", { ref: "INV-1001", amountKes: 10, status: "PENDING" }]]);
app.post("/api/orders/:ref/pay", async (req, res) => {
const order = orders.get(req.params.ref);
if (!order || order.status !== "PENDING") return res.status(404).json({ error: "Order not payable" });
const phone = String(req.body.phone || "").trim();
if (!/^(?:0[17]\d{8}|254[17]\d{8})$/.test(phone)) return res.status(400).json({ error: "Invalid phone" });
const r = await fetch(API + "/payments", {
method: "POST",
headers: auth,
body: JSON.stringify({
amount: order.amountKes, // integer KES from YOUR record
phone_number: phone,
channel_id: Number(process.env.PAYHERO_CHANNEL_ID),
provider: "m-pesa",
external_reference: order.ref,
callback_url: process.env.PAYHERO_CALLBACK_URL + "/" + process.env.PAYHERO_CALLBACK_TOKEN,
}),
});
const out = await r.json().catch(() => ({}));
if (!r.ok || !out.success) return res.status(502).json({ error: out.error_message || "Could not start payment" });
order.payheroRef = out.reference; // e.g. "E8UWT7CLUW"; status starts as QUEUED
order.checkoutRequestId = out.CheckoutRequestID;
res.json({ status: "PROMPT_SENT" });
});
app.post("/payhero/callback/:token", (req, res) => {
const a = Buffer.from(req.params.token || "");
const b = Buffer.from(process.env.PAYHERO_CALLBACK_TOKEN || "");
if (!b.length || a.length !== b.length || !crypto.timingSafeEqual(a, b)) return res.sendStatus(404);
res.sendStatus(200);
const r = req.body?.response || {};
const order = orders.get(String(r.ExternalReference || ""));
if (!order || order.status !== "PENDING") return; // unknown or final: no-op
if (order.checkoutRequestId && r.CheckoutRequestID !== order.checkoutRequestId) return;
if (r.ResultCode !== 0) { order.status = "FAILED"; return; }
order.status = Number(r.Amount) === order.amountKes ? "PAID" : "REVIEW";
order.receipt = r.MpesaReceiptNumber;
});
app.get("/api/orders/:ref", (req, res) => {
const o = orders.get(req.params.ref);
return o ? res.json({ ref: o.ref, status: o.status }) : res.sendStatus(404);
});
app.listen(process.env.PORT || 3000);Security: Never let the browser choose the amount or mark the order paid. Only your callback handler or a server-side status check may change order status.
Frontend
The frontend only posts the order reference and phone number to your backend, tells the customer to check their phone, and polls your order-status endpoint until it reports PAID or FAILED (give up politely after about two minutes and keep the order pending). The React pattern in the Metatron M-Pesa Daraja guide applies unchanged — only the backend differs.
Initiating the STK Push
POST https://backend.payhero.co.ke/api/v2/payments with fields from the docs:
amount(integer, required),phone_number(string, required; docs example0787677676).channel_id(integer, required) — your payment channel id.provider(required) —m-pesa.external_reference(optional) — your own id, e.g.INV-009.customer_name(optional),callback_url(optional, but you need it),credential_id(optional).
Success is HTTP 201 with { "success": true, "status": "QUEUED", "reference": "...", "CheckoutRequestID": "ws_CO_..." }. QUEUED means the prompt was sent — not that the customer paid.
<?php
// pay.php — plain PHP 8 with ext-curl. Load env vars with your framework or vlucas/phpdotenv.
function payhero_request(string $method, string $path, ?array $body = null): array
{
$ch = curl_init('https://backend.payhero.co.ke/api/v2' . $path);
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => [
'Authorization: Basic ' . getenv('PAYHERO_BASIC_TOKEN'),
'Content-Type: application/json',
],
]);
if ($body !== null) {
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
}
$raw = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$json = json_decode((string) $raw, true) ?: [];
if ($code >= 400 || $raw === false) {
throw new RuntimeException($json['error_message'] ?? ('PayHero HTTP ' . $code));
}
return $json;
}
// $order comes from YOUR database — never from $_POST.
function start_payment(array $order, string $phone): array
{
$out = payhero_request('POST', '/payments', [
'amount' => (int) $order['amount_kes'],
'phone_number' => $phone,
'channel_id' => (int) getenv('PAYHERO_CHANNEL_ID'),
'provider' => 'm-pesa',
'external_reference' => $order['ref'],
'callback_url' => getenv('PAYHERO_CALLBACK_URL') . '/' . getenv('PAYHERO_CALLBACK_TOKEN'),
]);
// Save $out['reference'] and $out['CheckoutRequestID'] on the order before replying.
return $out;
}Confirming the payment
The callback body (per the docs) wraps the M-Pesa result in response: Amount, CheckoutRequestID, ExternalReference, MerchantRequestID, MpesaReceiptNumber, Phone, ResultCode (0 = success), ResultDesc and Status (e.g. Success, Failed), plus top-level status and forward_url.
Confirm only when ResultCode is 0, ExternalReference and CheckoutRequestID match a pending order, and Amount equals the order amount. Store MpesaReceiptNumber.
{
"forward_url": "",
"response": {
"Amount": 10,
"CheckoutRequestID": "ws_CO_14012024103543427709099876",
"ExternalReference": "INV-009",
"MerchantRequestID": "3202-70921557-1",
"MpesaReceiptNumber": "SAE3YULR0Y",
"Phone": "+254709099876",
"ResultCode": 0,
"ResultDesc": "The service request is processed successfully.",
"Status": "Success"
},
"status": true
}Callbacks (webhooks) and how to trust them
The docs do not describe any signature header on PayHero callbacks, so protect the endpoint yourself:
- Put a long random token in the callback path and compare it in constant time (as in the examples).
- Accept only callbacks whose
ExternalReferenceandCheckoutRequestIDmatch a pending order and whose amount matches. - For valuable orders, confirm with Get Transaction Status before fulfilment.
- Return HTTP 200 quickly and make processing idempotent.
<?php
// callback.php — route /payhero/callback/{token} here. Table orders(ref UNIQUE, amount_kes, status,
// checkout_request_id, receipt UNIQUE).
$token = basename(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
if (!hash_equals((string) getenv('PAYHERO_CALLBACK_TOKEN'), $token)) {
http_response_code(404);
exit;
}
$payload = json_decode(file_get_contents('php://input'), true) ?: [];
$r = $payload['response'] ?? [];
$pdo = new PDO(getenv('DB_DSN'), getenv('DB_USER'), getenv('DB_PASS'), [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$pdo->beginTransaction();
$stmt = $pdo->prepare('SELECT * FROM orders WHERE ref = ? FOR UPDATE');
$stmt->execute([(string) ($r['ExternalReference'] ?? '')]);
$order = $stmt->fetch(PDO::FETCH_ASSOC);
if ($order && $order['status'] === 'PENDING'
&& $order['checkout_request_id'] === ($r['CheckoutRequestID'] ?? null)) {
if ((int) ($r['ResultCode'] ?? -1) === 0) {
$status = ((int) $r['Amount'] === (int) $order['amount_kes']) ? 'PAID' : 'REVIEW';
$pdo->prepare('UPDATE orders SET status = ?, receipt = ? WHERE ref = ? AND status = ?')
->execute([$status, $r['MpesaReceiptNumber'] ?? null, $order['ref'], 'PENDING']);
} else {
$pdo->prepare('UPDATE orders SET status = ? WHERE ref = ? AND status = ?')
->execute(['FAILED', $order['ref'], 'PENDING']);
}
}
$pdo->commit();
http_response_code(200);
echo json_encode(['received' => true]);Security: Without a signature, the callback URL is the only secret protecting your orders. Keep it out of logs and client code, and confirm high-value payments with the status API.
Transaction status
GET https://backend.payhero.co.ke/api/v2/transaction-status?reference=... with your Basic token. reference is the reference returned by the payment request (the docs say you can also pass the M-Pesa code). The response has status — QUEUED (no callback received yet), SUCCESS or FAILED — plus provider_reference (the M-Pesa receipt), success and transaction_date.
Run it for orders still pending a few minutes after the prompt, and before shipping high-value orders.
export async function payheroStatus(reference) {
const url = "https://backend.payhero.co.ke/api/v2/transaction-status?reference=" + encodeURIComponent(reference);
const r = await fetch(url, { headers: { Authorization: "Basic " + process.env.PAYHERO_BASIC_TOKEN } });
if (!r.ok) throw new Error("PayHero status HTTP " + r.status);
const s = await r.json();
// status: QUEUED (not final) | SUCCESS | FAILED
return { final: s.status !== "QUEUED", paid: s.status === "SUCCESS", receipt: s.provider_reference || null };
}Refunds
The PayHero developer docs we reviewed do not document a refund or reversal API for STK payments. Handle refunds operationally: through your PayHero dashboard or support, through your Till/Paybill's M-Pesa business tools, or by a separate payout. Record refunds against the order in your own system.
Warning: Refund availability and process for PayHero could not be verified from public docs. Ask PayHero before promising automatic refunds.
Errors and limits
Error responses in the docs look like { "error_message": "Invalid request" } with HTTP 400. Callback ResultCode values come from M-Pesa (e.g. 0 success; cancelled or timed-out prompts are non-zero) — treat every non-zero code as not paid.
Abuse protection (from the STK Push page):
- More than 10 successive failed or cancelled STK requests to the same phone number blocks that number from your account's prompts for 24 hours.
- Over 50 failed requests in a sliding 6-hour window restricts the account for 4 hours; 500 → 24 hours; 1000 → 72 hours.
Warning: Careless retries in tests or a bot hitting your /pay endpoint can lock your whole account. Rate-limit prompts per phone and per user.
Going to production
- Use a stable HTTPS callback URL on your domain and a fresh, rotated API key.
- Keep the service wallet funded and monitor its balance (
GET /api/v2/wallets). - Persist orders with unique references; make updates conditional on
PENDING. - Add a reconciliation job using the transaction-status endpoint.
- Rate-limit prompt initiation to stay well below the abuse thresholds.
Security checklist
- Basic token only on the server, in environment variables; rotate regularly.
- Amount from your database; phone number validated.
- Callback URL protected by a secret path token; payload matched to a pending order; amount checked.
- Idempotent updates and unique receipt numbers.
- Never treat a client-side message ("I've paid") or the 201
QUEUEDresponse as payment.
Testing
- Request test credits from PayHero, set a small order amount (KES 1–10), and pay to your own phone.
- Cancel one prompt to see a failed callback — but not ten in a row (abuse protection).
- Replay a captured callback with curl to confirm the duplicate is a no-op.
- Stop your server during a payment and confirm the status job completes the order.
curl -s -X POST "http://localhost:3000/payhero/callback/$PAYHERO_CALLBACK_TOKEN" \
-H "Content-Type: application/json" \
-d '{"forward_url":"","status":true,"response":{"Amount":10,"CheckoutRequestID":"ws_CO_REPLACE_ME",
"ExternalReference":"INV-1001","MerchantRequestID":"test","MpesaReceiptNumber":"TEST123456",
"Phone":"+254700000000","ResultCode":0,"ResultDesc":"ok","Status":"Success"}}'Common mistakes
- Wrong
channel_id— using your Till/Paybill number instead of the PayHero channelid. - Sending
channel_idas a string oramountwith decimals — both are integers in the docs. - Treating
QUEUEDas paid. - Empty service wallet — requests fail when there is no credit for fees.
- Retry loops that trigger the abuse-protection blocks.
- Callback URL on localhost or plain HTTP.
Troubleshooting
- 401/403: the Basic token is wrong, revoked, or has a stray
Basicprefix twice. - 400
Invalid request: check field names (phone_number,channel_id,provider: "m-pesa") and types. - Prompt never arrives: phone off or not on M-Pesa, number blocked by abuse protection, or an earlier prompt still open.
- No callback: confirm
callback_urlis public HTTPS and not blocked by CSRF middleware; use the transaction-status endpoint meanwhile. - Callback order not found: you did not send
external_reference, or you saved the order after the callback arrived.
Further reading
- Get payment channels and register-payment-channel in the same docs.
- PayHero's docs list community/official packages: a Node wrapper and the PHP package
payherokenya/payhero-phpon Packagist. - Related Metatron guide: M-Pesa Daraja STK Push, to integrate directly with Safaricom.
Official documentation
Checked 2026-11-25. The docs site renders in the browser; if a deep link opens the home page, use its navigation.
Official documentation
Sources
More payment guides
- PayHero Kenya provider profile
- Adyen Checkout: Sessions flow, Drop-in and HMAC webhooks
- Airtel Money Collections: USSD Push with the Airtel Africa Open API
- Flutterwave Checkout (Standard): hosted payment page, webhooks, verify and refunds
- M-Pesa Daraja STK Push (Lipa na M-Pesa Online)
- MTN MoMo Collections: Request to Pay with the MoMo Open API
- Mercado Pago Checkout Pro: preferences, back URLs and signed webhooks
- Mollie Payments API: hosted checkout, webhooks and refunds
- PayPal Checkout with Orders v2, verified webhooks and refunds