Git Product home page Git Product logo

africastalking-php's Introduction

Africa's Talking PHP SDK

Latest Stable Version

This SDK provides convenient access to the Africa's Talking API for applications written in PHP.

Documentation

Take a look at the API docs here.

Install

You can install the PHP SDK via composer or by downloading the source

Via Composer

The recommended way to install the SDK is with Composer.

composer require africastalking/africastalking

Usage

The SDK needs to be instantiated using your username and API key, which you can get from the dashboard.

You can use this SDK for either production or sandbox apps. For sandbox, the app username is ALWAYS sandbox

use AfricasTalking\SDK\AfricasTalking;

$username = 'YOUR_USERNAME'; // use 'sandbox' for development in the test environment
$apiKey   = 'YOUR_API_KEY'; // use your sandbox app API key for development in the test environment
$AT       = new AfricasTalking($username, $apiKey);

// Get one of the services
$sms      = $AT->sms();

// Use the service
$result   = $sms->send([
    'to'      => '+2XXYYYOOO',
    'message' => 'Hello World!'
]);

print_r($result);

See example for more usage examples.

Instantiation

Instantiating the class will give you an object with available methods

Application

  • fetchApplicationData(): Get app information. e.g balance

Airtime

  • send($parameters, $options): Send airtime

    • $parameters: associative array with the following keys:

      • recipients: An array of arrays containing the following keys
        • phoneNumber: Recipient of airtime. REQUIRED
        • currencyCode: 3-digit ISO format currency code (e.g KES, USD, UGX etc). REQUIRED
        • amount: Amount to send. REQUIRED
    • $options: optional associative array with the following keys:

      • idempotencyKey: Key to use when making idempotent requests
      • maxNumRetry: Maximum number of retries in case of failed airtime deliveries due to telco unavailability or any other reason.

SMS

  • send($options): Send a message

    • message: SMS content. REQUIRED
    • to: An array of phone numbers. REQUIRED
    • from: Shortcode or alphanumeric ID that is registered with your Africa's Talking account.
    • enqueue: Set to true if you would like to deliver as many messages to the API without waiting for an acknowledgement from telcos.
  • fetchMessages($options): Fetch your messages

    • lastReceivedId: This is the id of the message you last processed. Defaults to 0

The followoing methods have been moved to the content service, but, have been maintained on SMS for backwards compatibility:

  • sendPremium($options): Send a premium SMS. Calls $content->send($options)
  • createSubscription($options): Create a premium subscription. Calls $content->createSubscription($options)
  • fetchSubscriptions($options): Fetch your premium subscription data. Calls $content->fetchSubscriptions($options)
  • deleteSubscription($options): Delete a phone number from a premium subscription. Calls $content->$deleteSubscription($options)

Content

  • send($options): Send a premium SMS

    • message: SMS content. REQUIRED
    • to: An array of phone numbers. REQUIRED
    • from: Shortcode that is registered with your Africa's Talking account. REQUIRED
    • keyword: Your premium product keyword
    • linkId: "[...] We forward the linkId to your application when a user sends a message to your onDemand service"
    • retryDurationInHours: "This specifies the number of hours your subscription message should be retried in case it's not delivered to the subscriber"
  • createSubscription($options): Create a premium subscription

    • shortCode: Premium short code mapped to your account. REQUIRED
    • keyword: Premium keyword under the above short code and is also mapped to your account. REQUIRED
    • phoneNumber: PhoneNumber to be subscribed REQUIRED
  • fetchSubscriptions($options): Fetch your premium subscription data

    • shortCode: Premium short code mapped to your account. REQUIRED
    • keyword: Premium keyword under the above short code and mapped to your account. REQUIRED
    • lastReceivedId: ID of the subscription you believe to be your last. Defaults to 0
  • deleteSubscription($options): Delete a phone number from a premium subscription

    • shortCode: Premium short code mapped to your account. REQUIRED
    • keyword: Premium keyword under the above short code and is also mapped to your account. REQUIRED
    • phoneNumber: PhoneNumber to be subscribed REQUIRED

