africastalkingltd / africastalking-php Goto Github PK
View Code? Open in Web Editor NEWOfficial PHP SDK
Home Page: https://developers.africastalking.com
License: MIT License
Official PHP SDK
Home Page: https://developers.africastalking.com
License: MIT License
Get warning message below:
Deprecation warning: Your package name africastalking-example is invalid, it should have a vendor name, a forward slash, and a package name. The vendor and package name can be words separated by -, . or _. The complete name should match "^a-z0-9/a-z0-9$". Make sure you fix this as Composer 2.0 will error.
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?
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?
$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();
}
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 ...
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).
Although PHP is synchronous, GuzzleHTTP provides a Promises library that would allow us to either:
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();
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']
]
]);
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
.
I'm willing to work on this solution but would need a go-ahead from you. Cheers 🥂
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
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.
Dashboard link is currently pointed to https://account/africastalking.com instead of https://account.africastalking.com
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?
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
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");
}
`
I have checked your sdk/api and there are many places that you are calling static methods using $this, this will quack sometime.
See answer 2 below
https://stackoverflow.com/questions/15707029/calling-static-method-non-statically
$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
I am getting the following error:
Error: Client error:
POST https://api.africastalking.com/version1/airtime/send
resulted in a401 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?
I am getting this error
Uncaught Error: Class 'AltoRouter' not found
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
How i can send sms to sandbox ?
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.
Installation requires one to downgrade to guzzle 6.5.5 from later versions of guzzle
The minimum airtime to transfer is set to 10 whereas the API allows sending 5 credits
Please make a release for africastalking ^v3.0 which includes support for guzzlehttp ^v7.0
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.
https://github.com/pro-cms/africastalking_laravel_api
Thanks for these amazing services, We can do something as africans
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.
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.
Vendor folder is not a part of the repository and the SDK folders are not found
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.