Build USSD with Python and Django

How I build my USSD subscription service

Alamin Musa Magaga
7 min readJul 8, 2022
Photo by Ashutosh Singh Rana on Unsplash

In this tutorial, I will show how to build a USSD subscription service with python, Django, Ngrok, and Africastalking API. so let's get started

USSD

Unstructured Supplementary Service Data (USSD) is a Global System for Mobile Communications (GSM) protocol that allows users without a smartphone or internet connection to subscribe to certain services, check account balances, transfer funds, and many others.USSD fosters a greater financial inclusion for the underbanked, people in rural areas, and those without a smartphone by allowing them to enjoy almost the same opportunities as those with smart devices in financial and transaction assessment.

The USSD gateway transmits the request to the USSD application, which then generates a response to the request and sends it back to the gateway. The gateway then delivers the response to the application, which in turn sends it to the user, who receives it on their mobile phone screen. This creates a real-time connection and enables speedier communication between the user and the client application.

The use of USSD is not only limited to financial transactions; it is also used in many other contexts, including voting, surveys, utility services, competitions, and promotions.

Django

Django is a highly secured, free, and open-source Python web framework that makes it easier for developers to build websites with greater flexibility.

Django is one of the most popular Python frameworks for web development because of its Compatibility, Infrastructure, Security, great documentation, and active community support.

Django is being used by top global industries such as Instagram, Spotify, Pinterest, Mozilla, and Eventbrite.

Ngrok

Ngrok is a cross-platform, that enables developers to share their localhost servers with people, systems, and cloud services.

Ngrok creates a secure tunnel to our local machine and allows the local host server to be hosted on its subdomain with no need for the computer IP address or domain name.

It allows developers to share their local host server for clients and interesting parties to access projects run locally without deployment to a live server.

Africastalking

Africastalking is a platform that allows developers to employ strong SMS, USSD, Voice, Airtime, and Payments APIs to realize their ideas as they create and support scalable enterprises.

Step 1: Create A Django Project

open your command prompt and install Django

pip install django==1.11

Note: For this project, Django version 1.11 is Required.

Create a Django project after installation.

django-admin startproject subscription

Navigate to the project directory

cd subscription

Use your favorite editor or IDE to open the Subscription project; I’m using Visual Studio Code.

code .

Step 2: Create an Application

Create an application after opening the project by executing the following code in the Vs code terminal.

python manage.py startapp demo

Open the settings.py file in the subscription folder, and then add “demo” to the INSTALLED APPS list.

settings.py

# Application definitionINSTALLED_APPS = ['django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','demo', #demo added]

Also copy this, then paste it into the urls.py file.

urls.py

from django.conf.urls import url, includefrom django.contrib import admin
urlpatterns = [url(r'^admin/', admin.site.urls),url(r'', include('demo.urls')),]

Add this code to the views.py file in the demo folder as well.

views.py

from django.views.decorators.csrf import csrf_exemptfrom django.http import HttpResponse@csrf_exemptdef index(request):
if request.method == 'POST':
session_id = request.POST.get('sessionId')
service_code = request.POST.get('serviceCode')
phone_number = request.POST.get('phoneNumber')
text = request.POST.get('text')

response = ""
if text == "":
response = "CON Welcome to our News subscription service \n"
response += "1. Sport \n"
response += "2. political \n
response += "3. Local \n"
response += "4. International"
elif text == "1":
response = "CON Select Your Preferred Sport Plans \n"
response += "1. Daily @ N100 \n"
response += "2. Weekly @ N50 \n"
response += "3. Monthly @ N25 "
elif text == "1*1":
response = "CON You will be charged N100 for your Daily Sports news subscription \n"
response += "1. Auto-Renew \n"
response += "2. One-off Purchase \n"
elif text == "1*1*1":
response = "END thank you for subscribing to our daily sport news plan \n"
elif text == "1*1*2":
response = "END thank you for your one-off daily sport news plan \n"
elif text == "1*2":
response = "CON You will be charged N50 for our weekly Sports news plan \n"
response += "1. Auto-Renew \n"
response += "2. One-off Purchase \n"
elif text == "1*2*1":
response = "END thank you for subscribing to our weekly sport news plan \n"
elif text == "1*2*2":
response = "END thank you for your one-off weekly sport news plan \n"
elif text == "1*3":
response = "CON You will be charged N25 for our monthly Sports news plan \n"
response += "1. Auto-Renew \n"
response += "2. One-off Purchase \n"
elif text == "1*3*1":
response = "END thank you for subscribing to our monthly sport news plan \n"
elif text == "1*3*2":
response = "END thank you for your one-off monthly sport news plan \n"
return HttpResponse(response)

