首页 > 解决方案 > 我无法使用 Twilio 和 Aloha 库发送短信

问题描述

我正在使用 Laravel 5.1,我想发送短信,所以我安装了 Aloha 库: https ://github.com/aloha/laravel-twilio

我编辑了 .env 文件:

TWILIO_SID=AC7556934234234234234uuuuuuuuuu3
TWILIO_TOKEN=ca8xxxxxb9b60e66666666666666d355cfe315
TWILIO_FROM=+555555555555

现在我尝试发送带有代码的短信:

...
use Twilio;
use Illuminate\Database\Eloquent\Model;
use Aloha\Twilio\TwilioInterface;
use Services_Twilio_RestException;

class AdminController extends Controller {

    public function send() {
        try {
            Twilio::message('+77777777777', 'test test test');
        } catch (\Services_Twilio_RestException $e) {
            dd($e);
        }

当我运行函数send()时,没有任何反应(空白屏幕)- catch{} 没有错误,但我也没有收到短信。当我查看 Twilio SMS 日志时,也没有任何内容。

我怎样才能收到错误消息?为什么此代码不发送消息?

标签: phplaravelsmstry-catchtwilio

解决方案


狂热的 Twilio 用户在这里。我建议在 aloha/twilio 上使用 Twilio 的原生 PHP SDK。默认情况下,我相信 aloha/twilio 会引入 twilio/sdk,因为它取决于它,但我会删除 aloha/twilio 并只使用 twilio/sdk。

composer require twilio/sdk

然后,我建议在 Services/Twilio.php 中创建一个 Twilio 类,您可以在其中注入 Twilio 的客户端,创建一个新实例并使用您的 twilio 配置数据对其进行实例化。在这个 Service 类中,您现在可以放置所有 Twilio 方法,如 sendSMS()、sendMMS()、validatePhoneNumber() 等,并通过将新的 Twilio 服务类注入控制器的构造函数来访问它们。

它可能看起来像这样:

请注意,我的 sendSMS() 实现使用了 MessagingServiceSid 而不是来自号码。如果您未在其平台中使用 Twilio CoPilot 消息服务,则可以将“messagingServiceSid”替换为“来自”。

服务/Twilio.php

namespace App\Services;

use Twilio\Rest\Client;

class Twilio
{


    /**
     * @var Client
     */
    protected $twilio;


    public function __construct() {
        try {
            $this->twilio = new Client(config('twilio.SID'), config('twilio.TOKEN'));
        }
        catch (\Exception $e) {
            //do something with the exception, client could not be instantiated.
        }
    }

//My sendSMS allows for the passing of an array in the $to argument, letting you send to
//multiple numbers (or just one)
    public function sendSMS($to, $message)
    {
        if (is_array($to)) {
            foreach($to as $value) {
                $this->twilio->messages->create($value, ['messagingServiceSid' => config('twilio.MESSAGING_SERVICE_SID'), 'body' => $message]);
            }
            return true;
        }
        $this->twilio->messages->create($to, ['messagingServiceSid' => config('twilio.MESSAGING_SERVICE_SID'), 'body' => $message]);
    }
}

管理员控制器.php

use App\Services\Twilio;

class AdminController extends Controller {

    protected $twilio;
    public function __construct(Twilio $twilio) 
    {
       $this->twilio = $twilio;
    }

    public function index()
{
$this->twilio->sendSMS('5551234567', 'Test message');
return 'Message was sent.';
}

}

如果您以这种方式实现 Twilio,您将能够在控制器内部使用任何 Twilio 逻辑,而无需重复创建新的 Twilio 客户端或传递任何配置数据。

我希望这有帮助。


推荐阅读