Complete guide on how to integrate Mpesa Express Daraja 2.0 payments API into you django app

Snospark
8 min readSep 6, 2021

I have found that the process of integrating mpesa into your app and going live with an absolutely new paybill or till number is not very straight forward. The process is not fully documentation anywhere. I had to struggle through guessing, through multiple exchanges with the bank that provided me the paybill, and a back and forth with safaricom business, and safaricom api team. Phew!! I wouldn’t want anyone to go through that.

So let’s say we want our simple django app to simply charge a user a specified amount. Our app will
- send a request to the mpesa daraja 2.0 api which will initiate a stk push to the user’s phone number. The users is informed of the amount to be deducted and the to whom the money will be sent and given the option to authorize the transaction by entering their pin. The user can cancel the request or wait for it to timeout.
- record the results of the mpesa transaction based on the responses we get from safaricom.

1. Set up the app

Assuming you have python and django installed in a virtual environment(if not, understand the basics here), and using this simple minimal app on github (or you can create your own project and app and read on to the relevant parts of this article):

git clone --single-branch --branch basic https://github.com/chainedcoder/mpayments.git

2. Mpesa developers portal

Visit https://developer.safaricom.co.ke/ and signup for an Mpesa developer portal account.

Once you’ve created the account login and create an app.

Follow this instruction video to create an app→ https://developer.safaricom.co.ke/api/v1/Repository/videos/CreatingAnApp.mp4

Once you create your portal account and an app, you’ll see it in the list of your apps as shown below. Take note of the Consumer Key and the Consumer Secret in your new app. We’ll be using these values to get an access_token that is needed for each request to the Mpesa Api.

3. A bit of context on how the Mpesa Express payment(Lipa Na Mpesa) API works

To make an mpesa request we will post to the the mpesa api url:

https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest

But when we go into production we won’t be using the sandbox url but will post to

https://api.safaricom.co.ke/mpesa/stkpush/v1/processrequest

The request body sample for mpesa express payment:

Just so you know, when we make a successful payment request, we’ll get two responses from safaricom (Get to know the Mpesa api over → here):

  1. The immediate response of our post request
  2. The callback response

The result of the post requests would look something like:

The request response would look like:

Once payment request is processed, we’ll get a callback with a successful or unsuccessful response:

4. Completing the mpayments django App and integrating Mpesa

We set up our Transaction model as shown below:

Then we’ll add .env file in the folder that has the settings file. We’ll use it to store the urls and variables that we need for Mpesa API such as the consumer_key, consumer_secret, checkout_url, callback_url etc.

We’ll install django-environ and then add the following code to the settings file. You don’t have to use django-environ to don’t even have to use environment variable. You can use a config file or some other dot-env alternative. You do you.

# settings.pyimport environ...env = environ.Env(DEBUG=(bool, False))# reading .env fileenviron.Env.read_env()...

Once that’s out of the way, we’ll use the simple code below to verify if the phone number provided is a valid. We not checking if it is a safaricom number — That is not immediately necessary. We are only checking if the number is a valid phone .

Then well write the error_codes.py file to help manage different types of errors.

Then the serializer class for processing the input and response we give to our customers or users.

Then the view.py

Then urls.py

Before we write the logic for the MpesaGateway class, let’s write our .env file. It will have the following variables:

consumer_key=xxxx
consumer_secret=xxxx
shortcode=174379
pass_key=bfb279f9aa9bdbcf158e97dd71a467cd2e0c893059b10f78e6b72ada1ed2c919
access_token_url=https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials
checkout_url=https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest

The shortcode and the pass_key are provided as test credentials by safaricom. Enter the consumer_key and consumer_secret using the values in the app you created on the Mpesa portal. Follow this link → https://developer.safaricom.co.ke/MyApps You'll need to login if you are not.

Now we’ll use the values set in our .env to post or get from the Safaricom Mpesa Sandbox servers.

Get the Access Token

We need this token to initiate a payment request. Simply, the code will be something like.

access_token_url = env("access_token_url")
consumer_key = env("consumer_key")
consumer_secret = env("consumer_secret")
requests.get(access_token_url,auth=HTTPBasicAuth(consumer_key, consumer_secret))

The token received will expire after about 3599 seconds. So we’ll need to renew it every time it’s about to expire. We’ll write a decorator class that would allow us to do just that. Then we’ll just add the decorator to methods that need to use the access_token.

So everytime we initialize the MpesaGateway class the token we be generated. The response looks something like

