← Back to list

Implementing Mpesa STK push and CallbackView using Django Rest Framework(DFR)

Mpesa and Safaricom stand head and shoulders above all its competition in networking.The primary goal of Mpesa was to establish a means for…

Gabriel Ngeti · 2024-06-18 16:38 · 1 claps · 3.5 min read
#mpesa-integration #django-rest-framework #python #daraja
Open on Medium ↗
Wiki topics: 🌐 · Web Development

Implementing Mpesa STK push and CallbackView using Django Rest Framework(DFR)

Mpesa and Safaricom stand head and shoulders above all its competition in networking.The primary goal of Mpesa was to establish a means for users to transact with convience.With the strides made in technology,there was a necessity for Mpesa team to create APIs to be used within the many web and mobile applications that required the users to perform monetary transactions.

MPESA STK PUSH

Most people have their phones on them at most time,so it would make sense pay with it.Mpesa team introduced the live and sandbox api.For mpesa stk push to work one needs to generate an access token.An access token is a code genarated to give the application a time slot for the application can use the mpesa api.To implement access token generation one needs to have an Daraja account.Then navigate to the My apps section in the navbar of home view and create an app.After the app creation ,this will be generate:

App credentials

App credentials

This provides you with all the necessary details needed.Though each app is built for a specific organization,therefore some of the credentials seen there are not what you may require.

Now we implement the access generation function in your views file.Side note:This guide assumes you have the basics of django and its structures nailed.However for the purpose of security, I strongly advice to install python decouple using ‘pip install python-decouple’,it helps you to organize your settings so that you can change parameters without having to redeploy your app.Here is the implementation of the function in django:

The actual consumer key and secret should not be exposed to the source for security purpose but put in a separate .env file.It retrieves consumer key and secret from configuration, concatenates them with a colon delimiter, Base64 encodes the result, and constructs an HTTP Authorization header using the encoded value. It then sends a GET request to a specified API URL with the Authorization header and a JSON Content-Type header. The API response, expected to be in JSON format, is parsed to extract the “access_token” value, which is returned by the function. The access token will be used in the mpesa stk push function

MPESA STK PUSH(apologize for congestion)

MPESA STK PUSH(apologize for congestion)

Okay,as stated eariler the keys generated by safaricom are confidential and should never be exposed in the source code.The format date is required in the function to attach a time stamp all the transaction done by the function and should follow the format as shown above.Then use the access token received from the above function.Then ,an mpesa password is required and the formula requires the user to added the stringified mpesa shortcode ,mpesa passkey and the formatted date together and encode the password.Then construct a payload using the data received and in this case is the phone number and the amount.We then receive a JSON Response on whether the transaction is successful or not.

MPESA CALLBACK VIEW

In the mpesa stk payload,a secure callbackurl should be included where all the stk push transaction results are sent.This will help keep track transactions.

callback view function

callback view function

Note that the squigly line indicate models that have been created to store transaction results.All the transactions even the unsuccessful ones received from the mpesa to the callback urls are stored there.The body recieved from mpesa is a dictionary whose structure can be found in the daraja website.The responses whose status code is 200 are considered successful and are stored in the SuccessfulResponses model.The POST method allows the callback URL to access the function to store the data,the GET method is for viewing purposes to see all the transaction in the model.A serializer is used in this case to convert the python objects into JSON.All the conversion complexity is handled by a serializers that has to be deifined.Here is an example :

serializer

serializer

This serializer converts all the records in the AllResponses model in the database.

To summarise,This is pretty much the whole flow of the mpesa transaction via stk push.I have tried not to use non-technical terms to describe the whole flow of the data but this is with the assumption of basic django paradigms.

Happy coding.


메타데이터
post_id
fc42bf0474df
slug
implementing-mpesa-stk-push-and-callbackview-using-django-rest-framework-dfr-fc42bf0474df
url
https://medium.com/@gabrielngeti4/implementing-mpesa-stk-push-and-callbackview-using-django-rest-framework-dfr-fc42bf0474df
canonical_url
https://medium.com/@gabrielngeti4/implementing-mpesa-stk-push-and-callbackview-using-django-rest-framework-dfr-fc42bf0474df
author_url
https://medium.com/@gabrielngeti4
status
ok
fetched_at
2026-07-23 14:27:56