For developers building payment flows in Kenya, M-Pesa STK Push (Lipa na M-Pesa Online) is the gold standard for mobile checkout. Instead of asking customers to manually navigate their SIM Toolkit, copy a Paybill number, and type an account reference, STK Push beams a payment prompt straight to their screen. All they have to do is enter their PIN.
When implementing STK Push in your application, you face an early architectural choice: integrate directly with Safaricom’s Daraja API, or route payments through an orchestration layer like PayHero.
Both get the money into your account, but the developer experience, setup time, and fee structures are vastly different. Let’s break down how both integrations work under the hood; complete with working Node.js examples—so you can pick the right tool for your stack.
The Two Paths at a Glance
Before writing a single line of code, it helps to understand what each platform actually is.
Safaricom Daraja is the official, direct-to-source REST API provided by Safaricom. Integrating with Daraja means talking directly to the telecom infrastructure with zero middlemen.
PayHero is a payment aggregator and orchestration platform built on top of mobile money rails. It connects to your existing M-Pesa Paybill, Buy Goods Till, or bank settlement account and wraps the underlying payment APIs into a cleaner, unified interface.
| Dimension | Safaricom Daraja (Direct) | PayHero (Orchestrator) |
| Go-Live Speed | 24–48+ working hours (requires M-Pesa Org Portal approval and manual Go-Live checks). | Minutes (link an existing Till/Paybill and generate keys immediately). |
| Authentication | Two-step OAuth 2.0 (fetch a short-lived Bearer token before transacting). | Single-step HTTP Basic Auth (static Base64 username:password). |
| Payload Complexity | High (requires real-time YYYYMMDDHHmmss timestamps and Base64 passkey hashing). | Low (standard JSON with channel_id, amount, and phone_number). |
| Pricing Model | Lowest cost—you only pay standard Safaricom Paybill/Till tariffs. | Requires topping up a PayHero service wallet to cover platform transaction fees alongside your underlying settlement tariff. |
| Best For | High-volume enterprises, fintechs, and teams avoiding third-party dependencies. | Startups, MVPs, SaaS products, and developers prioritizing speed to market. |
Option 1: Integrating Directly with Safaricom Daraja
Going direct with Daraja gives you full control and eliminates intermediary fees, at the cost of a slightly more ceremonial API handshake.
How It Works
Every STK Push request on Daraja requires two network calls and some cryptographic string formatting:
- Authenticate: Exchange your
Consumer KeyandConsumer Secretfor an OAuth 2.0 Bearer token. - Generate a Password: Concatenate your
BusinessShortCode, yourPasskey, and a current timestamp (YYYYMMDDHHmmss), then Base64-encode the resulting string. - Initiate the Prompt: Send a
POSTrequest to/mpesa/stkpush/v1/processrequestwith the Bearer token and your generated password. - Listen for the Callback: Safaricom processes the PIN entry asynchronously and sends the final receipt payload to your HTTPS
CallBackURL.
Node.js Implementation (Daraja)
JavaScript
const express = require("express");
const app = express();
app.use(express.json());
const CONSUMER_KEY = process.env.DARAJA_CONSUMER_KEY;
const CONSUMER_SECRET = process.env.DARAJA_CONSUMER_SECRET;
const SHORTCODE = "174379"; // Daraja Sandbox Shortcode
const PASSKEY = "bfb279f9aa9bdbcf158e97dd71a467cd2e0c893059b10f78e6b72ada1ed2c919";
const BASE_URL = "https://sandbox.safaricom.co.ke"; // Switch to https://api.safaricom.co.ke in production
// Step 1: Fetch OAuth 2.0 Access Token
async function getDarajaToken() {
const credentials = Buffer.from(`${CONSUMER_KEY}:${CONSUMER_SECRET}`).toString("base64");
const response = await fetch(`${BASE_URL}/oauth/v1/generate?grant_type=client_credentials`, {
headers: { Authorization: `Basic ${credentials}` },
});
const data = await response.json();
return data.access_token;
}
// Step 2: Trigger the STK Push Prompt
app.post("/api/daraja/pay", async (req, res) => {
try {
const { phone, amount } = req.body; // Expected format: 2547XXXXXXXX
const token = await getDarajaToken();
// Format timestamp as YYYYMMDDHHmmss
const timestamp = new Date().toISOString().replace(/[^0-9]/g, "").slice(0, 14);
const password = Buffer.from(`${SHORTCODE}${PASSKEY}${timestamp}`).toString("base64");
const payload = {
BusinessShortCode: SHORTCODE,
Password: password,
Timestamp: timestamp,
TransactionType: "CustomerPayBillOnline", // Use "CustomerBuyGoodsOnline" for Till numbers
Amount: Math.round(amount),
PartyA: phone,
PartyB: SHORTCODE,
PhoneNumber: phone,
CallBackURL: "https://your-domain.com/api/daraja/callback",
AccountReference: "INV-2026",
TransactionDesc: "Checkout Payment",
};
const stkResponse = await fetch(`${BASE_URL}/mpesa/stkpush/v1/processrequest`, {
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
});
const result = await stkResponse.json();
res.json(result);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// Step 3: Receive Asynchronous Payment Confirmation
app.post("/api/daraja/callback", (req, res) => {
const callbackData = req.body?.Body?.stkCallback;
if (callbackData?.ResultCode === 0) {
// ResultCode 0 confirms the user entered their PIN and paid
console.log("Payment Confirmed:", callbackData.CallbackMetadata);
} else {
console.log("Payment Cancelled or Failed:", callbackData?.ResultDesc);
}
// Always acknowledge receipt with HTTP 200
res.status(200).json({ ResultCode: 0, ResultDesc: "Accepted" });
});
app.listen(3000, () => console.log("Daraja server listening on port 3000"));
Watch out for: Daraja strictly rejects non-HTTPS callback URLs and unformatted phone numbers (e.g., 0712... instead of 254712...). During local development, you will need a tunneling tool like ngrok or Cloudflare Tunnel to expose your local server over HTTPS.
Option 2: Integrating via PayHero
If you already have a registered Till or Paybill—or even a bank Paybill—and want to skip token management, timestamp hashing, and Daraja’s Go-Live approval queue, PayHero streamlines the entire flow into a single HTTP request.
How It Works
- Link a Channel: Inside your PayHero dashboard, connect your M-Pesa Paybill, Till, or bank settlement account to get a numeric
channel_id. - Trigger the Prompt: Send a single
POSTrequest to[https://backend.payhero.co.ke/api/v2/payments](https://backend.payhero.co.ke/api/v2/payments)using HTTP Basic Auth. PayHero handles token generation, passkey encoding, and phone number normalization (07...or2547...) behind the scenes. - Listen for the Callback: PayHero forwards a clean JSON webhook to your
callback_urlonce the transaction settles.
Node.js Implementation (PayHero)
JavaScript
const express = require("express");
const app = express();
app.use(express.json());
const API_USERNAME = process.env.PAYHERO_USERNAME;
const API_PASSWORD = process.env.PAYHERO_PASSWORD;
const CHANNEL_ID = 133; // Your linked Payment Channel ID from PayHero
const BASIC_AUTH = Buffer.from(`${API_USERNAME}:${API_PASSWORD}`).toString("base64");
// Step 1: Trigger STK Push in a Single Call
app.post("/api/payhero/pay", async (req, res) => {
try {
const { phone, amount, reference } = req.body; // Accepts 07XXXXXXXX or 2547XXXXXXXX
const payload = {
amount: Math.round(amount),
phone_number: phone,
channel_id: CHANNEL_ID,
provider: "m-pesa",
external_reference: reference || "INV-2026",
callback_url: "https://your-domain.com/api/payhero/callback",
};
const response = await fetch("https://backend.payhero.co.ke/api/v2/payments", {
method: "POST",
headers: {
Authorization: `Basic ${BASIC_AUTH}`,
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
});
const result = await response.json();
res.json(result);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// Step 2: Receive Payment Webhook
app.post("/api/payhero/callback", (req, res) => {
const { response } = req.body;
if (response?.Status === "Success") {
console.log(`Order ${response.ExternalReference} paid! Receipt: ${response.MpesaReceiptNumber}`);
} else {
console.log("Transaction unsuccessful:", response);
}
res.status(200).json({ status: "ok" });
});
app.listen(3000, () => console.log("PayHero server listening on port 3000"));
3 Rules for Production M-Pesa Integrations
Whichever route you choose, mobile money networks behave asynchronously. Following three non-negotiable engineering practices will save you from lost orders and accounting headaches:
- Never fulfill an order on the initial API response. When your
POSTrequest returns200 OK, it only means the prompt was queued to appear on the customer’s phone—not that they paid. The user might still cancel the prompt, mistype their PIN, or have insufficient funds. Only unlock goods or services inside your callback handler (or after polling a transaction status endpoint). - Make your callback handler idempotent. Mobile network retries can occasionally fire the same webhook twice. Always record the unique transaction identifier (
CheckoutRequestIDon Daraja, orExternalReference/MpesaReceiptNumberon PayHero) in your database and check if it has already been processed before crediting a user’s balance. - Round amounts to whole integers. M-Pesa STK Push does not accept decimal cents. Passing
199.50will trigger a bad-request rejection on Daraja. Always useMath.round()before constructing your payload.
Which One Should You Choose?
- Choose Safaricom Daraja if you are processing high transaction volumes where every shilling of margin counts, if you have an existing M-Pesa Business Administrator ready to approve your Go-Live application, or if your compliance team mandates zero third-party payment intermediaries.
- Choose PayHero if you want to ship a working M-Pesa checkout today, prefer clean REST conventions over OAuth token caching and timestamp hashing, or want a ready-made dashboard to track settlements across multiple Tills, Paybills, and bank accounts.