api

API

The documentation of all available functions and types.

STK Push

The library exports a function stkPushRequest that takes an object as a parameter. the type of the object is STKPushRequestParam. You can use the type to provide you with intellisense as you build out the object.

Here is an example of how you can make a request in node .

import { stkPushRequest , STKPushRequestParam} from "daraja-kit"; const myReqObj:STKPushRequestParam = { phoneNumber: "254719428019", amount: "100", callbackURL: "https://example.com/api/stk-push-callback", transactionDesc: "Payment for your service", accountReference: "user123@example.com", } const makeSTKPushRequest = async () => { try { const response = await stkPushRequest(myReqObj); console.log("STK Push Request Successful:", response); } catch (error) { console.error("Error:", error.message); } }; makeSTKPushRequest();

The account reference param i have found to be required when using the api. If you don`t have an account reference or you don`t need it you might just include a random non-empty string.

Handling stk push callbacks

Daraja API sends the result of the STKPush Request after processing to the callback url you sent when making the request.

Personal opinion.

I don`t like the way we send a callback url each time we make STK push requests, same thing with validation and confirmation urls, i feel this is something that i should just set on some dashboard somewhere and it just works. The way sanity and other platforms handle that. I really hope the engineers at safaricom work on that.

Anyways the library exports two types STKPushSuccessfulCallbackBody and STKPushErrorCallbackBody that you can use to when processing daraja responses. Here is an example of how you can use the types in NextJS.

import { STKPushErrorCallbackBody, STKPushSuccessfulCallbackBody} from "daraja-kit"; import { NextRequest, NextResponse } from "next/server"; const POST = async (req: NextRequest, res: NextResponse) => { const receivedResponse:STKPushSuccessfulCallbackBody | STKPushErrorCallbackBody = req.body; let successObj: STKPushSuccessfulCallbackBody; let errorObj: STKPushErrorCallbackBody; if (receivedResponse.Body.stkCallback.ResultCode === 0) { successObj = receivedResponse; //do something } else { errorObj = receivedResponse; //do something } //the below response doesn't matter but nextjs requires you to return something from Api route handlers return NextResponse.json({ received: true }); };

QR Code

The library exports three QRCode helpers. Lets start with a NextJS example. You can import QRCodeDisplay from the library to display a QRcode on your website that people will scan to pay. Example

import React from "react"; import { QRCodeDisplay } from "daraja-kit"; import { ScannableQrParams } from "daraja-kit"; import { BUSINESS_SHORT_CODE } from "daraja-kit"; export const QRCodeExample = () => { const qrCodeParams: ScannableQrParams = { Amount: 100, MerchantName: "Daraja Kit docs", RefNo: "REF100", Size: "100", TrxCode: "PB", }; return ( <> <div className="w-[100px] aspect-square mt-5 mx-auto"> <QRCodeDisplay scannableQRParams={qrCodeParams} /> </div> </> ); };
Now if you use vanilla react i.e create-react-app or vite maybe you can import QRCodeDisplayReact from react but you have to fetch the QRString yourself from your backend. For that use case here is how you might fetch the string in your node backend or next api route.
import { NextRequest, NextResponse } from "next/server"; import { fetchQrCode } from "daraja-kit"; import { BUSINESS_SHORT_CODE } from "daraja-kit"; import { ScannableQrParams } from "daraja-kit"; export const GET = async (req: NextRequest, res: NextResponse) => { const scannableQRParams: ScannableQrParams = { Amount: 100, MerchantName: "KISS KISS Adventures", RefNo: "Your REF NO", Size: "100", //square pixels, TrxCode: "BG", //for buy goods. others are "BG" | "WA" | "PB" | "SM" | "SB", }; try { const { QRCode } = await fetchQrCode(scannableQRParams); return NextResponse.json({ data: QRCode }, { status: 200 }); } catch (err: any) { console.error(err); return NextResponse.json( { message: "An error occurred", }, { status: 500, } ); } };

After fetching your QRCode in your backend you can then use the QRCodeDisplayReact from daraja-kit to display your QRCode . Example

import React, { useEffect, useState } from "react"; import { QRCodeDisplayReact } from "daraja-kit"; import axios from "axios"; const VanillaReactQRCodeExample = () => { const [qrString, setQrString] = useState(null); useEffect(() => { axios .get('your backend route') .then((res) => setQrString(res.data.QRCode)) .catch((err) => { //handle errors here }); }, []); return ( <> {qrString ? ( <div className="w-[100px] aspect-square mt-5 mx-auto"> <QRCodeDisplayReact qrString={qrString} /> </div> ) : ( "show loading spinner or something" )} </> ); }; export default VanillaReactQRCodeExample;

You can use the className prop to adjust the size and appearance of the QRcode. However it is best practice to use the same size as the size you defined when making the request to daraja api.

State Of A Lipa Na Mpesa Online Payment

You can use the getStateOfALNMOnlinePayment to get the state of a lipa na mpesa online payment. You can use the types StateOfALNMOnlinePaymentParam and StateOfALNMOnlinePaymentResponse to handle the response.

RegisterURLS

You can use this api to register validation and confirmation URLs. You can read the official docs here. The gist is that the URLs you register will be used to confirm or validate a transaction each time it is executed.

You can use the registerC2BUrl function to make the request. It takes in an object as an argument of type RegisterUrlBody and returns a RegisterUrlResponse

B2CPaymentRequest

B2C API is an API used to make payments from a Business to Customers (Pay Outs), also known as Bulk Disbursements. B2C API is used in several scenarios by businesses that require to either make Salary Payments, Cashback payments, Promotional Payments(e.g. betting winning payouts), winnings, financial institutions withdrawal of funds, loan disbursements, etc. You can read the official docs here.

You can use the b2cPaymentRequest function to make that call. It takes a B2CRequestBody and returns a Promise of type B2CRequestResponse.

Transaction Status

Check the status of a transaction. Read the official docs here.

You can use the getTransactionStatus function to make the api call. The function takes a TransactionStatusBody and returns a promise of TransactionStatusResponse.

Account balance

The Account Balance API is used to request the account balance of a short code. This can be used for both B2C, buy goods and pay bill accounts. Read the official docs here.

You can use the getAccountBalance function to make the call. It takes an object of type AccountBalanceBody and returns an awaitable promise of type AccountBalanceResponse

ReverseC2BTransaction

Reverses a C2B M-Pesa transaction. Once a customer pays and there is a need to reverse the transaction, the organization will use this API to reverse the amount. You can read the official docs here.

You can use the reverseC2BTransaction function to make the API call. It takes in an arguement of typeReverseC2BTransactionBody and returns an awaitable promise of type ReverseC2BTransactionResponse

Tax Remittance

This API enables businesses to remit tax to Kenya Revenue Authority (KRA). To use this API, prior integration is required with KRA for tax declaration, payment registration number (PRN) generation, and exchange of other tax-related information. You can read the official docs here.

You can use the remitTax function to make the api call. It takes in an arguement of type TaxRemittanceBody and returns an awaitable promise of type TaxRemittanceResponse

B2BPayment Request

This API enables you to pay bills directly from your business account to a pay bill number, or a paybill store. You can use this API to pay on behalf of a consumer/requester.

You can use the b2bPaymentRequest function to make that call. It takes an arguement of type BusinessRequestBody and returns an awaitable promise of type BusinessRequestResponse.

B2BExpressCheckout

This API enables you to pay bills directly from your business account to a pay bill number, or a paybill store. You can use this API to pay on behalf of a consumer/requester.

You can use the b2bExpressCheckout function to make that call. It takes an arguement of type B2BExpressCheckoutBody and returns an awaitable promise of type unknown. I have not used this api extensively but i am working on finding out how it works in depth and update the return typings correctly.