Mobile Data

  • send($parameters, $options): Send mobile data to customers

    • $parameters: associative array with the following keys:

      • productName: Payment product on Africa's Talking. REQUIRED

      • recipients: A list of recipients. Each recipient has:

        • phoneNumber: Customer phone number (in international format). REQUIRED
        • quantity: Mobile data amount. REQUIRED
        • unit: Mobile data unit. Can either be MB or GB. REQUIRED
        • validity: How long the mobile data is valid for. Must be one of Day, Week and Month. REQUIRED
        • metadata: Additional data to associate with the tranasction. REQUIRED
    • $options: optional associative array with the following keys:

      • idempotencyKey: Key to use when making idempotent requests
  • findTransaction($parameters): Find a particular transaction

    • transactionId: ID of trancation to find. REQUIRED
  • fetchWalletBalance(): Fetch your payment wallet balance

Voice

  • call($options): Initiate a phone call

    • to: Phone number that you wish to dial (in international format). REQUIRED
    • from: Phone number on Africa's Talking (in international format). REQUIRED
    • clientRequestId: Variable sent to your Events Callback URL that can be used to tag the call. OPTIONAL
  • fetchQueuedCalls($options): Fetch queued calls on a phone number

    • phoneNumber: Phone number mapped to your Africa's Talking account (in international format). REQUIRED
    • name: Fetch calls for a specific queue.
  • uploadMediaFile($options): Upload a voice media file

    • phoneNumber: phone number mapped to your Africa's Talking account (in international format). REQUIRED
    • url: The url of the file to upload. Should start with http(s)://. REQUIRED

MessageBuilder

Build voice xml when callback URL receives a POST from the voice API. Actions can be chained to create an XML string.

$voiceActions = $voice->messageBuilder();
$xmlresponse = $voiceActions
    ->getDigits($options)
    ->say($text)
    ->record()
    ->build();
  • say($text): Add a Say action

  • text: Text (in English) that will be read out to the user.

  • play($url): Add a Play action

    • url: Public url to an audio file. This file will be played back to user.
  • getDigits($options): Add a GetDigits action

    • numDigits: Number of digits should be gotten from the user
    • timeout: Timeout (in seconds) for getting digits from a user.
    • finishOnKey: key which will terminate the action of getting digits.
    • callbackUrl: URL to forward the results of the GetDigits action.
  • dial($options): Add a Dial action

    • phoneNumbers: An array of phone numbers (in international format) to call. REQUIRED
    • record: Boolean - Whether to record the conversation.
    • sequenntial: Boolean - If many numbers provided for phoneNumbers, determines whether the phone numbers will be dialed one after the other or at the same time.
    • callerId: Africa's Talking number you want to dial out with.
    • ringBackTone: URL location of a media playback you would want the user to listen to when the call has been placed before its picked up.
    • maxDuration: maximum amount of time in seconds a call should take.
  • conference(): Add a Conference action

  • record($options): Add a Record action

    • finishOnKey: Key which will terminate the action of recording.
    • maxLength: Maximum amount of time in seconds a recording should take.
    • timeout: Timeout (in seconds) for getting a recording from a user.
    • trimSilence: Boolean - Specifies whether you want to remove the initial and final parts of a recording where user was silent.
    • playBeep: Boolean - Specifies whether the API should play a beep when recording starts.
    • callbackUrl: URL to forward the results of the Recording action.
  • enqueue($options): Add an Enqueue action

    • holdMusic: URL to the file to be played while the user is on hold.
    • name: Name of queue to put call on.
  • deqeue($options): Add a Dequeue acton

    • phoneNumber: Phone number mapped to your Africa's Talking account which a user called to join the queue. REQUIRED
    • name: Name of queue you want to dequeue from.
  • reject(): Add a Reject action

  • redirect($url): Add a Redirect action

    • url: URL to transfer control of the call to
  • build(): Build the xml after chaining some of the above actions

Token

  • generateAuthToken(): Generate an auth token to use for authenticating API requests instead of your API key.

Testing the SDK

The SDK uses PHPUnit as the test runner.

