Skip to content

Instantly share code, notes, and snippets.

@JaniKibichi
Last active January 27, 2022 10:42
Show Gist options
  • Save JaniKibichi/ad03c433f45d87e3cbf11273914b3071 to your computer and use it in GitHub Desktop.
Save JaniKibichi/ad03c433f45d87e3cbf11273914b3071 to your computer and use it in GitHub Desktop.
ussd + sms API integration
<?php
//in case you are connecting to a database
require_once('dbConnector.php');
//include the Africa's Talking Library
require_once('AfricasTalkingGateway.php');
//include a config file with your API Key and username etc.
require_once('config.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";
$response .= "1. My Account \n";
$response .= "2. My phone number";
}
else if ( $text == "1" ) {
// Business logic for first level response
$response = "CON Choose account information you want to view \n";
$response .= "1. Account number \n";
$response .= "2. Account balance";
}
else if($text == "2") {
// This is a terminal request. Note how we start the response with END
$response = "END Your phone number is $phoneNumber";
}
else if($text == "1*1") {
// This is a second level response where the user selected 1 in the first instance
$accountNumber = "ACC1001";
// This is a terminal request. Note how we start the response with END
$response = "END Your account number is $accountNumber";
}
else if ( $text == "1*2" ) {
// This is a second level response where the user selected 1 in the first instance
$balance = "NGN 10,000";
// SMS New Balance
$code = '20880';//use a senderId mapped to your account
//you can call a db for user number and data
$recipients = $phoneNumber;
$message = "Your new balance is ".$balance.". Thank you.";
$gateway = new AfricasTalkingGateway($username, $apikey);
try { $results = $gateway->sendMessage($recipients, $message, $code); }
catch ( AfricasTalkingGatewayException $e ) {echo "Encountered an error while sending: ".$e->getMessage(); }
// This is a terminal request. Note how we start the response with END
$response = "END Your balance is $balance";
}
// Print the response onto the page so that our gateway can read it
header('Content-type: text/plain');
echo $response;
// DONE!!!
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment