laravel短信;laravel通知

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

文章来源网络,作者:运维,如若转载,请注明出处:https://shuyeidc.com/wp/67794.html<

(0)
运维的头像运维
上一篇2025-02-06 14:15
下一篇 2025-02-06 14:17

相关推荐

发表回复

您的邮箱地址不会被公开。必填项已用 * 标注