Laravel学习-短信验证码

1.安装拓展包    overtrue/easy-sms

地址:   overtrue/easy-sms – Packagist

安装:  

composer require overtrue/easy-sms

创建控制器

php artisan make:controller Api/BindController

BindController.php

<?php

namespace App\Http\Controllers\Admin;

use App\Events\SendSms;
use App\Http\Controllers\Controller;
use Doctrine\Common\Cache\Cache;
use Illuminate\Http\Request;
use Overtrue\EasySms\EasySms;

class BindController extends Controller
{
    public function send(Request $request)
    {
        // 使用事件派发 发送验证码 Providers\EventServiceProvider\$listen下
        SendSms::dispatch($request->input('phone'), '绑定手机');
    }

    public function updatePhone(Request $request)
    {
        $request->validate([
            'phone' => 'required',
            'code'  => 'required'
        ]);

        // 验证code是否正确
         if (\cache('phone_code_'.$request->input('phone')) !=  $request->input('code')) {
             return response()->json(['code' => 500]);
         }

    }
}

在阿里云里添加用户还要添加权限, 只有分配了权限, 才能使用这里的数据

Laravel短信验证码

Laravel短信验证码


优化: 把短信的config需要抽离出来

在config下新建 sms.php

<?php
return [
    // HTTP 请求的超时时间(秒)
    'timeout' => 5.0,

    // 默认发送配置
    'default' => [
        // 网关调用策略,默认:顺序调用
        'strategy' => \Overtrue\EasySms\Strategies\OrderStrategy::class,

        // 默认可用的发送网关
        'gateways' => [
            'aliyun',
        ],
    ],
    // 可用的网关配置
    'gateways' => [
        'errorlog' => [
            'file' => '/tmp/easy-sms.log',
        ],
        'aliyun' => [
            'access_key_id' => env('SMS_AK'),
            'access_key_secret' => env('SMS_SK'),
            'sign_name' => '',
        ]
    ],
];

在.env中添加

SMS_AK=
SMS_SK=

使用事件派发 发送验证码 Providers\EventServiceProvider\$listen里面
protected $listen = [
	Registered::class => [
		SendEmailVerificationNotification::class,
	],
	'App\Events\OrderShoped' => [
		'App\Listeners\SendShopToUser',
	],
	'App\Events\SendSms' => [
		'App\Listeners\SendSmsListener',
	],
];

然后执行  php artisan event:generate 可以生成监听文件

SendSms.php

<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class SendSms
{
    use Dispatchable, InteractsWithSockets, SerializesModels;
    public $phone;
    public $product;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($phone, $product)
    {
        $this->phone = $phone;
        $this->product = $product;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('channel-name');
    }
}

SendSmsListener.php

<?php

namespace App\Listeners;

use App\Events\SendSms;
use Doctrine\Common\Cache\Cache;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Overtrue\EasySms\EasySms;

class SendSmsListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  SendSms  $event
     * @return void
     */
    public function handle(SendSms $event)
    {
        $config = config('sms');
        $easySms = new EasySms($config);
        $code = rand(1000, 9999);
        // 缓存验证码
        Cache::put('phone_code_'.$event->phone, $code, now()->addMinutes(15));
        try {
            $easySms->send(13188888888, [
                'content'  => '您的验证码为: ',
                'template' => $config['template'],
                'data' => [
                    'code' => $code
                ]
            ]);
        } catch (\Exception $e) {
            return $e->getExceptions();
        }
    }
}

TODO:

使用队列

检查env中 QUEUE_CONNECTION=database



版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/TO_Web/article/details/120741466