How to use QR codes & MPESA for fast payments in your merchant application

User journey:

  1. User selects a product from the webpage
  2. User inputs their phone number for payment
  3. Qr code generated and displayed to the user
  4. The user scans the Qr code and gets a link to complete the payment process in Mpesa.
  5. The link received by the user initiates an Mpesa STK push to the user’s phone.
  6. The user enters the Mpesa pin to complete the payment.

Prerequisites

  • Basic knowledge of Python Programming
  • Basic understanding of Django and Rest APIs

Requirements

  • Windows 8 or any higher version
  • Django version3.2
  • Python version 3.6, 3.7, 3.8, and 3.9.
  • This article uses git bash terminal.

What you will learn:

  • Environment Setup
  • Qr code implementation in Django
  • Integration of QR with Daraja API

**NOTE**:This app focuses on the intergration of the STK with QRcode

BACKEND

These will contain the parts of the web application that allow the application to operate and are not visible to the user. We will use Django for the backend of this application.

Setting up your Django project

  • Create a directory for your project
  • Run the following code in the directory’s terminal to install virtual environment -“python -m venv venv”
  • Activate your virtual environment:- “source venv/Scripts/activate”
  • Install Django –“pip install django”
  • Install QRcode –pip install qrcode
  • Install Pillow –pip install pillow
  • Create your Django project “django-admin createproject qr_Pay” (our project will be named ‘qr_Pay’)
  • Go to the projects directory – “cd qr_Pay”
  • Create an application called ‘Payment’-“django-admin startproject Payment
  • Include the ‘Payment’ app in your project’s settings.py file
  • In the application, import the following to ‘models.py‘ file
  • Create model ‘Transactions’ to store the dbase’s contact and amount field.
  • Register your models in ‘admin.py’ .
  • Now we go back to the terminal to migrate the changes.
1. python manage.py makemigrations Payment
2. python manage.py migrate
  • Create a super user that we will use to log into the django admin site.
  • Run the following code in your terminal:
        python manage.py createsuperuser
  • The code will prompt you to fill your username, email address and password like below:
  • Now, we have a working django project called ‘qr_Pay’ with an app called ‘Payment’ which contains ‘name’ field that will store our app’s product and ‘Transactions’ field that conatains ‘item’ field as our foreign key and ‘contact’ field to receive client phone number & ‘amount field’.
  • At this point we will write the following codes in the terminal to make project migrations
    python manage.py make migtations
    python manage.py migrate
  • Run the server through the terminal:
    python manage.py runserver
  • Open your browser and log into your admin site. You should be able to see the following
  • We have created a database that contains contact and amount
  • Paste the following codes in the app’s ‘models.py’ file :

code guide

  • line 4: added ‘code’ field to contain the QR code
  • line 5: added UUID field for our uuid
  • line 7: an overwite save function
  • line 8: declare a dynamic url that triggers stk push. Replace ‘0.0.0.0:8000’ with ‘<your ip address>:8000’. Your computer will be the server of this application.
  • line 9: Map the link to the QR code
  • line 10: construct a new image based on parameters size and color
  • line 11: paste the qr code to the canvas image
  • line 12: set up the qr code file name
  • line 13: create an in memory file name
  • line 14:pass in the buffer to the canvas
  • line 15:create a file object and pass it to the ‘code’ imagefield
  • line 16:close the canvas
  • line 17:save canvas

The above code creates a model ‘Transactions’ to receive contact and amount using the respective fields

The save function overwrites the default save function after generating a QR code for the model’s ‘code’ field

**NOTE** In this program, your computer will work as the server, hence the need to replace your IP address as required.

Next step is to set up the API

Mpesa API’s

**Note** Kindly farmiliarize with the  M-Pesa API documentation before you begin this procedure 

Mpesa API is a simple and dynamic API whose integration capabilities work dynamically from small scale businesses to multi-billion companies. The following are the APIs Mpesa provides;

  • Reversal
  • Transaction Status
  • Account Balance
  • Business to Customer (B2C)
  • Customer to Business (C2B)
  • Mpesa Express

M-PESA Integration

Daraja Login page

You should sign up if you don’t have a developers account or login into your developers portal if you already have an account. Once you login into your account you should be able to see this screen;

This page contains apps a user has created using Mpesa daraja.
  • Use Case:- creating the app
    • Click the “Add a new App”  button at the top right of the page. You should see the page shown below.
    • We will use the Mpesa sandbox to develop our integrations.
    • Select ‘Lipa na Mpesa Sandbox’ and ‘Mpesa Sandbox’.
daraja add app page
  • Hit ‘create app’ button
  • You should see the following

