Programmer Level

1. Beginner

SMS

Sending an SMS

To send and SMS we have to require the africastalking-ruby module; this is done with bundler, so you have to gem install africastalking-ruby to get started. You then have to create an instance of the gateway class and add your API key and username, you also need to specify the environment you’re working on; whether sandbox (test) or production. You then have to invoke the sendMessage call on the gateway instance to send a message to the specified number with the to parameter.

The number you’re sending a message to must contain a country code prefix for the send message call to work.

require 'AfricasTalkingGateway'

gateway = AfricasTalkingGateway.new("username", "apikey", "sandbox")

gateway.sendMessage(to="+254701XXXXXX", message="Hey, testing message send")

# now you can dance

To handle exceptions; you could use a try/catch on the call to sendMessage, for logging purposes, you could also print the results of the call, you would have to store the results of the method to a variable and print it out.

AIRTIME

Sending airtime

With airtime, we make a call to the sendAirtime method; when we invoke the call we pass a parameter which is a List of dictionaries. This again, allows us to send money to many numbers, and also send different amounts. The minimum amount of airtime you can send is 10 KES; this varies with the country, <here’s> a list for different countries.

require './AfricasTalkingGateway'

gateway = AfricasTalkingGateway.new("jani", "api_key","sandbox")

gateway.sendAirtime( [{:phoneNumber => "+254711AAABBB", :amount => "KES 19"},{:phoneNumber => "+254711XXXYYY", :amount => "KES 10"}] )

VOICE

Make a voice call

You need to create virtual number on the sandbox test account, or provision for one <here>.

The virtual number that you just created is the default caller number when you make outgoing calls. It is also the number that will be dialled when your clients want to make an incoming call.

  • To make an outgoing call, you need to create an AfricasTalking Gateway instance and pass your username, api key and the 'sandbox' flag as parameters. You will also need to require the gateway library.
  • Create a new file 'voice.rb' in your project directory ruby app.

require 'AfricasTalkingGateway'

gateway = AfricasTalkingGateway.new("username", "api_key")

gateway.call('+254711082300', "+254711XYZXYZ")

Handling a voice call with Sinatra

We send POST parameters to a callback you have to register <here> If we fail to invoke the callback, because the host is down or any other reasons such an internet; the call fails and is dropped; there’s a zero latency tolerance with voice. The parameters we send on the POST request are <link>.

<image_link> <sandbox_setup>

You can check voice logs <here>. This is useful to detect failure and for debugging purposes.

post '/voicecall' do

@sessionId = params[:sessionId]

@isActive = params[:isActive]

content_type 'application/xml'

# Compose the response

response = "<Response>" "<Say>"Thank you for writing in ruby, it's so concise"</Say>" "</Response>"

body response status 200

end

You can have a test virtual number that receives calls for you or your organization. When you receive several calls at once, you can determine how to route this calls as well as what to play your users as they wait on line.

Receiving a call

  • When the Africa's Talking API receives an incoming call on your virtual number, a HTTP POST is sent to your web address where your script is listening out for the post. This is your callback URL or webhook[link!]
  • You receive the HTTP POST and respond to the Africa's Talking Voice Server with XML response in PLAIN TEXT after running through your logic(saving to the database, classifying the caller, fetching the callers details).
  • The Africa's Talking Voice Server executes the response action from your callback URL. For a list of accepted actions, please see the documentation here: http://docs.africastalking.com/voice/call

Save this in a file called voice.rb and run. You’ll see this as the output;

<code output here>

Run ngrok and point it to port 5000 - copy callback url to site.

We first setup a handler on a route; with the callback we registered. This is exposed remotely via tunneling through <ngrok>; here’s how to setup ngrok locally. Running ngrok generates a URL that we update as our callback.

We return a response of type application/xml since we’re returning an XML string. The response forms the body of our response; we use sinatra’s DSL, and also return a status of 200.

In this sample we return a Say command; this will invoke our TTS engine; and an audio output will generated and sent to the caller number.

note

Unless you’re on a paid plan, when you restart ngrok - you have to update your callback urls since they change on every start.

USSD

Serving a menu

Handling USSD calls is through a callback, so you must set a callback url and own a USSD code, you can raise one <here> on the sandbox. Whenever the USSD code is dialled, we POST parameters to your callback url; you then return a response string, that must start with a CON/ END. CON allows you to continue processing other USSD requests and will display an input when dialled while END is terminal and terminates the USSD session. Some for the POST parameters we send are:

  • serviceCode
  • sessionId
  • phoneNumber
  • text

require 'sinatra'

require './AfricasTalkingGateway'

require 'dotenv'Dotenv.load

#instantiate gateway

gateway = AfricasTalkingGateway.new(ENV['AT_API_USERNAME'], ENV['AT_API_KEY'],"sandbox")

post '/ussd' do

@sessionId = params[:sessionId]

@serviceCode = params[:serviceCode]

@phoneNumber = params[:phoneNumber]

@text = params[:text]

puts "text -#{@text} on - #{@phoneNumber}"

if( @text == "" )

# This is the first request. Note how we start the response with CON

response = "CON What would you like to do? \n"

response += "1. is the value of happiness \n"

response += "2. is the formula of laughing"

elsif(@text=="1") # Your business logic to determine the account number goes here

accountNumber = "ACC1001" # This is a terminal request. Note how we start the response with END

response = "END Your account number is $accountNumber"

elsif(@text =="2") # Your business logic to determine the balance goes here

balance = "KES 1,000" # This is a terminal request. Note how we start the response with END

response = "END Your balance is $balance"

end

# Print the response onto the page so that our gateway can read it

body response status 200

end

results matching ""

    No results matching ""