Skip to content

Commit e094d2e

Browse files
committed
Doc: Add Africas Talking Airtime API tutorial
1 parent b498ec2 commit e094d2e

File tree

11 files changed

+270
-0
lines changed

11 files changed

+270
-0
lines changed

Diff for: README.md

+4
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,10 @@ This repository holds all the notes of the things I have learnt. Anyone else can
6262
- [Getting started with the Windows Subsystem for Linux](non_technical_articles/wsl.md)
6363
- [Integer conversion to binary using Python](non_technical_articles/convert_integers_to_binary_using_python.md)
6464

65+
### Africa's Talking API
66+
67+
- [Airtime API](at_airtime.md)
68+
6569
## Flask Demo Projects
6670

6771
The [flask articles above](#flask-focused-articles) are great, though I think that seeing demos of the projects which integrate the concepts is a good way to learn. Check a few below:

Diff for: at_airtime.md

+266
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,266 @@
1+
# Send Your Users Free Airtime
2+
3+
![Hero Image](/images/africas_talking/airtime/hero.jpeg)
4+
5+
How best can you appreciate your users or online clients? Say they have successfully purchased a product or service, and you want to show gratitude as a business. Or, they may be loyal clients who have stood by you for some time as a business, or as an organization.
6+
7+
One way can be to top up their voice call time. You can give them airtime. After successfully purchasing a product or service (in the case of an e-commerce site), you can send some airtime to their phone.
8+
9+
### Table of Contents
10+
11+
- [Welcome to Africa's Talking (AT)](#welcome-to-africas-talking-at)
12+
- [Getting Started With the Airtime API from AT](#getting-started-with-the-airtime-api-from-at)
13+
- [Putting It Together](#putting-it-together)
14+
- [Notes](#notes)
15+
16+
## Welcome to Africa's Talking (AT)
17+
18+
Africa's Talking aims to power communication solutions in Africa, hence the name. They have quite a number of valuable services from SMS to USSD, Voice, Payments, and Airtime. In this article, I will show you how you can utilize their Airtime API to add the appreciation feature to a web application, Flask web app to be exact.
19+
20+
### Utilizing The Airtime API
21+
22+
```python
23+
# airtime.py
24+
25+
import africastalking
26+
27+
username = "sandbox"
28+
api_key = "your-api-key"
29+
30+
africastalking.initialize(username, api_key)
31+
32+
airtime = africastalking.Airtime
33+
34+
phone_number = "+2547xxxxxxxx"
35+
currency_code = "KES" # Change this to your country's code
36+
amount = 50
37+
38+
try:
39+
response = airtime.send(
40+
phone_number=phone_number,
41+
amount=amount,
42+
currency_code=currency_code)
43+
print(response)
44+
except Exception as e:
45+
print(f"Encountered an error while sending airtime. '
46+
'More error details below\n {e}")
47+
```
48+
49+
This is a very simple and direct Python script that makes use of the Airtime API from Africa's Talking, AT in short. The API needs the following to work:
50+
51+
- SDK ( `username` and `api_key`)
52+
- Customer `phone_number`
53+
- Your country's `currency`
54+
- The `amount` to send
55+
56+
## Getting Started With the Airtime API from AT
57+
58+
These are the things you will need to do to work with the Airtime API:
59+
60+
- [Create a FREE account](#create-account)
61+
- [Initialize the SDK](#initialize-the-sdk)
62+
- [Initialize the Airtime Service](#initialize-the-airtime-service)
63+
- [The Client](#the-client)
64+
- [Sending](#sending)
65+
- [Summary](#summary)
66+
67+
### Create Account
68+
69+
Africa's Talking has a comprehensive tutorial on the Airtime API. To get started, you will need to create an account with them. It is FREE.
70+
71+
![Create account](/images/africas_talking/airtime/create_account.png)
72+
73+
### Initialize the SDK
74+
75+
The SDK needs two things: `username` and `api_key`. These are found when you create an app. Africa's Talking provides a default "sandbox" app to start with.
76+
77+
![Initialize sdk](/images/africas_talking/airtime/initialize_sdk.png)
78+
79+
The `username` can be found at the top-right of the app. With the sandbox app, you are required to use "sandbox" for the `username`. The `api_key` can be found by clicking on "Settings > API Key" as seen below.
80+
81+
![Create api key](/images/africas_talking/airtime/create_api.png)
82+
83+
Enter your password to generate an API Key. Copy it somewhere because it will not be shown to you again. Remember, the value of the `api_key` is SECRET, so be sure to maintain it as such. Within your application, you may save it in a .env file.
84+
85+
```python
86+
#.env
87+
88+
AT_API_KEY=''
89+
AT_USERNAME=''
90+
```
91+
92+
Access them as environment variables.
93+
94+
```python
95+
# config.py
96+
97+
import os
98+
99+
class Config(object):
100+
101+
# Africa's Talking configurations
102+
AT_API_KEY = os.environ.get("AT_API_KEY")
103+
AT_USERNAME = os.environ.get("AT_USERNAME")
104+
```
105+
106+
### Initialize the Airtime Service
107+
108+
With the SDK in place, it is time to initialize the airtime service.
109+
110+
```python
111+
# airtime.py
112+
113+
from app import app
114+
115+
africastalking.initialize(app.config["AT_USERNAME"], app.config["AT_API_KEY"])
116+
airtime = africastalking.Airtime
117+
```
118+
119+
The service is stored in a variable `airtime`. It will be used below to send a customer some airtime.
120+
121+
122+
### The Client
123+
124+
Before crediting a customer's airtime balance, we at least need to identify them and specify what we would like to send them.
125+
126+
```python
127+
# airtime.py
128+
129+
phone_number = current_user.phone
130+
amount = app.config["AIRTIME_AMOUNT"]
131+
currency_code = app.config["CURRENCY"]
132+
```
133+
134+
Once again, the values are sourced from environment variables. Only the `phone_number` is gotten from the app's context.
135+
136+
137+
### Sending
138+
139+
The `airtime.send()` function is used to send a customer airtime.
140+
141+
```python
142+
# airtime.py
143+
144+
try:
145+
response = airtime.send(
146+
phone_number=phone_number,
147+
amount=amount,
148+
currency_code=currency_code)
149+
150+
# See the output
151+
print(response)
152+
except Exception as e:
153+
# See any possible errors
154+
print(f"An error occured. More info:\n\n {e}")
155+
```
156+
157+
To ensure that the application does not crash in the event an error occurs, we can use the `try-except` block. We try sending some airtime. If not successful, then we print the error on the terminal so we can know what went wrong.
158+
159+
160+
### Summary
161+
162+
The final script that sends a customer airtime is as below:
163+
164+
```python
165+
# airtime.py
166+
167+
# Import AT package (pip3 install africastalking)
168+
import africastalking
169+
from app import app
170+
from flask_login import current_user
171+
172+
def airtime():
173+
# Initialize SDK
174+
africastalking.initialize(
175+
app.config["AT_USERNAME"],
176+
app.config["AT_API_KEY"])
177+
178+
# Connect to the airtime service
179+
airtime = africastalking.Airtime
180+
181+
# To client
182+
phone_number = current_user.phone
183+
amount = app.config["AIRTIME_AMOUNT"]
184+
currency_code = app.config["CURRENCY"]
185+
186+
# Send
187+
try:
188+
response = airtime.send(
189+
phone_number=phone_number,
190+
amount=amount,
191+
currency_code=currency_code)
192+
193+
# See the output
194+
print(response)
195+
except Exception as e:
196+
# See any possible errors
197+
print(f"An error occured. More info:\n\n {e}")
198+
```
199+
200+
Remember, to use the africastalking package, you will need to install it in your active virtual environment:
201+
202+
```python
203+
# Activate your virtualenvironment
204+
$ python3 -m venv venv # create
205+
$ source venv/bin/activate # activate
206+
207+
# Alternatively, you may use virtualenvwrapper
208+
# It creates and activates a virtual environment
209+
$ mkvirtualenv venv
210+
211+
# Install
212+
(venv)$ pip3 install africastalking
213+
```
214+
215+
It is always recommended to do the installation in an active virtual environment primarily to isolate the needs of one application from another.
216+
217+
218+
### Putting It Together
219+
220+
Now that the airtime module is in place, we can now show some appreciation to the customer.
221+
222+
```python
223+
# routes.py
224+
225+
from app import app
226+
from app.airtime import airtime
227+
228+
@app.route('/thank-you')
229+
def thank_you():
230+
airtime()
231+
return render_template("index.html", title="Thanks")
232+
```
233+
234+
### Notes
235+
236+
The sandbox app is ideal for testing. You should be able to see the necessary output in your terminal due to the use of the `print()` statements. However, the recipient identified by the current user's phone number will not receive the airtime top-up. You will need to switch to a "live" app, one credited with cash, and enabled by Africa's Talking team. To get started with the "live" app,
237+
238+
- Return to the [home](https://medium.com/r/?url=https%3A%2F%2Faccount.africastalking.com%2F) page
239+
240+
![Home](/images/africas_talking/airtime/home.png)
241+
242+
- Click on any of the existing teams or create a new team.
243+
244+
![Team](/images/africas_talking/airtime/team.png)
245+
246+
- Click on the "Create App" button to create a new app.
247+
248+
![Create app](/images/africas_talking/airtime/create_app.png)
249+
250+
- Your app will be listed in the new team.
251+
252+
![App list](/images/africas_talking/airtime/app_list.png)
253+
254+
- Click on the app name (in my case "test_test").
255+
256+
![App](/images/africas_talking/airtime/app.png)
257+
258+
- The app currently has KES 0.00 balance in the wallet. As much as the script may work, the recipient will not get any airtime until there is some money in her wallet. So, be sure to top up the wallet. Head over to "Billing > Payment Methods" on the left sidebar menu. Select your preferred method, and follow the steps.
259+
260+
- The last step would be to enable the Airtime service. This is done by Africa's Talking itself. Send an email to [email protected], notifying them of your intention to use the service. You will be asked to provide a few information for verification. If you are a Kenyan, you may be asked to provide a copy of your National ID card too.
261+
262+
- Hoping all goes well, and you should be good to go. You can test out the script.
263+
264+
### A Working Example
265+
266+
If you would like to see an example of a project utilizing the service, check out [sending-free-airtime-after-purchase](https://medium.com/r/?url=https%3A%2F%2Fgithub.com%2FGitauHarrison%2Fsending-free-airtime-after-purchase) on GitHub.

Diff for: images/africas_talking/airtime/app.png

47.1 KB
Loading

Diff for: images/africas_talking/airtime/app_list.png

27.1 KB
Loading

Diff for: images/africas_talking/airtime/create_account.png

48.9 KB
Loading

Diff for: images/africas_talking/airtime/create_api.png

27.6 KB
Loading

Diff for: images/africas_talking/airtime/create_app.png

24.1 KB
Loading

Diff for: images/africas_talking/airtime/hero.jpeg

50.7 KB
Loading

Diff for: images/africas_talking/airtime/home.png

27 KB
Loading

Diff for: images/africas_talking/airtime/initialize_sdk.png

38.2 KB
Loading

Diff for: images/africas_talking/airtime/team.png

27 KB
Loading

0 commit comments

Comments
 (0)