laravel短信;laravel通知

2024-12-06 107

Laravel短信;Laravel通知

在现代Web应用中,短信通知和邮件通知是与用户交互的重要方式。Laravel框架提供了强大的通知系统,可以轻松实现多种通知方式。介绍如何在Laravel中实现短信通知,并提供几种不同的实现思路。

解决方案

Laravel的通知系统允许开发者通过多种渠道发送通知,包括邮件、短信、数据库记录等。重点介绍如何使用第三方短信服务(如阿里云短信服务)来发送短信通知,并提供详细的代码示例。

使用阿里云短信服务发送短信

安装依赖

我们需要安装阿里云SDK。可以通过Composer来安装:

bash
composer require alibabacloud/sdk

配置环境变量

.env文件中添加阿里云短信服务的配置信息:

env
ALIBABA_CLOUD_ACCESS_KEY_ID=your_access_key_id
ALIBABA_CLOUD_ACCESS_KEY_SECRET=your_access_key_secret
ALIBABA_CLOUD_SIGN_NAME=your_sign_name
ALIBABA_CLOUD_TEMPLATE_CODE=your_template_code

创建通知类

接下来,创建一个通知类。假设我们要发送注册成功后的短信通知:

bash
php artisan make:notification RegisterSuccessNotification

在生成的通知类中,编写发送短信的逻辑:

php
namespace AppNotifications;</p>

<p>use IlluminateBusQueueable;
use IlluminateNotificationsNotification;
use IlluminateContractsQueueShouldQueue;
use AlibabaCloudClientAlibabaCloud;
use AlibabaCloudClientExceptionClientException;
use AlibabaCloudClientExceptionServerException;</p>

<p>class RegisterSuccessNotification extends Notification implements ShouldQueue
{
    use Queueable;</p>

<pre><code>protected $user;

public function __construct($user)
{
    $this->user = $user;
}

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

public function toSms($notifiable)
{
    AlibabaCloud::accessKeyClient(
        config('services.alibabacloud.access_key_id'),
        config('services.alibabacloud.access_key_secret')
    )->regionId('cn-hangzhou')
     ->asDefaultClient();

    try {
        $result = AlibabaCloud::rpc()
            ->product('Dysmsapi')
            ->scheme('https')
            ->version('2017-05-25')
            ->action('SendSms')
            ->method('POST')
            ->host('dysmsapi.aliyuncs.com')
            ->options([
                'query' => [
                    'RegionId' => 'cn-hangzhou',
                    'PhoneNumbers' => $notifiable->phone_number,
                    'SignName' => config('services.alibabacloud.sign_name'),
                    'TemplateCode' => config('services.alibabacloud.template_code'),
                    'TemplateParam' => json_encode(['name' => $this->user->name]),
                ],
            ])
            ->request();
        return $result->toArray();
    } catch (ClientException $e) {
        // 处理客户端异常
        Log::error($e->getErrorMessage());
    } catch (ServerException $e) {
        // 处理服务器异常
        Log::error($e->getErrorMessage());
    }
}

}

发送通知

在控制器或服务中调用通知:

php
use AppNotificationsRegisterSuccessNotification;</p>

<p>public function register(Request $request)
{
    $user = User::create($request->all());</p>

<pre><code>$user->notify(new RegisterSuccessNotification($user));

return response()->json(['message' => '注册成功']);

}

其他实现思路

使用Twilio发送短信

除了阿里云短信服务,还可以使用Twilio来发送短信。安装Twilio SDK:

bash
composer require twilio/sdk

然后,在.env文件中添加Twilio的配置信息:

env
TWILIO_ACCOUNT_SID=your_account_sid
TWILIO_AUTH_TOKEN=your_auth_token
TWILIO_PHONE_NUMBER=your_phone_number

创建一个通知类并编写发送逻辑:

php
namespace AppNotifications;</p>

<p>use IlluminateBusQueueable;
use IlluminateNotificationsNotification;
use IlluminateContractsQueueShouldQueue;
use TwilioRestClient;</p>

<p>class RegisterSuccessNotification extends Notification implements ShouldQueue
{
    use Queueable;</p>

<pre><code>protected $user;

public function __construct($user)
{
    $this->user = $user;
}

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

public function toSms($notifiable)
{
    $client = new Client(config('services.twilio.account_sid'), config('services.twilio.auth_token'));

    $client->messages->create(
        $notifiable->phone_number,
        [
            'from' => config('services.twilio.phone_number'),
            'body' => "恭喜您,{$this->user->name},注册成功!"
        ]
    );
}

}

使用Nexmo发送短信

Nexmo也是一个常用的短信服务提供商。安装Nexmo SDK:

bash
composer require nexmo/client

.env文件中添加Nexmo的配置信息:

env
NEXMO_KEY=your_api_key
NEXMO_SECRET=your_api_secret
NEXMO_PHONE_NUMBER=your_phone_number

创建一个通知类并编写发送逻辑:

php
namespace AppNotifications;</p>

<p>use IlluminateBusQueueable;
use IlluminateNotificationsNotification;
use IlluminateContractsQueueShouldQueue;
use NexmoClient;</p>

<p>class RegisterSuccessNotification extends Notification implements ShouldQueue
{
    use Queueable;</p>

<pre><code>protected $user;

public function __construct($user)
{
    $this->user = $user;
}

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

public function toSms($notifiable)
{
    $client = new Client(new NexmoClientCredentialsBasic(config('services.nexmo.key'), config('services.nexmo.secret')));

    $client->message()->send([
        'to' => $notifiable->phone_number,
        'from' => config('services.nexmo.phone_number'),
        'text' => "恭喜您,{$this->user->name},注册成功!"
    ]);
}

}

我们可以在Laravel中轻松实现短信通知功能。无论是使用阿里云、Twilio还是Nexmo,Laravel的通知系统都提供了灵活的接口来支持多种通知渠道。希望能帮助你在项目中实现高效的短信通知功能。

Image

1. 本站所有资源来源于用户上传和网络,因此不包含技术服务请大家谅解!如有侵权请邮件联系客服!cheeksyu@vip.qq.com
2. 本站不保证所提供下载的资源的准确性、安全性和完整性,资源仅供下载学习之用!如有链接无法下载、失效或广告,请联系客服处理!
3. 您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容资源!如用于商业或者非法用途,与本站无关,一切后果请用户自负!
4. 如果您也有好的资源或教程,您可以投稿发布,成功分享后有积分奖励和额外收入!
5.严禁将资源用于任何违法犯罪行为,不得违反国家法律,否则责任自负,一切法律责任与本站无关

源码下载