使用 overtrue/easy-sms 发送 Laravel 消息通知。
composer require leonis/easysms-notification-channel
-
在 config/app.php 注册 ServiceProvider (Laravel 5.5 + 无需手动注册):
'providers' => [ // ... Leonis\Notifications\EasySms\EasySmsChannelServiceProvider::class, ],
-
创建配置文件:
php artisan vendor:publish --provider="Leonis\Notifications\EasySms\EasySmsChannelServiceProvider"
-
修改应用根目录下的 config/easysms.php 中对应的参数即可。
-
创建通知:
<?php namespace App\Notifications; use Illuminate\Bus\Queueable; use Illuminate\Notifications\Notification; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\Messages\MailMessage; use Leonis\Notifications\EasySms\Channels\EasySmsChannel; use Leonis\Notifications\EasySms\Messages\EasySmsMessage; class VerificationCode extends Notification { use Queueable; public function via($notifiable) { return [EasySmsChannel::class]; } public function toEasySms($notifiable) { return (new EasySmsMessage) ->setContent('您的验证码为: 6379') ->setTemplate('SMS_001') ->setData(['code' => 6379]); } }
-
向已绑定手机号用户发送通知。
用户模型:
<?php namespace App; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; use Overtrue\EasySms\PhoneNumber; class User extends Authenticatable { use Notifiable; public function routeNotificationForEasySms($notification) { return new PhoneNumber($this->number, $this->area_code); } }
发送通知:
// 使用 Notifiable Trait $user->notify(new VerificationCode()); // 使用 Notification Facade Notification::send($user, new VerificationCode());
-
向未注册用户或未绑定手机号用户发送通知。
Notification::route( EasySmsChannel::class, new PhoneNumber(13333333333, 86) )->notify(new VerificationCode());