the function index will receive the call response from your service code. This first line of code if request.method == ‘POST’ instructs Python to run the lines of code below if a POST is sent to the server when a user dials the service code. The next four lines of code are the defined variables.

 session_id = request.POST.get(‘sessionId’)
service_code = request.POST.get(‘serviceCode’)
phone_number = request.POST.get(‘phoneNumber’)
text = request.POST.get(‘text’)

The line if text == “ “: means that the user has not sent any request after dialing the USSD code. the line of code response = “CON Welcome to our News subscription service \n” is the first message that appears on a User’s screen immediately after dialing a USSD code. According to Africastalking, every if or elif statement has a procedure that starts with the CON that appears in the response. response += “1. Sport \n”. is the first option that a user can reply while the response += “1. political \n” and response += “1. local \n” are the second and the third option that the user can reply to, you can create as many options as you like.

The elif text == “1” means that if a user replies with 1, do the following. If a user replies with 1, execute the following after the previous person replies with 1 which is indicated by the elif text == “1*1”, the elif text == “1*1*1” also means that if a user replies with 1, do the following after the user has initially replied twice to the first choices. the response = “END thank you for your one-off daily sport news plan \n”is the message that appears on a User screen since the User replied with 1. The END in the string is the last message after which the connection will be terminated. this principle is the same for elif text == “2” ,elif text == “2*1”,elif text == “2*1*1”and the rest of the elif text lines of code.

the last line of code return HttpResponse(response) allows a view function to return a response. we decorated our function with @csrf_exempt because the POST request is not from a form we have to explicitly inform Django to exempt this particular views function {% csrf_token %}which is generally used in forms.

Include this code below in the demo folder’s urls.py.py file.

urls.py

from django.conf.urls import urlfrom . import views
urlpatterns = [url(r'^$', views.index, name='index')]

Step 3:Create an Africastalking account

Create an account on the Africastalking website and log in, click on the Sandbox app.

Navigate to the USSD in the dashboard and Click Create channel This will take you to a page where you will create your own USSD service code.

Africastalking has a general shared Service Code *384#, and you are expected to add a unique code in the channel to differentiate your Service Code from others.

You will also be required to provide a USSD callback URL that is connected to our project. Since we are running our project locally, we will use Ngrok to provide a public URL that we will use later for accessing our local host

Run the Django server using the following command

python manage.py runserver

Go to the Ngrok website, download the Ngrok zip file, unzip it, and then transfer the file to your computer’s /usr/local/bin PATH directory.

Run Ngrok in the terminal using the following command

ngrok https 8000

open the settings.py file in the project and paste the Ngrok URL in ALLOWED_HOSTS.

ALLOWED_HOSTS = ['3121-197-210-53-7.eu.ngrok.io']

Use the command below to launch the Django server. Return to the africastalking app and enter the public URL for Ngrok in the callback URL field as well.

python manage.py runserver

Click on Launch simulator to test your new USSD app.

Note: Every time we run Ngrok, the URL changes, therefore you must also update the callback URL and the URL in the ALLOWED_HOSTS.

Conclusion

Congratulations, we have successfully created a simple USSD subscription app with python, Django, Ngrok, and africastalking API.

you can download the complete project from the Link

--

--

Alamin Musa Magaga

Data Scientist | Developer | Embedded System Engineer | Zindi Ambassador | Omdena Kano Lead | Youth Opportunities Ambassador | CTO YandyTech