niisan/laravel-sms-notification

为 Laravel 添加短信通知通道。

v0.2.1 2021-01-11 15:11 UTC

This package is auto-updated.

Last update: 2024-09-11 23:24:29 UTC


README

为 Laravel 添加短信通知通道。

安装

首先,通过 composer 安装包。

composer require niisan/laravel-sms-notification

然后使用客户端 SDK 进行安装。如果我们使用 twilio,则需要安装 twilio SDK。

composer require twilio/sdk

然后发布配置。

php artisan vendor:publish --provider "Niisan\Notification\SmsNotificationServiceProvider"

用法

设置 .env 文件。

SMS_DRIVER=twilio
SMS_DEFAULT_FROM='+1111222233'
TWILIO_SID=***********************
TWILIO_TOKEN=***********************

在通知类中,我们可以编写以下内容

    public function via($notifiable)
    {
        return ['sms'];
    }

    public function toSms($notifiable)
    {
        return (new SmsMessage)
                ->body('hello world! ' . $notifiable->name);
    }

在可通知模型中,我们从 routeNotificationForSms 方法获取 phone_number 以发送短信

    public function routeNotificationForSms()
    {
        return $this->phone_number;
    }

在这种情况下,短信来自 env 值:SMS_DEFAULT_FROM

否则,通过 SmsMessage 类设置 tofrom

    public function toSms($notifiable)
    {
        return (new SmsMessage)
                ->body('hello world! ' . $notifiable->name)
                ->to('+2222333344')
                ->from('+1111222233');
    }

Unicode

如果我们想使用 Unicode 字符串,我们使用 unicode 方法

    public function toSms($notifiable)
    {
        return (new SmsMessage)
                ->body('hello world! ' . $notifiable->name)
                ->unicode();
    }