weezqyd/africastalking

AfricasTalking 的 PHP API 网关

v1.1.0 2018-03-13 18:49 UTC

This package is auto-updated.

Last update: 2024-09-13 21:56:18 UTC


README

从 composer 安装此包

$ composer require weezqyd/africastalking @dev

您需要安装以下之一:一个,但我们推荐 GuzzleHttp

$ composer require guzzlehttp/guzzle
$ composer require kriswallsmith/buzz
$ composer require nategood/httpful

配置适配器

此包使用 guzzlehttp 作为默认适配器。如果您决定使用其他 HTTP 客户端,那么您需要配置您的客户端并将适配器作为构造函数的第四个参数传递。您也可以创建自己的适配器,只要它实现了 Http\Adapter\AdapterInterface 即可。

一个例子胜过千言万语

require_once 'vendor/autoload.php';

use AfricasTalking\Gateway;
use Http\Adapter\BuzzAdapter;

// These Headers are required
$headers = [
        'apikey' => 'API-KEY',
        'Accept' => 'application/json',
        'Content-Type' => 'application/x-www-form-urlencoded',
    ];
$adapter = new BuzzAdapter($headers);
// Pass the adapter and your Africastalking Username to the gateway 
// The third parameter is a sandbox flag when true the Api wiil run in the sandbox, The defaults is false
// Because we are using a custom client you dont need provide the API KEY to the gateway
// Instead pass an empty string or null
$gateway = new Gateway('USERNAME', null, true, $adapter);
        

发送短信消息

现在让我们发送一条短信通知

use AfricasTalking\Gateway;
use Http\Exceptions\HttpException;

$gateway = new Gateway('API-TOKEN', 'USERNAME');
try {
	$response = $gateway->sms->sendMessage('+254700123XXX', 'My sample message');
	var_dump($response);
} catch(HttpException $e) {
	print_r($e);
}

传递额外选项

短信 API 接受在请求中传递的额外选项

带选项发送

use Http\Exceptions\HttpException;
// ..... Rest of adapter setup
$options = [
	'from' => '22123',
	'enqueque' => 1
];
try {
	$response = $gateway->sms->sendMessage('+254700123456', 'My sample message', $options);
	var_dump($response);
} catch(HttpException $e) {
	print_r($e);
}

发送到多个收件人

有时您可能想要处理 API 响应。不用担心。为了实现这一点,将回调函数作为 sendMessage() 方法的第四个参数传递。这个回调将为发送的每条消息执行。

use Http\Exceptions\HttpException;
// ..... Rest of adapter setup
$recipients = ['+254700123456', '+254700123123', '+254700123000'];
try {
	$gateway->sms->sendMessage($recipients, 'My sample message', ['from' => '22123'], funtion($recipient) {
		// $recipient->status;
		// $recipient->messageId;
		// $recipient->cost;
		// $recipient->number;
	});
} catch(HttpException $e) {
	print_r($e);
}