Fetch messages from API

Fetching messages sample code

The PHP code snippet below shows how to fetch messages from our API.

The code uses our PHP SDK

require 'vendor/autoload.php';
use AfricasTalking\SDK\AfricasTalking;

// Set your app credentials
$username = "MyAppUsername";
$apikey   = "MyAppAPIKey";

// Initialize the SDK
$AT       = new AfricasTalking($username, $apiKey);

// Get the sms service
$sms = $AT->sms();

// Our API will return 100 messages at a time back to you
// starting with what you currently believe is the lastReceivedId.
// Specify 0 for the first time you access the method
// and the ID of the last message we sent you on subsequent calls
$lastReceivedId = 0;

try {
    // Fetch all messages using a loop
    do {
        $messages = $sms->fetchMessages([
            'lastReceivedId' => $lastReceivedId

        foreach($messages as $message) {

            // Reassign the lastReceivedId
            $lastReceivedId = $message->id;
    } while(count($results) > 0);

    // NOTE: Be sure to save the lastReceivedId for next time
} catch (Exception $e) {
    echo "Error: ".$e->getMessage();

You can incrementally fetch your application inbox. To do so, you make a HTTP GET request to the following endpoints:


Live: https://api.africastalking.com/version1/messaging
Sandbox: https://api.sandbox.africastalking.com/version1/messaging

Request Parameters

In addition to the standard request headers, the body of the request should contain the following fields:

Parameter Description
Africa's Talking application username.
This is the id of the message that you last processed. The default is 0.

Preferred Method

We highly recommend configuring your application to receive messages via notifications instead of using the fetch messages API. This is the preferred method of receiving messages.

API Response

The body of the response will be a JSON object containing the following fields:

Parameter Description
A Map containing the messages contained in your inbox.
  • Messages: List A list of messages in your inbox.

    Each message will have the following fields:
    • linkId: String A unique identifier attached to each incoming message.
    • text: String The content of the sms received.
    • to: String Your registered short code that the sms was sent out to.
    • id: Integer The id of this message.
    • date: String The date when the sms was sent.
    • from: String The sender's phone number.

Below is a sample fetch messages response for a successful request:

    "SMSMessageData": {
        "Messages": [{
            "linkId": "SampleLinkId123",
            "text": "Hello",
            "to": "28901",
            "id": 15071,
            "date": "2018-03-19T08:34:18.445Z",
            "from": "+254711XXXYYY"