MPESA STK-PUSH INTEGRATION STEP-BY-STEP GUIDE TO INTEGRATING LIPA NA MPESA ONLINE IN PYTHON
In this guide, you are going to learn how to develop Mpesa integration to any custom website using Python. Mpesa is one of the most popular mobile money transfer services in the world.
The innovative product is offered by Safaricom — Kenya’s leading telecommunication company with the strongest and widest network coverage.
With Mpesa, anyone can send money to you in Kenya using their Safaricom sim card and a mobile phone that supports a Sim Tool Kit(STK).
Safaricom has a ‘Lipa na Mpesa’ service specifically tailored for businesses that want to collect payments through the Mpesa payment gateway for Till and Paybill numbers(short codes).
Lipa na Mpesa offers a lot of convenience to customers and businesses. Text notifications are sent to merchants’ nominated mobile numbers when customers make payments to the business’s shortcode that is issued for free by Safaricom.
Safaricom Developers Account
Make sure that we have an account with Safaricom Developers Account. To create an account visit Daraja Safaricom website. If you have an account with Safaricom Daraja you can log in else sign up.
The next step is to create a new sandbox app by clicking on the Add a New App button and give it a name. Ensure you select both Lipa na Mpesa Sandbox and Mpesa Sandbox and hit the Create App button. You will get the following success message. Awesome! Now that we have our app created successfully. Click on your newly created app.
Take note of Consumer Key and Consumer Secret, the two should always be kept as a secret.NB: Never Share Your Consumer Key or Consumer Secret with anyone.
Authentication
To make an API call, you will need to authenticate your app. We have provided an OAuth API for you to generate an access token, we support client_credentials grant type. To authorize your API call to the OAuth API, you will need a Basic Auth over HTTPS authorization token. The Basic Auth string is a base64 encoded string of your app’s client key and client secret. We have provided a means to obtain the Basic Auth string for your sandbox apps; while you are in the OAuth API’s sandbox. Click on ‘HTTP Basic Set Credentials’ button.
The OAuth access token expires after an hour, after which, you will need to generate another access token. On a production app, use a base64 library of the programming language you are using to build your app to get the Basic Auth string that you will then use to invoke our OAuth API to get an access token.
HTTP HEADER PARAMETERS
With an OAuth 2.0 Access Token, an application can now invoke our APIs by including the access token in the HTTP header. Our APIs currently only support application/json content type
import requests
import json
from requests.auth import HTTPBasicAuth
from datetime import datetime
import base64
class MpesaC2bCredential:
consumer_key = 'v0z30UH3yG7p15oGdGQiAADMZadNwBF9' # please Enter your own
consumer_secret = 'q7dKYsWqFiH7JT5Y' # please Enter your own
api_URL = 'https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials'
class MpesaAccessToken:
r = requests.get(MpesaC2bCredential.api_URL,
auth=HTTPBasicAuth(MpesaC2bCredential.consumer_key, MpesaC2bCredential.consumer_secret))
mpesa_access_token = json.loads(r.text)
validated_mpesa_access_token = mpesa_access_token['access_token']
class LipanaMpesaPpassword:
lipa_time = datetime.now().strftime('%Y%m%d%H%M%S')
Business_short_code = "174379"
OffSetValue = '0'
passkey = 'bfb279f9aa9bdbcf158e97dd71a467cd2e0c893059b10f78e6b72ada1ed2c919'
data_to_encode = Business_short_code + passkey + lipa_time
online_password = base64.b64encode(data_to_encode.encode())
decode_password = online_password.decode('utf-8')
Lipa na M-Pesa Online Payment API is used to initiate an M-Pesa transaction on behalf of a customer using STK Push. This is the same technique my Safaricom App uses whenever the app is used to make payments.
from django.http import HttpResponse
import requests
from requests.auth import HTTPBasicAuth
import json
from . credentials import MpesaAccessToken, LipanaMpesaPpassword
def getAccessToken(request):
consumer_key = 'v0z30UH3yG7p15oGdGQiAADMZadNwBF9'
consumer_secret = 'q7dKYsWqFiH7JT5Y'
api_URL = 'https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials'
r = requests.get(api_URL, auth=HTTPBasicAuth(
consumer_key, consumer_secret))
mpesa_access_token = json.loads(r.text)
validated_mpesa_access_token = mpesa_access_token['access_token']
return HttpResponse(validated_mpesa_access_token)
add the code under views.py
def lipa_na_mpesa_online(request):
access_token = MpesaAccessToken.validated_mpesa_access_token
api_url = "https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest"
headers = {"Authorization": "Bearer %s" % access_token}
request = {
"BusinessShortCode": LipanaMpesaPpassword.Business_short_code,
"Password": LipanaMpesaPpassword.decode_password,
"Timestamp": LipanaMpesaPpassword.lipa_time,
"TransactionType": "CustomerPayBillOnline",
"Amount": 1,
"PartyA": 254792598285,
"PartyB": LipanaMpesaPpassword.Business_short_code,
"PhoneNumber": 254792598285,
"CallBackURL": "https://sandbox.safaricom.co.ke/mpesa/",
"AccountReference": "BIKESHARE",
"TransactionDesc": "Testing stk push"
}
response = requests.post(api_url, json=request, headers=headers)
print(response.text)
return HttpResponse('success')
Find the code on Github