To run available tests, from the root of the project run:

# Configure needed fixtures, e.g sandbox api key, Africa's Talking products
cp tests/Fixtures.php.tpl tests/Fixtures.php

# Run tests
phpunit --testdox

Issues

If you find a bug, please file an issue on our issue tracker on GitHub.

africastalking-php's People

Contributors

aksalj avatar calvinkarundu avatar dftaiwo avatar ianjuma avatar jnyoike avatar kanyikennedy avatar kevokevoh avatar michaelmwirigi avatar nicholaskimuli avatar samuelmwangiw avatar skedone avatar stephenafamo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

africastalking-php's Issues

Sandbox

How i can send sms to sandbox ?

Can I make a PR to this repo?

I would like a more fluent Api to this SDKs here is an example.

 SMS::with('username', 'api_key'))
 ->to('recipient[s]')
 ->message('hello world')
 ->as('SENDER')
 ->asPremium()
 ->shouldEnqueue()
 ->addOtherOptions([options]);
 ->done()

I believe this is more clean and straight forward to get started with. This is just a sample. If you guys are open to it, I will be more than glad to provide more information.

Move hard coded values from code to configs

I propose moving hard coded values in code such as the maximum and minimum amounts, the regex string etc... I am willing to work on this
`

		if ( !preg_match('/^[a-zA-Z]{3} \d+(\.\d{1,2})?$/', $recipient['amount']) ) {
			return $this->error("must contain a currency followed by an amount between 10 and 10000");
		}

		$amount = (int) explode(" ", $recipient['amount'])[1];

		if ( $amount < 10 || $amount > 10000) {
			return $this->error("amount must be between 10 and 10000");
		}

`

Vendor file

Vendor folder is not a part of the repository and the SDK folders are not found

The request content was malformed

Fatal error: Uncaught GuzzleHttp\Exception\ClientException: Client error: POST https://payments.africastalking.com/mobile/checkout/request resulted in a 400 Bad Request response: The request content was malformed: Expected Map as JsObject

Any help?

This is my code

$payments = $AT->payments();
try
    {
    $payments->mobileCheckout([
        'productName' => 'myproduct',
        'phoneNumber' => '+25078XXXXXXX',
        "currencyCode" => explode(" ", $amount)[0],
        "amount" => explode(" ", $amount)[1],
        'metadata'=>'test product payment'
    ]);
    return true;
     } catch ( AfricasTalkingGatewayException $e )
    {
        echo "Encountered an error while sending: ".$e->getMessage();
    }

Try catch

    $AT = new AfricasTalking(self::USERNAME, self::APIKEY);
    $SMS = $AT->sms();

    try
    {
        $SMS->send(['message' => $msg, 'to' => "+".$phone, 'from' => 'MAKANIKA']);
        return true;
    }
    catch ( AfricasTalkingGatewayException $e )
    {
        return "Encountered an error while sending: ".$e->getMessage();
    }

I think it would be nice if you added support for Exception handling like in the example available on the website

php 8

Problem 1
- Root composer.json requires africastalking/africastalking ^2.4 -> satisfiable by africastalking/africastalking[v2.4.0].
- africastalking/africastalking v2.4.0 requires guzzlehttp/guzzle ^6.2 -> found guzzlehttp/guzzle[6.2.0, ..., 6.5.x-dev] but it conflicts with your root composer.json require (^7.0.1).
Problem 2
- league/glide 2.0.x-dev requires php ^5.4 | ^7.0 -> your php version (8.0.15) does not satisfy that requirement.
- spatie/crawler 6.0.2 requires spatie/browsershot ^3.14 -> satisfiable by spatie/browsershot[3.57.5].
- spatie/browsershot 3.57.5 requires spatie/image ^1.5.3|^2.0 -> satisfiable by spatie/image[2.0.0].
- spatie/laravel-sitemap 5.9.2 requires spatie/crawler ^5.0|^6.0 -> satisfiable by spatie/crawler[6.0.2].
- spatie/image 2.0.0 requires league/glide ^2.0 -> satisfiable by league/glide[2.0.x-dev].
- spatie/laravel-sitemap is locked to version 5.9.2 and an update of this package was not requested.

