Notes · Payments

M-Pesa STK Push with the Daraja API: a practical guide

How to take M-Pesa payments in your web app with the Daraja STK Push API: tokens, the password, callbacks, failures and the checks we do in production.

Published
Read
9 min

STK Push (Lipa na M-Pesa Online) is the prompt that appears on a customer’s phone asking for their M-Pesa PIN. It’s the smoothest way to take money in a Kenyan web app: no typing Paybill numbers, no copying confirmation codes. It’s also easy to get subtly wrong. This is how we do it, and what tends to go wrong.

What you need first

  • A Paybill or Buy Goods (Till) number for the business
  • An app on the Safaricom Daraja portal for the consumer key and secret
  • The Lipa na M-Pesa Online passkey for your shortcode (Safaricom issues it when you go live; the sandbox has a public test one)
  • A public HTTPS URL for Safaricom to send the result to

The flow, end to end

  1. Your server gets an OAuth access token from Daraja
  2. Your server sends the STK Push request: amount, phone, shortcode, a password and your callback URL
  3. Daraja replies straight away with a CheckoutRequestID. Nothing has been paid yet
  4. The customer sees the prompt and enters their PIN (or cancels, or ignores it)
  5. Daraja POSTs the result to your callback URL
  6. You mark the order paid, using the CheckoutRequestID to find it

1. Get a token

ts
const BASE = process.env.MPESA_ENV === 'live'
  ? 'https://api.safaricom.co.ke'
  : 'https://sandbox.safaricom.co.ke'

async function token(): Promise<string> {
  const basic = Buffer.from(`${process.env.MPESA_KEY}:${process.env.MPESA_SECRET}`).toString('base64')
  const res = await fetch(`${BASE}/oauth/v1/generate?grant_type=client_credentials`, {
    headers: { Authorization: `Basic ${basic}` },
  })
  if (!res.ok) throw new Error(`Daraja token: ${res.status}`)
  const { access_token } = await res.json()
  return access_token // valid for about an hour: cache it
}

2. Send the push

The password is the shortcode, the passkey and a timestamp (YYYYMMDDHHmmss, Nairobi time) joined together and base64-encoded. The same timestamp goes in the request body.

ts
function stamp(d = new Date()) {
  // Daraja expects East Africa Time
  const eat = new Date(d.getTime() + 3 * 60 * 60 * 1000)
  return eat.toISOString().replace(/[-:T]/g, '').slice(0, 14)
}

export async function stkPush(o: { phone: string; amount: number; ref: string; orderId: string }) {
  const shortcode = process.env.MPESA_SHORTCODE!
  const timestamp = stamp()
  const password = Buffer.from(shortcode + process.env.MPESA_PASSKEY + timestamp).toString('base64')

  const res = await fetch(`${BASE}/mpesa/stkpush/v1/processrequest`, {
    method: 'POST',
    headers: { Authorization: `Bearer ${await token()}`, 'Content-Type': 'application/json' },
    body: JSON.stringify({
      BusinessShortCode: shortcode,
      Password: password,
      Timestamp: timestamp,
      TransactionType: 'CustomerPayBillOnline', // 'CustomerBuyGoodsOnline' for a Till
      Amount: Math.round(o.amount),             // whole shillings only
      PartyA: o.phone,                          // 2547XXXXXXXX
      PartyB: shortcode,                        // the Till number for Buy Goods
      PhoneNumber: o.phone,
      CallBackURL: `${process.env.PUBLIC_URL}/api/mpesa/callback/${process.env.MPESA_CALLBACK_SECRET}`,
      AccountReference: o.ref.slice(0, 12),
      TransactionDesc: 'Payment',
    }),
  })
  const data = await res.json()
  if (data.ResponseCode !== '0') throw new Error(data.errorMessage ?? data.ResponseDescription)
  // save this BEFORE you return: the callback can arrive very quickly
  await db.payment.update({ where: { orderId: o.orderId }, data: { checkoutId: data.CheckoutRequestID, status: 'pending' } })
  return data.CheckoutRequestID as string
}

3. Handle the callback

Daraja sends a JSON body with Body.stkCallback. A ResultCode of 0 means paid; anything else means it didn’t happen. The useful values (amount, M-Pesa receipt number, phone) are in CallbackMetadata.Item as name/value pairs, and only on success.

ts
export async function POST(req: Request) {
  const { Body } = await req.json()
  const cb = Body.stkCallback
  const payment = await db.payment.findUnique({ where: { checkoutId: cb.CheckoutRequestID } })
  if (!payment || payment.status === 'paid') return Response.json({ ok: true }) // unknown or already done

  if (cb.ResultCode !== 0) {
    await db.payment.update({ where: { id: payment.id }, data: { status: 'failed', reason: cb.ResultDesc } })
    return Response.json({ ok: true })
  }

  const item = (name: string) => cb.CallbackMetadata.Item.find((i: any) => i.Name === name)?.Value
  if (Number(item('Amount')) !== payment.amount) {
    await db.payment.update({ where: { id: payment.id }, data: { status: 'review' } }) // never trust, check
    return Response.json({ ok: true })
  }
  await db.payment.update({
    where: { id: payment.id },
    data: { status: 'paid', receipt: item('MpesaReceiptNumber'), paidFrom: String(item('PhoneNumber')) },
  })
  return Response.json({ ok: true })
}

What goes wrong in production

  • The callback never comes. It happens. Use the STK Push Query API (/mpesa/stkpushquery/v1/query) to ask for the result of anything still pending after a minute or two, and run a sweep for stragglers.
  • The customer cancels or doesn’t answer. Common result codes are 1032 (cancelled by the user) and 1037 (the phone couldn’t be reached). Tell the customer plainly and offer to send the prompt again.
  • Insufficient funds or a wrong PIN come back as their own codes. Show the ResultDesc in words a customer understands, not the raw code.
  • Double-tapping Pay sends two prompts. Disable the button and refuse a new push while one is pending for the same order.
  • Anyone can POST to your callback. Daraja’s callback isn’t signed. Put a secret in the URL path, accept only known CheckoutRequestIDs, check the amount, and for high-value payments confirm with the query API before releasing anything.
  • Going live means a different base URL, your real shortcode and passkey, and callback URLs Safaricom can reach. Test the whole path with a real KSh 1 payment before you announce anything.

Beyond STK Push

STK Push is for payments you start. When customers pay your Paybill on their own (school fees are the classic case), you register C2B URLs instead and match each payment to an account. We cover that in matching school fee payments automatically.