joinjit / laravel-sms
1.1.7
2024-05-08 15:08 UTC
Requires
- php: >=7
- giggsey/libphonenumber-for-php: ^8.12
- guzzlehttp/guzzle: ^7.3
- infobip/infobip-api-php-client: ^2.4
- twilio/sdk: ^6.10
README
关于
laravel-sms
包允许您通过多个服务提供商发送短信消息。它创建了一个新的通知通道,您可以通过在通知类中调用toSMS
函数来利用它。此包允许您定义自定义规则,强制使用特定提供商将短信消息发送到某些国家。
特性
- 使用通知通道从Laravel发送短信消息
- 在发送消息前指定自定义的发件人ID
- 集成了多个短信服务提供商
- 根据国家代码和提供商定义规则
可用的提供商
- [x] [Twilio](https://twilio.com)
- [x] [Infobip](https://infobip.com)
- [x] [Leblines](https://leblines.com)
- [x] [ProxiReach](https://proxireach.com)
- [x] [SMSGlobal](https://smsglobal.com)
- [x] 日志
安装
您可以通过Composer安装此包
composer require joinjit/laravel-sms
配置
发布配置文件,您可以在这里设置您的短信提供商
php artisan vendor:publish --tag="laravel-sms"
高级
为了使包能够检测电话号码,您的notifiable
应该在模型上有一个phone
属性。电话号码应遵循E.164国际格式(例如,+9613123456),否则将抛出InvalidReceiverPhoneNumber
异常。
要覆盖notifiable
模型上的电话属性,定义一个routeNotificationForSms
函数
<?php
class User
{
...
public function routeNotificationForSms()
{
return '+' . $this->phone_number;
}
...
}
在这个例子中,用户模型有一个
phone_number
属性而不是phone
,并且不包含不符合E.164标准的电话号码的加号。
使用方法
使用php artisan make:notification <notification_name>
命令创建一个新的通知类。
在您的通知类中,确保使用Joinjit\LaravelSMS\SMSChannel
和Joinjit\LaravelSMS\SMSMessage
类。然后您应该在via
方法中指定SMSChannel::class
,然后实现一个创建新的SMSMessage
的toSMS
方法
<?php
namespace App\Notifications;
use Joinjit\LaravelSMS\SMSChannel;
use Joinjit\LaravelSMS\SMSMessage;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Notification;
class WelcomeNotification extends Notification
{
use Queueable;
/**
* The SMS message text.
*
* @var string
*/
protected $text;
/**
* Create a new notification instance.
*
* @return void
*/
public function __construct($text)
{
$this->text = $text;
}
/**
* Get the notification channels.
*
* @param mixed $notifiable
* @return array|string
*/
public function via($notifiable)
{
return [SMSChannel::class];
}
/**
* Get the SMS representation of the notification.
*
* @param mixed $notifiable
* @return SMSMessage
*/
public function toSMS($notifiable)
{
return (new SMSMessage)
->sender(env('APP_NAME'))
->content($this->text);
}
}
创建您的通知类后,您现在可以按照以下方式使用它(假设您要通知的模型已经使用了Notifiable
特性)
<?php
namespace App\Http\Controllers;
use App\User;
use App\Notifications\WelcomeNotification;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
class UserController extends Controller
{
...
/**
* Send a welcome SMS to the user.
*
* @param Request $request
* @return Response
*/
public function sendWelcomeSms(Request $request)
{
...
// Notify the user
$user->notify(new WelcomeNotification("Welcome to the app!"));
...
}
...
}
许可证
此库采用MIT许可证