webstudios
← Back to all articles
M-Pesa Engineeringβ€’8 min readβ€’Published 2026-05-10

How to Integrate Safaricom Daraja M-Pesa STK Push into Your Web Application (2026 Developer Blueprint)

A complete technical guide to implementing automated Lipa na M-Pesa STK Push in web applications. Architecture, OAuth token generation, callback webhooks, and production security.

How to Integrate Safaricom Daraja M-Pesa STK Push into Your Web Application (2026 Developer Blueprint)

Over 85% of commercial transactions in Kenya flow through M-Pesa. Yet, countless online shops and service platforms still force customers to manually open their SIM toolkit, enter a Till or Paybill number, copy the transaction code, and paste it back into a form. In 2026, automating your payment flow via Safaricom's Daraja 2.0 Lipa na M-Pesa Online (STK Push) API is the single most effective way to eliminate checkout friction, decrease cart abandonment, and increase revenue.

1. The Anatomy of an M-Pesa STK Push Flow

Unlike manual Paybill transfers where the buyer drives the transaction, an STK Push (ProcessRequest) inverts the control. When the customer enters their Kenyan phone number (e.g., 2547XXXXXXXX) and hits 'Complete Order', your web application's backend server sends an authenticated JSON payload to Safaricom's Daraja gateway.

Within 1 to 2 seconds, a secure pop-up prompt appears natively on the customer's phone displaying your business name, amount, and an M-Pesa PIN input box. Once the user enters their PIN, Safaricom validates the balance and sends an asynchronous HTTP POST webhook to your server's CallBackURL with the MpesaReceiptNumber.

Key TakeawayNever initiate an STK push directly from client-side browser JavaScript. Your Safaricom Consumer Secret and Passkey must remain strictly protected on your backend server or serverless Edge Function.

2. Generating the OAuth Access Token and Base64 Password

Every call to Safaricom's Daraja endpoint requires an ephemeral Bearer token obtained by encoding your Consumer Key and Consumer Secret with HTTP Basic authentication.

Furthermore, each STK push payload requires a dynamic password created by concatenating your Business ShortCode, Passkey, and current timestamp in the format YYYYMMDDHHmmss, then converting the string to Base64.

// Node.js / TypeScript Example for Daraja Password Generation
const shortCode = process.env.DARAJA_SHORTCODE; // e.g. 174379 (sandbox) or live Till
const passKey = process.env.DARAJA_PASSKEY;
const timestamp = new Date().toISOString().replace(/[^0-9]/g, '').slice(0, 14);

// Generate Base64 Password
const password = Buffer.from(`${shortCode}${passKey}${timestamp}`).toString('base64');

3. Handling Asynchronous Callback Webhooks Safely

When the customer completes or cancels the PIN prompt, Safaricom sends a JSON payload to your public HTTPS CallBackURL. Your server must immediately acknowledge the webhook with an HTTP status code 200 OK. If your endpoint times out or returns an error, Safaricom will retry multiple times, potentially creating duplicate notification logs.

Extract the ResultCode: a code of 0 indicates successful payment. You can then parse the CallbackMetadata array to retrieve the MpesaReceiptNumber, Amount, and TransactionDate to update your order in your database and dispatch an instant confirmation SMS or WhatsApp message.

  • Verify the CheckoutRequestID against your pending orders database table.
  • Always return res.status(200).json({ ResultCode: 0, ResultDesc: 'Accepted' }) immediately.
  • Never mark an order as paid until the ResultCode === 0 callback is verified on the backend.
  • Cache your OAuth access tokens for ~3,500 seconds to avoid hitting Safaricom rate limits.

4. Why Custom Engineered Checkout Beats Third-Party Redirects

Many agencies install slow third-party redirect plugins that force customers away from your website onto an external gateway. Every extra redirect reduces mobile conversion rates by 15% to 30%.

At Web Studios, we hand-code direct Daraja STK Push integrations natively into your web application with zero third-party commissions, instant order dispatch, and sub-second transaction validation.

Ready to build a website or booking app that dominates?

Tell us about your business goals and get an exact quote with zero hidden fees.