如何通过Livewire组件实现Nexmo短信发送?
Livewire 发送 Nexmo(Vonage)短信实现方案
Livewire 组件属于标准的 Laravel 类,控制器中可用的 Nexmo 短信发送逻辑可以直接复用,无需额外适配,具体实现步骤如下:
1. 基础配置校验
先确认你已经完成了 Laravel Vonage 通道的基础配置:
- 已安装依赖包:
composer require laravel/vonage-notification-channel guzzlehttp/guzzle .env配置项填写正确:VONAGE_KEY=你的Vonage平台API_KEY VONAGE_SECRET=你的Vonage平台API_SECRET VONAGE_SMS_FROM=平台注册的发送号码(必须带国际区号,例如国内号码为+8613xxxxxxxxx)
2. 生成短信通知类
和控制器场景使用的通知类完全一致,执行命令生成:
php artisan make:notification SendSmsNotification
修改通知类逻辑:
<?php namespace App\Notifications; use Illuminate\Notifications\Notification; use Illuminate\Notifications\Messages\VonageMessage; class SendSmsNotification extends Notification { // 传入自定义短信内容 public function __construct(private string $smsContent) {} // 指定使用Vonage通道发送 public function via($notifiable) { return ['vonage']; } // 组装短信内容 public function toVonage($notifiable) { return (new VonageMessage()) ->content($this->smsContent); } }
3. Livewire 组件中调用发送
在需要触发短信的 Livewire 方法中直接调用通知门面即可,示例:
<?php namespace App\Livewire; use App\Notifications\SendSmsNotification; use Illuminate\Support\Facades\Notification; use Livewire\Component; class SmsSender extends Component { public $targetPhone; public $sendContent; // 触发短信发送的方法 public function submitSend() { // 重点校验手机号格式:必须带完整国际区号,否则会发送失败 $validated = $this->validate([ 'targetPhone' => 'required|regex:/^\+[1-9]\d{1,14}$/', 'sendContent' => 'required|string|max:160' ]); // 向指定手机号发送短信,无需绑定用户模型 Notification::route('vonage', $validated['targetPhone']) ->notify(new SendSmsNotification($validated['sendContent'])); // 你的后续业务逻辑,例如发送成功提示 session()->flash('msg', '短信发送请求已提交'); } public function render() { return view('livewire.sms-sender'); } }
4. 发送失败常见排查点
- 接收手机号必须带完整国际区号,例如国内手机号不要直接写
13xxxxxxxxx,需要补全为+8613xxxxxxxxx - 检查 Vonage 平台账号余额,余额不足会直接拦截发送请求
- 查看
storage/logs/laravel.log日志,可定位具体的报错原因,常见为API密钥配置错误、号码格式非法、平台权限限制等 - 如果是绑定用户模型发送,确保用户模型中
routeNotificationForVonage方法返回的是带区号的正确手机号格式
内容的提问来源于stack exchange,提问作者Francis O. Manzolo
相关产品推荐
相关产品推荐

