Programmer Level
Setting up and getting started.
The africasTalking client library is required to run the examples below.
Simply install ‘AfricasTalkingGateway’ via nuget.
- Using visual studio click the ‘Tools’ menu bar and select ‘Nuget Package Manager’ > ‘Package Manager Console’
- a new window called ‘package manager console ‘ will appear.
- Run this command to install the api wrapper ‘install-package AfricasTalkingGateway’.
1. Beginner
SMS
Sending an SMS
We declare and create an instance of the AfricasTalkingGateway class, you then have to specify your username and api_key - with this you can authenticate successfully to the API gateway. You then initiate the sendMessage method on the gateway class. This is wrapped around a try/catch to handle any errors and exceptions that may occur as you try to send the message.
using System; class MainClass { static public void Main () { // Specify your login credentials string username = "username"; string apiKey = "APIKey"; string recipients = "+254711XXXYYY,+254733YYYZZZ"; // And of course we want our recipients to know what we really do string message = "I'm a lumberjack, I sleep all night and I work all day"; // Create a new instance of our awesome gateway class AfricasTalkingGateway gateway = new AfricasTalkingGateway (username, apiKey); try { dynamic results = gateway.sendMessage (recipients, message); foreach( dynamic result in results) { Console.Write((string)result["number"] + ","); Console.Write((string)result["status"] + ",");
Console.Write((string)result["messageId"] + ","); Console.WriteLine((string)result["cost"]); } } catch (AfricasTalkingGatewayException e) { Console.WriteLine ("Encountered an error: " + e.Message); } } }
AIRTIME
Sending Airtime
Sending airtime in C#
using System;class AirtimeSendClass { static public void Main () { ArrayList airtimeRecipientsList = new ArrayList(); Hashtable rec1 = new Hashtable(); rec1["phoneNumber"] = "+254722XXXYYY"; rec1["amount"] = "KES XXX"; // Add recipient to list airtimeRecipientsList.Add(rec1); Hashtable rec2 = new Hashtable(); rec2["phoneNumber"] = "+254722XXXYYY"; rec2["amount"] = "KES XXX"; airtimeRecipientsList.Add(rec2); AfricasTalkingGateway gateway = new AfricasTalkingGateway("MyAfricasTalking_Username", "MyAfricasTalking_APIKey"); gateway.sendAirtime(AirtimeRecipientsList);
}
VOICE
Calling a number from a virtual phone number. Make sure you have raised a number on the sandbox <here>
using System;class MainClass { static public void voiceTestCalling() { AfricasTalkingGateway gateway = new AfricasTalkingGateway(
"MyAfricasTalking_Username",
"MyAfricasTalking_APIKey"
); gateway.call("+254711082XYZ", "+254711XXXYYY"); }}
USSD
A few things to note about USSD:
- USSD is session driven. Every request we send you will contain a sessionId, and this will be maintained until that session is completed
- You will need to let the Mobile Service Provider know whether the session is complete or not. If the session is ongoing, please begin your response with CON. If this is the last response for that session, begin your response with END.
- If we get a HTTP error response (Code 40X) from your script, or a malformed response (does not begin with CON or END, we will terminate the USSD session gracefully.
Parameter | Method | Description |
---|---|---|
sessionId | POST | This is a session unique value generated when the session starts and sent every time a mobile subscriber response has been received |
phoneNumber | POST | This is the mobile subscriber number |
serviceCode | POST | This is your ussd code |
text | POST | This is the user input |
using visual studio 2013 or Greater
- go to file > new > project
- in the projects window choose web under C#
- select ASP.NET Web Application and name your project as you like
- click next
- in the template window select Empty and ensure the web api checkbox is selected and click ok
- after your project has been set up, locate the Controllers folder in your solution explorer
- right click on the Controllers folder, select Add > Controller
- in the Add Scaffold window, select Web API 2 Controller - Empty and click add
- Give it a name, we will call it MobileController
- paste this code in the MobileController.cs file.
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace Controllers
{
// you need to explicitly declare the parameters that the server will send to your app
// the server returns phoneNumber, text, sessionId and serviceCode
// this class acts as complex type to facilitate parameter binding
// make getters and setters for the values you expect from the server
public class ServerResponse
{
public string text { get; set; }
public string phoneNumber { get; set; }
public string sessionId { get; set; }
public string serviceCode { get; set; }
}
[RoutePrefix("api/mobile")]
public class MobileController : ApiController
{
[Route("ussd")]
// specify the actual route, your url will look like... localhost:8080/api/mobile/ussd...
[HttpPost, ActionName("ussd")]
// state that the method you intend to create is a POST
public HttpResponseMessage ussd([FromBody]ServerResponse ServerResponse)
{
// declare a complex type as input parameter
HttpResponseMessage rs;
string response;
if (ServerResponse.text == null) {
ServerResponse.text = "";
}
// loop through the server's text value to determine the next cause of action
if (ServerResponse.text.Equals("", StringComparison.Ordinal)) {
// always include a 'CON' in your first statements
response = "CON This is AfricasTalking \n"
response+= "1. Get your phone number";
}else if (ServerResponse.text.Equals("1", StringComparison.Ordinal)) {
response= "END Your phone number is "+ServerResponse.phoneNumber;
//the last response starts with an 'END' so that the server understands that it's the final response
} else {
response = "END invalid option";
}
rs = Request.CreateResponse(HttpStatusCode.Created, response);
// append your response to the HttpResponseMessage and set content type to text/plain, exactly what the server expects
rs.Content = new StringContent(response, Encoding.UTF8, "text/plain");
// finally return your response to the server
return rs;
}
}
}
Build and run your project.
When a user dials your ussd code, the AfricasTalking server will send a post request to your registered callback url. Use any localhost tunneling tool like ‘ngrok’.