Programmer Level
1. Beginner
SMS
Sending an SMS
Create a php file in your webroot. For WAMP server (windows) the webroot or “www” directory will be automatically created (usually c:\wamp\www). For LAMP server (Linux), this is at /var/www/html. See the LAMP/WAMP setup<link>.
Ensure you have included the AfricasTalkingGateway in your webroot by downloading the gateway from the docs here or run composer require africastalking/africastalking from the command line while in your webroot folder.
Paste the code below in your script and save it as SMS.php.
<?php
require_once('AfricasTalkingGateway');
$gateway = new AfricasTalkingGateway("USERNAME", "APIKey");
$gateway->sendMessage("+254733YYYZZZ","Hey Stranger!!!!");
?>
Go to your browser and run the URL: http://localhost/SMS.php to send your message.
Ensure that you replace the “USERNAME” and “APIKey” with your credentials from your API Account.
AIRTIME
Sending Airtime
To send airtime, we make a call to the sendAirtime method and pass an array of arrays. This array allows us to send money to many numbers, and also send different amounts.
Create a php file in your webroot. For WAMP server (windows) the webroot or “www” directory will be automatically created (usually c:\wamp\www).
For LAMP server (Linux), this is at /var/www/html. See the LAMP/WAMP setup<link>.
Ensure you have included the AfricasTalkingGateway in your webroot by downloading the gateway from the docs here.
Alternatively, run composer require africastalking/africastalking from the command line while in your webroot folder.
Paste the code below in your script and save it as AIRTIME.php
<?php
require_once ('AfricastalkingGateway');
$gateway = new AfricasTalkingGateway("USERNAME", "APIKEY");
$okFormat = json_encode(array( array("phoneNumber"=>"+254700XXXYYY","amount"=>"KES 10"), array("phoneNumber"=>"+254733YYYZZZ", "amount"=>"KES 10") ));
$results = $gateway->sendAirtime($okFormat);
?>
You can have as many phone numbers as you require in the array. Go to your browser and run the URL: http://localhost/AIRTIME.php to send your message.
Ensure that you replace the “USERNAME” and “API Key” with your credentials from your API Account. Also replace your phone number with real numbers.
VOICE
Make a voice call
Voice calls are managed by the AfricasTalking infrastructure on the cloud. No SIM cards needed. First, you need a virtual number mapped to your account. You can raise one on the sandbox <here>.
Specify your Africa's Talking phone number in international format (like this “+254711082XYZ").
Specify the numbers that you want to call to in a comma-separated list. Please ensure you include the country code, +254 for Kenya in this case, +256 for Uganda, ( like this "+254711XXXYYY, +254733YYYZZZ" ).
Create a php file in your webroot. For WAMP server (windows) the webroot or “www” directory will be automatically created (usually c:\wamp\www).
For LAMP server (Linux), this is at /var/www/html. See the LAMP/WAMP setup<link>.
Ensure you have included the AfricasTalkingGateway in your webroot by downloading the gateway from the docs<here>.
Alternatively, run composer require africastalking/africastalking from the command line while in your webroot folder.
Paste the code below in your script and save it as MakeCall.php
<?php
require_once('AfricastalkingGateway');
$gateway = new AfricasTalkingGateway('USERNAME', 'APIKEY');
$results = $gateway->call("AT-Virtual-No", "Who-You-Are-Calling");
?>
You can have as many phone numbers as you require replacing the “Who-You-Are-Calling” like this "+254711XXXYYY,+254733YYYZZZ". Specify the Africastalking Virtual Number “AT-Virtual-No” as follows “+254711082XYZ".
Go to your browser and run the URL: http://localhost/MAKECALL.php to send your message.
Ensure that you replace the “USERNAME” and “API_KEY” with your credentials from your API Account. Also replace your phone number with real numbers.
Handling an incoming voice call
To handle an incoming call, your PHP script must be accessible on the public web. This means you need to be on a public IP. In case you only have your laptop, you can use Ngrok. See the setup process for your OS here.
All calls to your virtual number, will be sent as a HTTP POST to your script publicly accessible online. With Ngrok, your script running on http://localhost/HANDLECALL.php, you would have an online Public IP like https://55bf403e.ngrok.io/HANDLECALLS.php
Create a php file in your webroot. For WAMP server (windows) the webroot or “www” directory will be automatically created (usually c:\wamp\www).
For LAMP server (Linux), this is at /var/www/html. See the LAMP/WAMP setup<link>.
Ensure you have included the AfricasTalkingGateway in your webroot by downloading the gateway from the docs<here>.
Alternatively, run composer require africastalking/africastalking from the command line while in your webroot folder.
Paste the code below in your script and save it as HANDLECALLS.php
<?php
//Receive the POST PARAMETERS
$sessionId = $_POST['sessionId'];
$isActive = $_POST['isActive'];
$callerNumber = $_POST['callerNumber'];
if ($isActive == 1) {
//This is an incoming call, so you go ahead and compose the response
$response = '<?xml version="1.0" encoding="UTF-8"?><Response><Say> Hello Friday! </Say></Response>';
// Print the response onto the page so that our gateway can read it
header('Content-type: text/plain');
echo $response;
} else {
//The call is over, save POST parameters
}
?>
Set up the callback in your API dashboard.
USSD
Posting a USSD menu
To serve a USSD menu, your PHP script must be accessible on the public web. This means you need to be on a public IP. In case you only have your laptop, you can use Ngrok. See the setup process for your OS <here>.
All calls to your USSD number, will be sent as a HTTP POST to your script publicly accessible online. With Ngrok, your script running on localhost, you would have an online Public IP like https://ej4564o89.ngrok.eu.
Create a php file in your webroot. For WAMP server (windows) the webroot or “www” directory will be automatically created (usually c:\wamp\www).
For LAMP server (Linux), this is at /var/www/html. See the LAMP/WAMP setup<link>.
Ensure you have included the AfricasTalkingGateway in your webroot by downloading the gateway from the docs<here>.
Alternatively, run composer require africastalking/africastalking from the command line while in your webroot folder.
Paste the code below in your script and save it as USSDMENU.php
<?php
// Reads the variables sent via POST from our gateway
$sessionId = $_POST["sessionId"];
$serviceCode = $_POST["serviceCode"];
$phoneNumber = $_POST["phoneNumber"];
$text = $_POST["text"];
if ( $text == "" ) {
// This is the first request. Note how we start the response with CON
$response = "CON What would you want to check \n 1. My Account \n 2. My phone number";
}else {
//This is a terminal request. Note how we start the response with END
$response = "END Your phone number is $phoneNumber";
}
// Print the response onto the page so that our gateway can read it
header('Content-type: text/plain');
echo $response;
// DONE!!!
?>
Setup the callback in your API dashboard. The Menus are now available on dialing your USSD code.
2. Intermediate project (Laravel)
Introduction
This is a simple demo running on the Laravel Framework, showing usage on USSD, messaging, airtime and Voice API's.
To get started you require to install laravel version 5.2. See this link to see how to install the framework for your OS.
Why Laravel?
Laravel is fast becoming the most popular php framework available. You can quickly get started on Laravel to write clean and reusable code and develop projects smoothly.
It provides:
- Routing System: With Laravel, have an easy approach to routing. The route can be triggered in the application with good flexibility and control - with matching URLs.
- Artisan Console: Artisan is the command line interface in the laravel providing a number of commands while developing a web application.
- Http Middleware: Provides a convenient mechanism for filtering HTTP requests entering your application.
Project Structure: How to use this demo
If you have a basic idea about laravel you know the best place to get started is look at the routes. There you will see:
Route::group(['middleware' => ['web']], function () {
//
});
Route::group(['prefix' => '/main/serve'], function () {
Route::resource('/ussd', 'UssdController@index');
Route::resource('/sms', 'UssdController@getSms');
Route::resource('/call', 'UssdController@getCall');
Route::resource('/airtime', 'UssdController@getAirtime');
});
This generates a URL to a named controller and the function named that is contained in the controller.
FOR EXAMPLE if you start your apache server and run http://localhost/main/serve/sms this will send a simple message to the specified recipient.
This is basically a call to the getSms() method in the controller as referenced above. Here is the public function.
public function getSms() {
// if it’s part of the ussd replace the number with $phoneNumber
$recipient = "+254716XXXYYY";
$message = "Hi There! You were born to succeed. ;-) ";
// use your africastalking username and apikey
$gateway = new AfricasTalkingGateway($username, $apikey);
$results = $gateway->sendMessage($recipient, $message); return $results;
}
Here is the project structure and where your controller lives.
'/AppFolder/app/Http/Controllers/'
- /Auth
-AfricasTalkingGateway.php
-Controller.php
-UssdController.php
All the code is in the class:
class UssdController extends Controller {}
SMS
Code to send your SMS.
public function getSms()
{
$gateway = new AfricasTalkingGateway("USERNAME", "APIKey");
$gateway->sendMessage("+254733YYYZZZ","Hey Stranger!!!!");
}
VOICE
Code to make your call.
public function getCall() {
$gateway = new AfricasTalkingGateway('USERNAME', 'APIKEY');
$results = $gateway->call("AT-Virtual-No", "Who-You-Are-Calling");
}
AIRTIME
Code to send the airtime.
public function getAirtime() {
$gateway = new AfricasTalkingGateway("USERNAME", "APIKEY");
$okFormat = json_encode(array( array("phoneNumber"=>"+254700XXXYYY","amount"=>"KES 10"), array("phoneNumber"=>"+254733YYYZZZ", "amount"=>"KES 10") ));
}
USSD
In order to use this ensure you exclude the set of urls from CSRF protection ,this will be easy if you have already placed the web routes outside a web middleware group like you have seen above. Exclude by adding their URLs to the $except property of the VerifyCsrfToken middleware
'/AppFolder/app/Http/Middleware/'
Code to respond with your USSD Menu.
public function index(Request $request)
{
if(!empty($request)){
$serviceCode = $request->get('serviceCode');
$sessionId = $request->get('sessionId');
$phoneNumber = $request->get('phoneNumber');
$text = $request->get('text');
if ( $text == "" ) {
$response = "CON Welcome to".$serviceCode;
$response .= " 1. Send me an inspiring message.\n";
$response .= " 2. Please call and inspire me!\n";
$response .= " 3. Is it your lucky day?\n";
echo $response;
} else {
if ($text == '1') {
$main_menu = "We will be shortly sending you an inspiring message:";
$response = $main_menu;
$this->getSms();
$this->sendResponse($response, 2);
}
else {
if ($text == '2') {
$main_menu = "Please wait while we place your call.\n";
$response = $main_menu;
$this->getCall();
$this->sendResponse($response, 2);
}
else {
if ($text == '3') {
$main_menu = "Today it seems you are lucky.\n";
$response = $main_menu;
$this->getAirtime();
$this->sendResponse($response, 2);
}
}
}
}
Send Response Function
This public function composes the expected response and presents it as plain text to the USSD Gateway:
public function sendResponse($response, $type) {
switch ($type) {
case 1:
$output = "CON ";
break;
case 2:
$output = "END ";
break;
}
$output .= $response;
header('Content-type: text/plain');
echo $output;
exit;
}