Error facing

I am getting this error
Uncaught Error: Class 'AltoRouter' not found

Getting authentication errors on version 2.1.1

I am getting the following error:

Error: Client error: POST https://api.africastalking.com/version1/airtime/send resulted in a 401 Unauthorized response: The supplied authentication is invalid

I have passed in the correct username and generated a new token yet it still gives that error.


use AfricasTalking\SDK\AfricasTalking;

// Set your app credentials
$username = "myusername";
$apikey   = "09e4f23771xxxxxxxxxxxxxxxxxxxxxx";

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

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

What could be the problem?

Preprare for php 8.2

It's been months now(9) since PHP 8.2 was released and it looks like the library is not yet ready for it.

Using dynamic properties was deprecated in v8.2 and will be removed in v9(see rfc). If you're looking for info on dynamic properties, read the explanation here

the class AfricasTalking\SDK\AfricasTalking 4 occurrences

#44 seems to have a solution for it but I can't seem to find a release version

Sending Batch Messages

How do we achieve batch sending in cases where there is a unique phone number/message combination?

Something like this:

$sms->send([
        [
            'to' => '0722123456',
            'message' => 'This is a unique message'
        ],
        [
            'to' => '0713678900',
            'message' => 'this is another unique message'
         ],
         [
            'to' => '0712345678',
            'message' => 'even another one'
         ],
]);

What is available is sending a similar message to an array of numbers, or maybe am missing something ...

Upgrade to laravel 8

Please update the guzzle http library to a version supported by Laravel 8, I can't upgrade to Laravel 8 because of this dependency issue.

Composer autoloading

Composer autoloading does not seem to be working:

composer require africastalking/africastalking

Then

<?php
require 'vendor/autoload.php';

$gateway = new AfricasTalkingGateway($USERNAME, $API_KEY);

Throws

Class 'AfricasTalkingGateway' not found in index.php

Or am I doing something wrong?

Add clientRequestId to call action

clientRequestId is a feature that was added to voice to help users track call sessions.

The parameter expects a string value.

Example

            $callee = "+254720000002";
            $callerId = "+254720000000";
            $requestId = "test";
            $gatewayResponse = voice->call(callerId, callee, requestId); 

Other use-cases: one can initiate an outbound call to a sip address by passing the address as clientRequestId, when the dialplan will be processed, the application can read the clientRequestId value and place the call to that address.

The Play API is not clear

Here is the code I have:

$this->africa = new AfricasTalking($this->username, $this->apikey);
$voice = $this->africa->voice();

$text = 'https://app001100001.workers.ng/audio/glam_offer.opus';

$options = [
    'phoneNumbers' => ['+2347061105585'],
    'callerId' => $this->phone
];

$voiceActions = $voice->messageBuilder();
$xmlresponse = $voiceActions
    ->dial($options)
    ->play($text)
    ->build();

dd($xmlresponse);

Please when am done, what is the function to trigger the call.

Please ensure XXYYY is configured under your API account

Hi there, I created a create a subscription product for testing. I also have an API_KEY set, however, when I try to subscribe a user using

use AfricasTalking\SDK\AfricasTalking;

// Set your app credentials
$username = "sandbox";
$apiKey   = "apiKeyHidden";

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

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

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

// Set your premium product shortCode and keyword
$shortCode   = '22834';
$keyword     = 'music';

// Set the phone number you're subscribing
$phoneNumber = "phoneNumberRedacted";

try {
    // Get a checkoutToken for the phone number you're subscribing
    $checkoutTokenResult = $token->createCheckoutToken([
        'phoneNumber'    => $phoneNumber
    ]);

    $checkoutToken       = $checkoutTokenResult['data']->token;

    // Create the subscription
    $result = $sms->createSubscription([
        'shortCode'      => $shortCode,
        'keyword'        => $keyword,
        'phoneNumber'    => $phoneNumber,
        'checkoutToken'  => $checkoutToken
    ]);

    print_r($result);
} catch (Exception $e) {
    echo "Error: ".$e->getMessage();
}

