M-Pesa STK Push Integration: The Complete Developer Guide
If you are asking "How do I integrate M-Pesa STK Push into my website?", here is the direct technical answer.
You need to use the Safaricom Daraja API. The flow is: (1) Generate an OAuth Access Token, (2) Send an STK Push Request to Safaricom, and (3) Receive the payment confirmation via a Webhook (Callback URL).
Here is the exact code to execute an M-Pesa STK Push using Node.js (which you can drop into your Next.js API routes).
1. The STK Push Code Snippet (Node.js)
Before executing the push, ensure you have generated your access_token using your Consumer Key and Secret from the Daraja portal.
// Example: Next.js API Route (app/api/mpesa/stkpush/route.ts)
export async function POST(request: Request) {
const { phone, amount } = await request.json();
const shortCode = process.env.MPESA_SHORTCODE;
const passkey = process.env.MPESA_PASSKEY;
// 1. Generate Timestamp
const timestamp = new Date().toISOString().replace(/[^0-9]/g, '').slice(0, 14);
// 2. Generate Password (Base64 Encode: Shortcode + Passkey + Timestamp)
const password = Buffer.from(`${shortCode}${passkey}${timestamp}`).toString('base64');
// 3. Make the STK Push Request to Daraja
const response = await fetch('https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.MPESA_ACCESS_TOKEN}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
BusinessShortCode: shortCode,
Password: password,
Timestamp: timestamp,
TransactionType: 'CustomerPayBillOnline',
Amount: amount,
PartyA: phone, // Customer phone number
PartyB: shortCode,
PhoneNumber: phone,
CallBackURL: 'https://yourdomain.com/api/mpesa/callback',
AccountReference: 'Order123',
TransactionDesc: 'Payment for Order 123'
})
});
const data = await response.json();
return Response.json(data);
}
2. Handling the Safaricom Callback
Once the customer enters their M-Pesa PIN, Safaricom sends a POST request to your CallBackURL. You must capture this to update the order status in your database.
// Example: Next.js API Route (app/api/mpesa/callback/route.ts)
export async function POST(request: Request) {
const data = await request.json();
const callbackData = data.Body.stkCallback;
if (callbackData.ResultCode === 0) {
// Payment Successful
const metadata = callbackData.CallbackMetadata.Item;
const amountPaid = metadata.find((m) => m.Name === 'Amount').Value;
const mpesaReceiptNumber = metadata.find((m) => m.Name === 'MpesaReceiptNumber').Value;
const phoneNumber = metadata.find((m) => m.Name === 'PhoneNumber').Value;
// TODO: Update database (e.g., mark order as PAID)
console.log(`Received KES ${amountPaid} from ${phoneNumber}. Receipt: ${mpesaReceiptNumber}`);
} else {
// Payment Failed (e.g., Insufficient funds, User cancelled)
console.error(`Payment failed: ${callbackData.ResultDesc}`);
}
// Acknowledge receipt to Safaricom
return Response.json({ ResultCode: 0, ResultDesc: "Accepted" });
}
Why M-Pesa STK Push is the Standard
For years, businesses relied on manual Paybill and Till Number transactions where customers had to manually type amounts and send screenshot proofs via WhatsApp.
With STK Push (Lipa Na M-Pesa Online):
- Zero Math Errors: The exact amount is hardcoded into the pop-up prompt.
- Instant Verification: The Daraja API callback updates your system the millisecond the payment clears.
- Professionalism: An automated prompt builds massive trust compared to "send me a screenshot."
Security Best Practices
- Never expose your Consumer Secret in your frontend code. Always execute Daraja calls securely from a backend server (
.envfiles). - Whitelist Safaricom IPs on your server firewall if your callbacks are failing to reach you.
- Use HTTPS. Safaricom's Daraja API will not send callbacks to standard
http://URLs.
We Can Build It For You
Integrating the Daraja API requires back-end web development expertise, secure token handling, and robust database architecture. If you are not a developer, this is not a DIY project.
At DevLink Technologies, we specialize in building custom e-commerce systems and business tools with flawless M-Pesa STK integration out of the box. Contact us today to automate your business payments.
Ready to build a system that works?
Stop losing sales to manual processes. DevLink Technologies builds web systems that automate your operations and scale your Kenyan business.