Click on your newly created app, in this case ‘qr_Payment’ to get to the following screen

  • Here is a brief of each tab:
    • Keys – contains the consumer key and consumer secret. Note: These keys should be private, do not share with anyone.
    • Products – shows which API product you are using.
    • Analytics – shows how you interact with Mpesa API from your application.
    • Edit ‘App_name’ – to edit your app details.
    • Delete ‘App name’ – deletes your app option.

Create the first view

  • At this point , edit the INSTALLED_APPS settings in ‘qr_Pay/settings.py’ ;
  • Open the file Payment/views.py and put the following python code to write your first view:
  • In your ‘Projects’ app create a file called ‘urls .py’. The ‘Payment’ app directory should look as follows
  • Paste the following code under ‘Payment/urls’:

 code guide:

  • line 1: imports a function called path which returns an element for inclusion in urlpatterns
  • line 2: imports all methods in our views.py file.
  • line 6: defines our URL which is pointed to our getAccessToken view.
  • We’ll have to import the include() function in the ‘qr_Pay/urls.py‘ file to allow referencing of other URLconfs and insert an include() in the urlpatterns list to point the root URLconf at the Payment.urls module. Paste the following in the ‘qr_Pay/urls.py‘ file:

 Generate Mpesa Access Token

  • First, we need to authenticate our app
  • Safaricom provides an OAuth for generating an access token.
  • We need to install the python requests library which abstracts the complexities of making requests behind a simple API so that you can focus on interacting with the services and consuming data in your application.
        pip install requests

Earlier, we created a ‘qr_Payment’ app in the Mpesa Daraja account. Login into your mpesa Daraja account and find your app’s consumer_key and consumer_secret.

  • Paste the following code in ‘views.py’ .

code guide:

GET ACCESS TOKEN VIEW

line 1 :getAccessToken function
line 2: paste your customer_key variable
line 3: paste your customer_secret variable
line 4: create a URL variable that will generate the mpesa token.
line 6-8: generate the access token code to get the access token that will allow you to make calls to the API

Run the server and navigate to http://127.0.0.1:8000/api/v1/access/token on your browser to view your access token

STK Push Integration to M-Pesa on Daraja

To initiate an STK push, you will need to familiarize yourself with the parameters required by Lipa na M-Pesa online payment API

  • Log in to your Daraja account and on the navbar, under APIS select ‘MPESA Express’ then ‘MPESA EXPRESS REQUEST’
  • Go through page shown to farmiliarize with the required Lipa na M-pesa online payment API parameters
mpesa request parameters

In your Payment project, create a new file called ‘credentials.py’

created ‘credentials.py’ file

Paste the following codes in your ‘credentials.py’ file:

code guide:

line1-5: file imports
line 7: create a class called MpesaC2BCredential
line 8: consumer_key variable
line 9: consumer_secret variable
line 10: URL variable for generating the mpesa token
line 12-16: Well use the class to make a call to mpesa
line 20: define the format of our transaction timestamp.
line 21: we define our business Shortcode. Well use the test credentials provided by Safaricom Daraja sandbox.
line 22: define the passkey, this information is found in Mpesa sandbox test credentials.
line 24: define our password used to encrypt the request we send mpesa API STK push URL.
line 25: encode the password to base64 string.
line 26: decode our password to UTF-8

Now add the following function to your ‘Payment/views.py’

code guide:

