Giter VIP home page Giter VIP logo

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

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

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

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();
    }

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");
		}

`

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 ...

Error facing

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

Vendor file

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

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.

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.

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.

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?

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.

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 🥂

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

Sandbox

How i can send sms to sandbox ?

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

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.

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.