daraja-openapi

Handling callbacks

Daraja tells you the outcome of a payment by POSTing to a URL you give it. Those callbacks are not signed, so treat each one as a notification, not as proof.

Answer fast, then confirm

Reply HTTP 200 straight away, then confirm the payment with Daraja before you deliver anything. Anyone who discovers your callback URL can POST a fake "paid" body to it.

import { parseStkCallback } from "@bytegigs/daraja";

app.post("/daraja/callback", async (req, res) => {
  res.sendStatus(200); // answer Daraja first
  const result = parseStkCallback(req.body);
  if (!result) return; // not an STK Push result: ignore it
  // result.paid, result.amount, result.receipt, result.meaning ("The customer cancelled the payment")
  try {
    const confirmed = await daraja.stkQuery({ checkoutRequestId: result.checkoutRequestId });
    if (confirmed.state === "paid") await markOrderPaid(result.checkoutRequestId, result.receipt);
  } catch (error) {
    // A 429 or "still processing": leave the order open and check again later.
    // The response is already sent, so nothing may escape here: in Node it would crash the process.
    console.warn("payment not confirmed yet:", error.message);
  }
});

What a callback contains

A paid STK Push callback carries the amount, the M-PESA receipt, the phone number and the time. A failed one carries a result code instead. The SDKs turn the code into a plain meaning you can show the customer:

CodeMeaning
0Paid
1The customer's M-PESA balance was too low
1032The customer cancelled the payment
1037The customer's phone could not be reached, or they did not respond
2001The customer entered the wrong PIN
1019The payment prompt expired
1001The customer already has a payment in progress

When the callback never comes

Callbacks go missing: a timeout on your server, a deploy at the wrong moment, a network blip. If a payment has had no callback after a minute or two, query it with STK Push Query. waitForStkResult does this for you and also recovers payments whose callback never arrived.

Don't query straight after sending the push. Daraja answers HTTP 429 to a query sent a few seconds after the push. See errors and rate limits.

Other callbacks

View the source of this page

Built by ByteGigs Labs. Apache 2.0. M-PESA, Daraja and Safaricom are trademarks of Safaricom PLC; this project is independent and not endorsed by Safaricom.