AIRTIME

Sending Airtime

We are going to send airtime from a script running in the projectName folder. We create this folder in the Setup and Dependencies section.

You do not need any resources to send airtime on the sandbox.

In the projectName folder, create a script Airtime.py and copy-paste the code below. In the code we are sending airtime in the following steps:

  1. Import the AfricasTalkingGateway class installed via pip
  2. Specify an array of dictionaries to hold the recipients and the respective airtime amounts
  3. Create a gateway instance and authenticate by passing the username and api_key parameter
  4. Call the sendAirtime() method and pass the recipient array of dictionaries

#-> projectName/Airtime.py

#import our API wrapper
from africastalking.AfricasTalkingGateway import AfricasTalkingGateway, AfricasTalkingGatewayException

#Specify an array of dicts to hold the recipients and the amount to send 
recipients = [{"phoneNumber" : "+2547XXYYYZZZ", "amount" : "KES XX"}]

#Create a new instance of our awesome gateway class 
gateway = AfricasTalkingGateway(username, apikey,"sandbox")

try:
 #That's it, hit send and we'll take care of the rest.
 responses = gateway.sendAirtime(recipients)
  for response in responses:
   print "phoneNumber=%s; status=%s " %(response['phoneNumber'],response['status'])

except AfricasTalkingGatewayException, e:
 print 'Encountered an error while sending airtime: %s' % str(e)

Fire up the simulator, register the same number as the number in your script ('+2547XXYYYZZZ'). Also, update the amount in the recipients array to say 100 and you should see the airtime appear in the simulator.

Run your code to interact with the simulator:

python Airtime.py

results matching ""

    No results matching ""