Getting stated with Mpesa Api coding with Python Django

What is Application Programming interface(API)?

As the heading suggest API is set of routines, protocols, and tools for building software applications. An API specifies how software components should interact e.g. Mpesa with other business application. 

Why do we need mpesa API?

We need mpesa Api to be able to automate out tasks e.g. KPLC needs mpesa payement in real time to be able to activate tokens in real time. It will take ages if Tokens are updated manually.  They allow a specific audience to use data more quickly, easily and efficiently when they are looking to do something specific with the information.

Which type of mpesa api do i need?

Used for reversal transaction
30 image-not-found
B2C
Mpesa Transaction from company to client
34 image-not-found
Used for balance inquiry
33 image-not-found
Used to check the status of transaction
29 image-not-found
B2B
Mpesa Transaction from one company to another
40 image-not-found
For Lipa Na M-Pesa online payment using STK Push.



 

This list is not exhausted visit official site to see more, https://developer.safaricom.co.ke

Intergrating/coding C2B Mpesa Api With Python Django

In this article, am going to show you how to intergrate C2B mpesa Api to your website running on python django frame work. First you will need to navigate to Mpesa official website https://developer.safaricom.co.ke/ and create an app. 
  1. select mpesa sandbox and create and app. First you will need authentication to call the mpesa app https://developer.safaricom.co.ke/oauth/apis. And get the token.




  1. After getting the token the next thing you need to do is Register your url This can be done on the website or using postman utility from chrome. You register two url one for validation which will be used to send you a request so that you can validate if you want the paynment or not.The confirmation url is used to confirm if the paynment was done or not. 
  2. The next thing is to simulate transaction(assuming the role of the sender) this is done by use of postman or from the website.

Coding the validation and confirmation server

This is only for Python/django deverlopers. You can follow the tutorial here https://djangoproject.com.
After stating the project and creating an app, which i assume you have, you will nead to configue two url validation and confirmation. Go to views and add the following codes

urls.py

from django.conf.urls import url
from . import views
from django.views.decorators.csrf import csrf_exempt

urlpatterns = [
    url(r'^get_end/$',views.CreateEndPoint.as_view(), name = 'create_end' ),
    url(r'^validation/$', csrf_exempt(views.ValidationView.as_view()), name='major'),
    url(r'^confirmation/$', csrf_exempt(views.ConfirmationView.as_view()), name='major'),
]

views.py

import json
from django.views import View
class ValidationView(View):    
    def post(self, request):
        body = request.body  # remain
try:
            host_name = "%s"%str(request.get_host())
            c2b_con=json.loads(request.body)
            db = confirmationc2b(TransactionType =c2b_con["TransactionType"], TransId=c2b_con["TransID"],
                TransTime =timezone.now(),TrasAmount=c2b_con["TransAmount"],BusinessShortCode = c2b_con["BusinessShortCode"],\
                BillRefNumber =c2b_con["BillRefNumber"],InvoiceNumber =c2b_con["InvoiceNumber"],\
                OrgAccountBalance=c2b_con["OrgAccountBalance"], ThirdPartyTrasID =c2b_con["ThirdPartyTransID"],\
                MSISDN =c2b_con["MSISDN"],FirstName =c2b_con["FirstName"],MiddleName =c2b_con["MiddleName"],
                LastName =c2b_con["LastName"])
            db.save()
            message = {
                "ResultCode": 0,
                "ResultDesc": "The service was accepted successfully",
                 "ThirdPartyTransID": host_name
             };
            return  HttpResponse(json.dumps(message), content_type='application/json')
        except IntegrityError as err:
            ResultCod = 1
            resltexp = str(err)
            return response_return(ResultCod, resltexp)
        except KeyError as err:
            ResultCod = 2
            resltexp = str(err)
            return response_return(ResultCod, resltexp)
        except ArithmeticError as err:
            ResultCod = 3
            resltexp = str(err)
            return response_return(ResultCod, resltexp)
        except JSONDecodeError as err:
            ResultCod = 4
            resltexp = str(err)
            return response_return(ResultCod, resltexp)
        
        else:
            ResultCod = 5
            resltexp = "we can t handle this"
            return  HttpResponse(json.dumps(message), content_type='application/json')


class ConfimationView(View):    
    def post(self, request):
        body = request.body  # remain
        return JsonResponse({"results": 0, "result_error": "This is the error"})

Thats it guys i may not have tested some of the codes, but you can leave a comment below.

Comments

Post a Comment

Popular posts from this blog

How to file KRA nil returns for unemployed with pin

SAFARICOM AVAILS NEW M-PESA API PORTAL