daraja-openapi

Quick start

Send an M-PESA prompt to a phone and confirm the payment, in about five minutes.

Before you start

You need a Daraja sandbox app. Create one on the Daraja portal, then note its consumer key and consumer secret. The sandbox uses the public test shortcode 174379 and its passkey, both shown on the portal's test credentials page. See credentials and environments for what each value is.

Keep these in environment variables, never in your code.

Install

npm install @bytegigs/daraja

Send the prompt

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

const daraja = new Daraja({
  consumerKey: process.env.DARAJA_CONSUMER_KEY,
  consumerSecret: process.env.DARAJA_CONSUMER_SECRET,
  environment: "sandbox",
  shortCode: "174379",
  passkey: process.env.DARAJA_PASSKEY,
});

const push = await daraja.stkPush({
  amount: 150,
  phone: "0712 345 678",
  callbackUrl: "https://your-app.example/daraja/callback",
  accountReference: "INV-1001",
  description: "Invoice 1001",
});

Phone numbers can be written any common Kenyan way: 0712 345 678, +254 712 345 678 and 712345678 all become 254712345678. The client checks every field before sending, so a description over 13 characters fails on your server, not at Daraja.

Confirm the payment

The customer answers on their phone, and Daraja POSTs the result to your callback URL. Callbacks aren't signed, so confirm before you deliver anything:

const result = await daraja.waitForStkResult({ checkoutRequestId: push.CheckoutRequestID });
if (result.state === "paid") await markInvoicePaid("INV-1001");
else if (result.state === "failed") console.log(result.meaning); // "The customer cancelled the payment"

waitForStkResult waits a few seconds before its first query, treats "still processing" as waiting, and backs off when Daraja rate-limits. In a web request, prefer the callback and confirm there.

Next

Try every failure case without the sandbox using the mock, then read handling callbacks before you go live.

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.