Guides
Payouts and the initiator
B2C, B2B, reversal, transaction status and account balance act as your API initiator: a user on your M-PESA organisation account allowed to call these APIs.
Give the client your initiator
Daraja wants the initiator password encrypted with Safaricom's public certificate (RSA with PKCS #1 v1.5 padding), sent as SecurityCredential. The SDKs do the encryption, so the password never leaves your server.
import { readFileSync } from "node:fs";
const daraja = new Daraja({
consumerKey, consumerSecret, environment: "sandbox", shortCode: "600996",
initiatorName: "testapi",
initiatorPassword: process.env.DARAJA_INITIATOR_PASSWORD,
certificate: readFileSync("SandboxCertificate.cer"),
});
daraja = Daraja(key, secret, short_code="600996",
initiator_name="testapi",
initiator_password=os.environ["DARAJA_INITIATOR_PASSWORD"],
certificate=open("SandboxCertificate.cer", "rb").read())
$daraja = new Daraja($key, $secret, shortCode: '600996',
initiatorName: 'testapi',
initiatorPassword: getenv('DARAJA_INITIATOR_PASSWORD'),
certificate: file_get_contents('SandboxCertificate.cer'),
);
The sandbox and production certificates differ. Python needs pip install "bytegigs-daraja[credential]" for the encryption. In Swift, compute the credential once with openssl and pass it in; see the Swift SDK.
Pay a customer
await daraja.b2cPayment({
originatorConversationId: "refund-order-77",
amount: 150,
phone: "0708 374 149",
remarks: "Refund order 77",
resultUrl: "https://your-app.example/daraja/result",
timeoutUrl: "https://your-app.example/daraja/timeout",
});
originatorConversationId is yours. Store it before you call, and reuse it if you retry, so a retry can be matched to the first attempt and you never pay twice. The SDKs never retry a payout on their own.
Read the result
These APIs answer twice. The response only says Daraja queued the request. The outcome arrives later at resultUrl:
import { parseAsyncResult } from "@bytegigs/daraja";
app.post("/daraja/result", (req, res) => {
res.sendStatus(200);
const result = parseAsyncResult(req.body);
if (result?.ok) markRefunded(result.originatorConversationId, result.transactionId);
});
result.params holds the details, such as TransactionAmount and TransactionReceipt. For account balance, parseAccountBalance turns Daraja's Name|KES|Available|... string into numbers.
When the result times out
A call to timeoutUrl means M-PESA couldn't process the request in time, and the outcome is unknown. Don't simply pay again: look the payment up with transaction status using your originatorConversationId first.