line 1: define our STK push method called lipa_na_mpesa_online.
line 2: get UUID
line 3: get uuid model object
line 4: get our mpesa access token
line 5: define our STK push URL. Provided by Safaricom.
line 6: define our headers where we pass our access token
line 9: pass our mpesa Shortcode.
line 10: pass our M-pesa password.
line 11: define the transaction timestamp.
line 12: define the transaction type. Since it’s STK push we use CustomerPayBillOnline
line 13: define the amount, in this case, one shilling.
line 14: define the phone number sending the money.
line 15: define the organization shortcode receiving the funds.
line 16: define the mobile number to receive the STK pin prompt.
line 17: define a valid URL that will receive notification from Mpesa-TOKEN.Note this should be your confirmation URL.
line 18: define an identifier of the transaction.
line 19: define the description of what the transaction is all about.
line 22: get the response from Safaricom M-Pesa TOKEN.
line 24: define a response, of course, you can choose to redirect the user to a different page. In my case, I respond with HTTP response success.

  • Now we need to define URL for our STK push.
  • Paste the following code in ‘Payment/urls.py’ file.
  • Run the server using the following code: ‘python manage.py runserver 0.0.0.0:8000‘ (this uses your computer[the server] ip adress is used.
  • Log into your browser django admin page .
  • Add a transaction.
add transactions_admin page

Click ‘Save’

Now click to select the transaction. You should receive the folowing page

transactions qr code admin page

Notice the additional column ‘code’. The column contains the link to the generated qr code.

Click the link to scan te qr code .

generated qr admin page

The link from the qr_code will trigger an Mpesa stk popup on the respective inputed contact device like shown:

stk popup

At this point, we have created a fully functioning backend able to

  • receive available products a user provides
  • receive clients’ phone number and product amount
  • Generate a qr code which prompts an MPESA stk popup in the clients’ phone to complete payment.

This completes the application’s backend.

FRONTEND

The front end will entail what the user will interract with directly. The aim will be to create an interactive ui which the user will find relevant and easy to read. This will be made possible by configuring templates to our view our view. Let us begin

STEP 1: Configure static files directory:

  • Create 3 folders in your project directory namely ‘static ‘,’media’ and ‘media_root’
  • Create 2 folders inside the ‘static’ folder namely ‘static’ and ‘static-only’.
  • Add the following code at the bottom of your ‘settings .py’ file:

STEP 2: SETUP TEMPLATES DIRECTORY:

  • Create a folder called ‘templates’ inside the app directory(Payment).
  • Create another folder in the folder named ‘home’
  • In the ‘home’ folder create a file name it ‘index.html'(our hometemplate)
templates directory

STEP 3: SETUP Forms:

  • In your app directory create another file name it ‘forms.py’
forms.py
  • Install django-crispy-forms through your terminal pip install django-crispy-forms
  • Add crispy_forms in your setting.py file in INSTALLED APPS

Paste the following codes in ‘forms.py’

code guide:

line 1-3: Required imports
line 8-17: contact field form
line 18-24:amountfield form.Default value set to 1. ‘value’ attribute passes 1 as the default amount received in cosideration of the research purpose of this project.
line 25: code field form
Note ‘amount’ and ‘code’ field widgets have been set to ‘forms.HiddenInput’. This is because they wont be edited in the UI.
The user will only be required to enter their phonenumber to make payent

STEP 4: SETUP VIEWS

  • add the following codes to your ‘views.py’ file
  • Now paste the following codes in your ‘<app>/urls.py

**NOTE** update the ALLOWED HOSTS option in your ‘settings.py’ :

  • Paste the following guided code in the file ‘index.html’ and save

Notice the links <!-- Custom styles for this template-->
<link rel="stylesheet" href="{%static 'static/css/styles.css' %}">
<link rel="stylesheet" href="{%static 'static/bootstrap/css/bootstrap.min.css' %}">
.Our next step will be to add the respective directories including the images directories( {% static 'static/img/<image name>'%} ).

STEP 5:STATIC FILES

  • Inside the ‘<project name>/static/static’ directory create 2 folders namely ‘css’ and ‘img’.
staticfilesfolder
  • In the css folder, create a file called ‘styles.css’, then paste the following codes in the file

In the img folder, paste or download the sample images of your choice that you would require in your template.

samples used in this project are found in the github repository provided in the quicksetup section of this project.

images folder

  • Download bootstrap from- https://getbootstrap.com/docs/4.3/getting-started/download/ -and paste it in your'<<peoject folder>/static/static/’ directory.
  • Now run the following code in your terminal – python manage.py collectstatic
  • Run the server – python manage.py runserver
index view page

A user is now able to:

  • select product from webpage
  • input their phone number for payment

Our next step will be create a webpage to return the generated qr code for scanning.

Create a file called ‘payment.html’ in the templates folder and paste the following codes:

Run the server. This time use the code: python manage.py runserver 0.0.0.0:8000

  • Open the link -http://127.0.0.1:8000/api/v1/index
  • insert your number starting with ‘254…”
  • Select a product by clicking the ‘Buy’ button beside it
  • You should receive a generated qr code as like below:
qr_page

Scan the qr code and click the link provided. You should receive an stk push on your mobile device like shown below:

stk popup

That finalizes a complete end to end qr_pay django application.

PROJECT REPOSITORY LINK : https://github.com/apeli23/qrpay_django_darajaAPI.git

This completes the project. The application provided should be apble to achieve the following:

  1. Allow user to select a product from webpage
  2. Input their phone number for payment
  3. Generate QR code and display it to the user
  4. User scan the Qr code and get link to complete payment process in mpesa.
  5. Send link to the user which initiates an Mpesa stk push to user phone.
  6. Allow a user to enter Mpesa pin to complete the payment.

**STEPS TO NOTE**

Remember to:

  • Activate tour virtual environment before proceeding with the project
  • Activate a daraja API account to obtain required tools for your project. Check M-Pesa API documentation for proper farmiliarization
  • Include your ip adress in your models.py save function as instructed

We have successfully built an MPESA QRpayment application.

Happy coding!

0 Shares:
You May Also Like
Read More

APIs: The Web’s Legos

Over the past two years interacting with developers and businesses, one question found its way whenever conversations begin;…