it renders an error
[description] => Please ensure 22834 is configured under your API account

How is an exception executed if there is no internet connection

I get the following message in PHP when I try to get account balance and there is no internet. How do I deal with this?

(1/1) ConnectExceptioncURL error 6: Could not resolve host: api.africastalking.com (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)

in CurlFactory.php line 185
at CurlFactory::createRejection(object(EasyHandle), array('errno' => 6, 'error' => 'Could not resolve host: api.africastalking.com', 'url' => 'https://api.africastalking.com/version1/user?username=nyamonyegirls', 'content_type' => null, 'http_code' => 0, 'header_size' => 0, 'request_size' => 0, 'filetime' => -1, 'ssl_verify_result' => 0, 'redirect_count' => 0, 'total_time' => 11.515000000000001, 'namelookup_time' => 0, 'connect_time' => 0, 'pretransfer_time' => 0, 'size_upload' => 0, 'size_download' => 0, 'speed_download' => 0, 'speed_upload' => 0, 'download_content_length' => -1, 'upload_content_length' => -1, 'starttransfer_time' => 0, 'redirect_time' => 0, 'redirect_url' => '', 'primary_ip' => '', 'certinfo' => array(), 'primary_port' => 0, 'local_ip' => '', 'local_port' => 0))in CurlFactory.php line 149

Sending SMSes should be done using using GuzzleHttp Promises

Issue

This issue has to do with how SMSes are sent using the SMS service $sms->send([...]).

When sending out a lot of SMSes, the duration it takes in sending one after the other is unacceptable as it takes about 1 second for each message.

The solution provided by the current codebase is to forego receiving a response from AfricasTalking's servers on the sending status by setting the enqueue flag to true:

enqueue: Set to true if you would like to deliver as many messages to the API without waiting for an acknowledgment from telcos.

This, however, assumes that both getting a response on the sending status of messages and sending messages in a fast way is mutually exclusive.

This should not be the case as in most instances when using the SMS API one wants to achieve both (that is, messages should still be sent out as fast as the limit on the "telcos" provides and one should still receive a response on the status of the message).

Suggested Solution

Although PHP is synchronous, GuzzleHTTP provides a Promises library that would allow us to either:

  1. Return a promise when using send such as:

    $promise = $sms->send([
      'to' => '0712345678',
      'from' => 'sender_id',
      // ....
    ]);
    
    $promise->then(function ($response) {
      // work with the response here...
    });

    Sending many messages now becomes a breeze since one can do the following:

     $promises = []; // will hold unresolved promises
     foreach ($msgs as $msg)
        // create all promises
        $promises[] = $sms->send([$msg]);
     }
    
     // Resolves all promises and returns an array of responses
     // NOTE that this does not block as in the case of sending one SMS after the other
     $responses = \GuzzleHttp\Promise\settle($promises)->wait();
  2. Hide the details from the end user by incorporating the whole promise resolution on the package itself. We can then provide a neat interface that can be used to send batch messages.

    Possible implementation is:

     class SMS extends Service {
       // ....
       public function sendBatch($options) {
         $from = $options['from'];
         $msgs = $options['msgs'];
       
         $promises = []; // will hold unresolved promises
         foreach ($msgs as $msg) {
            // create all promises
            $promises[] = $this->send(array_merge(
              $msg,
              ['from' => $from],
             ));
          }
     
         // resolve promises and return their responses.
         return \GuzzleHttp\Promise\settle($promises)->wait();
        }
        // ....
      }

    This, in my opinion, is an even better solution as all the user will have to do is:

        $responses = $sms->sendBatch([
          'from' => 'sender_id',
          'msgs' => [
            ['to' => '0712345678', 'text' => 'Hello, friend']
          ]
         ]);

Performance Gains

To send 10,000 messages with the current implementation (and still get a response) would take 1.5 hrs.

Using the above implementation would allow sending 25,000 messages in a minute.

Note

I'm willing to work on this solution but would need a go-ahead from you. Cheers 🥂

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.