{
"access_token": "gzKTJOpGkJErKUpYD2nAGIO5hkXH",
"expires_in": "3599"
}

Now that we have the token, we can initiate the payment request. We write this method into our MpesaGateway class. We’ll call the method stk_push_request.

For that request, we’ll need to generate a password and then make a post request as shown below:

We’ll then add this to our class. The updated MpesaGateway class now looks like:

Now lets handle the callback. We are going to keep it simple. We won’t do error handling for the different types of failures such as invalid phone number (number that is not an mpesa number), or if the users phone is off etc. We simply generally handle failure and success.

The end product of our MpesaGateway class is now:

Now everything works. The STK prompt is made and the user is prompted for their Mpesa pin, and we are able to get a callback for success, timeout, wrong pin, or any other failure.

Here’s what it looks like:

Testing on localhost

To get the callback (since you can’t use an IP address and it must be a https:// secure url), you can install ngrok to tunnel connection to your localhost. When installed locally, it will provide you with a https url that will reach your localhost. You’ll provide this as callback in the mpesa express payment post request. Here’s a screenshot of what ngrok looks like when installed and running →

GOING LIVE

The most important thing is starting to receiving payment in the real production environment. It’s easy if you know what you are doing. If you don’t, we help you out.

Before clicking the Go Live link on the mpesa developer portal:

  1. Get an mpesa paybill or till number. You can register online (check out the requirements for opening a paybill → here). Once you have everything required, visit the mpesa portal link and register online → here, or visit any safaricom shop for further guidance, or open a till number through your bank.
  2. Create an mpesa portal. For this you’ll send an email to M-PESABusiness@Safaricom.co.ke and request for an mpesa portal (this is different from the developer portal we created at the beginning of this article). You’ll need to provide your mpesa paybill or till number. They’ll send you the application form that you will need to fill and sign.
    If you open your paybill through the bank then safaricom won’t be able to set you up for a mpesa portal — in which case you liaise with the bank that provided you with the till number or paybill so that they can create a portal for you.
    Once done, you’ll be sent the shortcode, the password, and the username (the username is generally what you provide in the application form you filled). Once these credentials are received, for your initial login, you’ll need to login ASAP before the password expires. Otherwise you’ll need the password to be reset.
    You can then use this administrator user for your app or create a new one by logging into the mpesa portal (mpesa-org.safaricom.co.ke.
  3. ̶T̶o̶ ̶l̶o̶g̶ ̶i̶n̶t̶o̶ ̶t̶h̶e̶ ̶p̶o̶r̶t̶a̶l̶ ̶y̶o̶u̶’̶l̶l̶ ̶n̶e̶e̶d̶ ̶a̶ ̶w̶i̶n̶d̶o̶w̶s̶ ̶c̶o̶m̶p̶u̶t̶e̶r̶.̶ ̶Y̶o̶u̶ ̶c̶a̶n̶ ̶b̶o̶r̶r̶o̶w̶ ̶a̶ ̶c̶o̶m̶p̶u̶t̶e̶r̶ ̶f̶o̶r̶ ̶t̶h̶i̶s̶ ̶s̶t̶e̶p̶ ̶i̶f̶ ̶d̶o̶n̶’̶t̶ ̶h̶a̶v̶e̶ ̶o̶n̶e̶ ̶o̶r̶ ̶i̶n̶s̶t̶a̶l̶l̶ ̶w̶i̶n̶d̶o̶w̶ ̶o̶n̶ ̶y̶o̶u̶ ̶c̶o̶m̶p̶u̶t̶e̶r̶;̶ ̶o̶r̶ ̶e̶a̶s̶i̶e̶r̶(̶w̶h̶i̶c̶h̶ ̶w̶h̶a̶t̶ ̶I̶ ̶d̶i̶d̶)̶,̶ ̶y̶o̶u̶ ̶c̶a̶n̶ ̶c̶r̶e̶a̶t̶e̶ ̶a̶ ̶v̶i̶r̶t̶u̶a̶l̶ ̶w̶i̶n̶d̶o̶w̶s̶ ̶e̶c̶2̶ ̶s̶e̶r̶v̶e̶r̶ ̶i̶n̶s̶t̶a̶n̶c̶e̶ ̶o̶n̶ ̶A̶W̶S̶ ̶a̶m̶a̶z̶o̶n̶ ̶u̶n̶d̶e̶r̶ ̶t̶h̶e̶ ̶f̶r̶e̶e̶ ̶t̶i̶e̶r̶,̶ ̶o̶r̶ ̶i̶f̶ ̶y̶o̶u̶ ̶h̶a̶v̶e̶ ̶f̶r̶e̶e̶ ̶c̶r̶e̶d̶i̶t̶ ̶o̶n̶ ̶G̶o̶o̶g̶l̶e̶ ̶C̶l̶o̶u̶d̶ ̶S̶e̶r̶v̶i̶c̶e̶s̶ ̶y̶o̶u̶ ̶c̶a̶n̶ ̶c̶r̶e̶a̶t̶e̶ ̶o̶n̶e̶ ̶t̶h̶e̶i̶r̶.̶
    ̶O̶n̶c̶e̶ ̶y̶o̶u̶ ̶h̶a̶v̶e̶ ̶y̶o̶u̶r̶ ̶w̶i̶n̶d̶o̶w̶s̶ ̶c̶o̶m̶p̶u̶t̶e̶r̶ ̶u̶p̶,̶ ̶r̶e̶q̶u̶e̶s̶t̶ ̶f̶o̶r̶ ̶t̶h̶e̶ ̶c̶e̶r̶t̶i̶f̶i̶c̶a̶t̶e̶ ̶b̶y̶ ̶e̶m̶a̶i̶l̶i̶n̶g̶ ̶a̶ ̶b̶l̶a̶n̶k̶ ̶e̶m̶a̶i̶l̶ ̶t̶o̶ ̶m̶-̶p̶e̶s̶a̶c̶e̶r̶t̶p̶a̶s̶s̶w̶o̶r̶d̶@̶s̶a̶f̶a̶r̶i̶c̶o̶m̶.̶c̶o̶.̶k̶e̶
    ̶Y̶o̶u̶’̶l̶l̶ ̶r̶e̶c̶e̶i̶v̶e̶ ̶a̶ ̶c̶e̶r̶t̶i̶f̶i̶c̶a̶t̶e̶ ̶w̶i̶t̶h̶ ̶a̶ ̶f̶e̶w̶ ̶m̶i̶n̶u̶t̶e̶s̶ ̶w̶i̶t̶h̶ ̶i̶n̶s̶t̶r̶u̶c̶t̶i̶o̶n̶s̶ ̶o̶n̶ ̶h̶o̶w̶ ̶t̶o̶ ̶i̶n̶s̶t̶a̶l̶l̶ ̶i̶t̶ ̶o̶n̶ ̶w̶i̶n̶d̶o̶w̶s̶.̶ ̶
    O̶n̶c̶e̶ ̶d̶o̶n̶e̶ ̶i̶n̶s̶t̶a̶l̶l̶i̶n̶g̶ ̶t̶h̶e̶ ̶c̶e̶r̶t̶i̶f̶i̶c̶a̶t̶e̶.̶ ̶L̶o̶g̶i̶n̶ ̶t̶o̶ ̶t̶h̶e̶ ̶p̶o̶r̶t̶a̶l̶.
    .
    To login into the mpesa portal, go to https://org.m-pesaforbusiness.co.ke/#/login
    .

    Create a user with administrator privileges for your app. Or simply use current administrator user you are logging in with.
  4. Now you can click the GO LIVE link on the developer portal(not the mpesa portal). Here is the direct link→ golive (you’ll need to be logged in). Fill in the details, select your app and you are good to go. You’ll need the OTP password sent to your mobile phone to complete this step.
    - Mpesa(or your bank, depending on who created the portal for you) will send you an email confirming the app has been approved for live, the email will have the pass_key, and the short_code it is associated with. This is sent to the email registered with the paybill or till number.
    - You’ll also get another email sent to the email associated with the developer portal. This email will have the production api links.
  5. Replace the consumer_key, consumer_secret, shortcode, pass_key, access_token_url, checkout_url With the production value.
    The consumer_key and consumer_secret you’ll find in the live app created by safaricom (not the sandbox app you created). Click My Apps, then select the appropriate app under active entity. The default option is sandbox.
    The .env file will be:
consumer_key=xxxx
consumer_secret=xxx
shortcode=xxx
pass_key=xxxxaccess_token_url=https://api.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentialsmpesa_query_check_url=https://api.safaricom.co.ke/mpesa/stkpushquery/v1/querycheckout_url=https://api.safaricom.co.ke/mpesa/stkpush/v1/processrequest

And just like that we are done!

--

--