The new M-PESA platform dubbed G2 (for M-PESA 2nd generation platform) offers versatile integration capabilities that our development partners can take advantage of, to create excellent M-PESA journeys across the different industries they serve. This was a key factor in moving to the new platform. We have been consolidating the different interfaces our developers have expressed interest in to enable innovation around M-PESA. As expected, most of these are about the payment journeys, covering both disbursements (Business to Customers – B2C) and service payments (Customer to Business – C2B and Business to Business – B2B). These and other features are now available via secure Application Programming Interfaces (APIs) that allow for third party applications to easily plug into M-PESA.
M-PESA has been very successful mainly because of its simplicity of use and device agnostic nature – works the same way for the latest iPhone as the good old Nokia phone that has been passed over several user generations. The API rides on the same concept, providing open interfaces over standard protocols through web services. Unlike the old system (G1) where a lot of workarounds had been done to automate payment experiences, developers can now hook directly to the core M-PESA and get creative with the systems they run. Let’s look at the payments use cases below:
- Automated Payment Receipt Processing: Imagine the different scenarios that require customers to pay and have this processed instantly! Before G2, this was handled purely through Instant Payment Notification (IPN) which has served quite well. As the name indicates, IPN is only for notification processing. The use cases for payment processing are as many as your imagination can get – from utility bills to m/ecommerce, and the future is likely to get even more interesting.
With the new system, the notifications are taken a notch higher by incorporating an optional payment validation step for Paybill. This allows the payment recipient (merchants) to confirm whether to accept the incoming payment or not. While this may not sound very beneficial at the face of it, think of how many customers send payments to the right Paybill number but enter the wrong account. Money moves from the customer’s M-PESA account but their service payment will not be processed and they have to follow up. This has been creating a big problem with the merchants, leading to massive reversal requests. This can now be handled through the validation API which allows the recipient to validate any of the payment parameters, including, account, amount and even sender and only accept the payment if processing can be guaranteed.
- Automated Payment Disbursements: Many systems that process receipts will also require outward payments processing. This could range from employees’ salary disbursements to paying other merchants that accept M-PESA payments. This feature was only available via web portal for business to customers (B2C) with limitations on capacity that made it unsuitable for large disbursements. With the new platform, developers can have this done via API, which empowers them and cuts off the manual process of generating payments file, putting it in the right format then uploading it via the web portal, after which it has to be approved by a different user. With the B2C API, this is now seamless.
- Automated Payments Reversal: Even with an elaborate system, there is always a unique case that calls for a reversal. Imagine a situation where a customer has made a payment for services that the merchant is no longer able to render. The best way to handle this would be to have a reversal process that the merchant can adapt based on their internal processes. G2 supports secure payment reversal automation for such cases. The implementation will fully depend on the service journey and controls required at the recipient’s business.
Looking at the above use cases, one cannot fail to see the vast opportunity presented by the open interfaces. The future we once thought very distant of machine to machine payments is here and now. The only limitation to the adaption is the developer’s imagination.
We will be organizing workshops to engage our developer community and exchange ideas on the available APIs as well as any gaps we may need to address. We will also be sharing documentation to guide developers manage these integrations seamlessly, delivering on our promise of nurturing innovation through open systems.s
For any feedback or onboarding requests, Kindly contact M-PESABusiness@safaricom.co.ke
M-Pesa is a mobile phone-based money transfer, financing and microfinancing service, launched in 2007 by Vodafone for Safaricom and Vodacom the largest mobile network operators in Kenya and Tanzania.
M-Pesa allows users to deposit, withdraw, transfer money and pay for goods and services (Lipa na M-Pesa) easily with mobile devices. M-Pesa has spread quickly like wildfire, and by 2010 had become the most successful mobile-phone-based financial service in the world.
With M-Pesa winning the heart and souls of the masses, there was a section of the population who yearned for more. These were the software developers, they wanted an API to access the M-Pesa products. Safaricom responded to them by giving them the M-Pesa G2 API. This was welcomed but only a handful of developers were able to integrate their apps with it. Some did not have the infrastructure nor the technical know-how to do the integrations because of its requirements which included: VPN connection, soap protocol, etc.
Safaricom recently introduced a new M-Pesa API dubbed ‘The Daraja API’ (Daraja in Swahili means bridge) to try and bridge this gap for developers. You can access this API over the public internet a step up from the G2 API which required a VPN connection. The other change was that it communicated over the REST protocol, this was to try and alleviate the pain of the developers whose Apps use REST protocol but had to find a way to accommodate M-Pesa’s SOAP. Daraja API not only had the old services from G2 API(C2B, B2C, and reversal) but also exposed new M-Pesa services(B2B, Transaction status, Account balance, and Lipa na M-Pesa online)
In this article, we’ll just cover the Lipa na M-Pesa online as this is one of the most exciting API they have provided so far.
- You should have a Safaricom developers account. If you don’t have one go here developers portal and register to get an account. It is free.
- You should have Node installed
- We will be using Ngrok to expose our local server to the internet hence having it downloaded now is encouraged.
- We will be using Postman to send requests so downloading it encouraged.
Lipa Na M-Pesa Online
The Lipa na M-Pesa online service exposed by Daraja API is a very efficient way to implement merchant checkouts in e-commerce sites, mobile Apps, car parking management systems etc.
A common implementation is, you have a checkout button in your mobile App/ internet site which a user clicks to pay for the goods or services you are offering. This button when clicked triggers a post request to Daraja with the relevant payload. When Daraja receives the request it then triggers an STK push to the user’s phone prompting the user to enter his/her M-Pesa password to complete the transaction. When the user enters the password to complete the transaction, this request is sent to M-Pesa for processing, the user’s M-Pesa account is debited, and then you receive a webhook (to your servers webhook URL you provided) with the details of the transaction.\
We will now implement the server which will be receiving these webhooks from Safaricom. Our server will have minimal functionality and nothing fancy hence you should not move with it to your production environment.
We will use ExpressJS a JS library to implement our simple server.
Okay let’s go to our terminal and create a new folder and call it webhook
$ mkdir webhook && cd webhook
Initiate our package.json in our directory
$ npm init
Let’s now install our dependencies using npm
npm i -s express body-parser prettyjson
we will use body-parser middleware to extract the entire body portion of an incoming request stream and exposes it on
we will use
prettyjson to format the output that we will dump in the terminal.
Now let’s implement our server, create a file called server.js
Let’s start our server and test it out
$ node server.js
Now that our server is running let’s expose it to the internet using ngrok. Go to the folder where you downloaded and extracted ngrok and run
$ ./ngrok http 5000
Now that we have connected our webhook server to the internet let’s test to see if we can reach it on the exposed URL. Fire up postman and send a JSON post to the link exposed on your ngrok followed by the endpoint of or webhook. for my case it will be
https://05135c4e.ngrok.io/hooks/mpesa for you the
05135c4e.ngrok.io will be different because every time you start ngrok it will give you a new unique URL.
Our request is then dumped to the terminal as expected
Now that we have developed our simple server and exposed it on the internet let us now interact with the M-Pesa API.
Go to the developers portal log in with your credentials then click on the my apps tab to access your apps. Create a new app by clicking on the Add new App button which will take you to a page like the one bellow
Enter your App name and check the Lipa Na Mpesa Sandbox checkbox then click the create app button.
Click on the app you’ve created to see the details and the credentials you will use to access the M-Pesa API.
Note: I created this app for demonstration purposes and it was deleted after so the keys exposed are no longer functional for those of us who will be scrambling to use them.
Now that we have the credentials let’s authenticate ourselves and get a token that we will use to interact with the Lipa na M-Pesa service.
since we have not gone Live with our app we will use the sandbox endpoints to demonstrate (
https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials). It uses basic auth to authenticate and returns our api token that we will use to access the Lipa na M-Pesa service. The username is your customer key and the password is your customer secret. So open postman and click the authorization tab and select type as basic auth. Fill in the Username and Password then paste the link url box.
Then send the get request to get the token as shown bellow.
Now that we have the access token let’s send our first request to the Lipa na M-Pesa service. This service expects a request payload that is JSON containing.:
- BusinessShortCode: This is the organisation’s short-code (Paybill or Buygood) used to identify an organisation and receive the transaction.
- Password: This is the password used for encrypting the request sent: A base64 encoded string. (The base64 string is a combination of Short-code+Passkey+Timestamp)
- Timestamp: This is the Timestamp of the transaction, normally in the formart of YEAR+MONTH+DATE+HOUR+MINUTE+SECOND (YYYYMMDDHHMMSS) Each part should be at-least two digits apart from the year which takes four digits.
- TransactionType: This is the transaction type that is used to identify the transaction when sending the request to M-Pesa. The transaction type for M-Pesa Express is “CustomerPayBillOnline”
- Amount: This is the Amount transacted normally a numeric value. Money that customer pays to the Short-code. Only whole numbers are supported.
- PartyA: The phone number sending money. The parameter expected is a Valid Safaricom Mobile Number that is M-Pesa registered in the format 2547XXXXXXXX
- PartyB: The organisation receiving the funds. The parameter expected is a 5 to 6 digit as defined on the Short-code description above. This can be the same as BusinessShortCode value above.
- PhoneNumber: The Mobile Number to receive the STK Pin Prompt. This number can be the same as PartyA value above. Use only Safaricom numbers.
- CallBackURL: A CallBack URL is a valid secure URL that is used to receive notifications from M-Pesa API. It is the endpoint to which the results will be sent by M-Pesa API.
- AccountReference: This is an Alpha-Numeric parameter that is defined by your system as an Identifier of the transaction for CustomerPayBillOnline transaction type. Along with the business name, this value is also displayed to the customer in the STK Pin Prompt message. Maximum of 12 characters.
- TransactionDesc: This is any additional information/comment that can be sent along with the request from your system. Maximum of 13 Characters
For testing we can get the testing credentials here once logged in.
On the credentials page we will use the Lipa Na Mpesa Online Short-code as our BusinessShortCode and PartyB. We will also use Lipa Na Mpesa Online Passkey as our Passkey for generating a base64 string password.
To generate your base64 string password go to this website and encode your
Shortcode+Passkey+Timestamp (eg 174379bfb279f9aa9bdbcf158e97dd71a467cd2e0c893059b10f78e6b72ada1ed2c91920181015123520) then copy the base64 encoded string to use it as your password.
We will then send a post request containing the payload described above and with an Authorization header containing:
Bearer <Access-Token>. to this URL https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest
So open postman and click the authorization tab and select type as Bearer token. Fill in the token (The API token we got from our authorization request)then paste the link url box.
Select the type of request to be a
post request then click on the body tab, click on the raw payload, select the content type as
application/json and enter the JSON payload and click send.
The phone-number provided would then receive a STK push to enter the M-Pesa pin to complete the transaction.
After the pin is entered the customer is debited then M-Pesa sends a webhook payload to the URL we provided.
All the deducted funds during testing are automatically reversed to your account later by Safaricom.
With this introduction you can continue to play around in the sandbox and explore this API. I hope the article was informative to you. You could leave comments on which M-Pesa API service you would like me to write an article on next. Until next time bye.’