grantholle/aliyun-sms-notification-channel

阿里云 SMS 通知通道适用于 Laravel。

2.4.0 2024-03-29 14:17 UTC

This package is auto-updated.

Last update: 2024-08-29 15:10:10 UTC


README

阿里云 SMS 产品用于 Laravel 的通知通道。

安装

composer require grantholle/aliyun-sms-notification-channel

配置

建议将敏感密钥和秘密包含在 .env 文件中,以便信息不包含在源代码控制中。

在您的 .env 文件中,添加以下密钥

ALIYUN_SMS_AK=XXXXXXXXXX
ALIYUN_SMS_AS=XXXXXXXXXX
ALIYUN_SMS_SIGN_NAME=名字

config/services.php 中,添加以下内容

'aliyun_sms' => [
    'key' => env('ALIYUN_SMS_AK'),
    'secret' => env('ALIYUN_SMS_AS'),
    'sign' => env('ALIYUN_SMS_SIGN_NAME'),
],

使用方法

开发期间

在开发应用程序时,可能需要防止意外向真实电话号码发送短信。为此,您可以使用非生产环境的 alwaysTo 函数来防止这种情况。

在您的 AppServiceProvider 中添加以下片段以防止向真实用户发送垃圾短信。

use GrantHolle\Notifications\Channels\AliyunSmsChannel;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        if (!app()->environment('production')) {
            AliyunSmsChannel::alwaysTo('your-phone-number');
        }
    }
}

创建通知

为您的应用程序生成一个新的通知。

php artisan make:notification OrderPaid

添加 aliyun 通道和 toAliyunSms() 函数以生成阿里云消息。存在 template() 函数来设置此消息的模板 ID,以及 data() 函数来设置模板中的占位符。

<?php

namespace App\Notifications;

use Illuminate\Notifications\Notification;
use GrantHolle\Notifications\Messages\AliyunMessage;
use App\Order;

class OrderPaid extends Notification
{
    protected $order;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct(Order $order)
    {
        $this->order = $order;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['aliyun'];
    }

    /**
     * Get the Aliyun SMS representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \GrantHolle\Notifications\Messages\AliyunMessage
     */
    public function toAliyunSms($notifiable)
    {
        return (new AliyunMessage)
            ->template('SMS_XXXXXXX')
            ->data([
                'order_no' => $this->order->order_no,
                'total' => $this->order->total,
            ]);
    }
}

路由通知

根据文档,此假设我们正在使用 User 模型。我们需要添加 Notifiable 特性和 routeNotificationForAliyun() 函数以返回电话号码。

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * Route notifications for the Aliyun SMS channel.
     *
     * @param  \Illuminate\Notifications\Notification  $notification
     * @return string
     */
    public function routeNotificationForAliyun($notification)
    {
        return $this->phone;
    }
}

发送通知

现在我们可以在应用程序中发送通知。有关队列的信息,请参阅文档

use App\Notifications\OrderPaid;

$user->notify(new OrderPaid($order));