PHP 手机短信验证码 laravel 实现流程

PHP 手机短信验证码 laravel 实现流程

https://blog.csdn.net/uknow0904/article/details/80336941

本人在自己博客(Laravel)的注册部分 使用手机号注册,需要发送短信验证码。

 使用云片(https://www.yunpian.com/)的 短信服务提供商,当然具体短信服务提供商大家可以自由选择。

1,实现流程

输入手机号,点击获取验证码
提交正确的短信验证码后,注册完成

2,实现思路图

这里写图片描述

3,注册 云片,以及开发信息认证,模板设置,这里就不详细展开了

4, 安装 easy-sms,easy-sms 是安正超写的一个短信发送组件,利用这个组件,我们可以快速的实现短信发送功能。

 composer require "overtrue/easy-sms"
    //新建配置文件
    touch config/easysms.php

然后在 easysms.php 文件内 添加以下内容:

 <?php

   return [

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

           // 默认可用的发送网关
           'gateways' => [
               'yunpian',
           ],
       ],
       // 可用的网关配置
       'gateways' => [
           'errorlog' => [
               'file' => '/tmp/easy-sms.log',
           ],
           'yunpian' => [
               'api_key' => env('YUNPIAN_API_KEY'),
           ],
       ],


   ];

然后创建一个 ServiceProvider

  php artisan make:provider EasySmsServiceProvider

修改文件

app/providers/EasySmsServiceProvider.php

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Overtrue\EasySms\EasySms;

class EasySmsServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton(EasySms::class,function ($app){

            return new EasySms(config('easysms'));

        });

        $this->app->alias(EasySms::class,'easysms');
    }
}

最后 打开config/app.php 在 providers 中增加

 App\Providers\EasySmsServiceProvider::class,

5,获取云片的API_KEY

在 .env中配置 YUNPIAN_API_KEY,注意下面需要替换为你自己的 key

6,控制器代码 获取验证码(将code 以及key存入缓存)

public function getVerificationCode($request)
    {
        if(FALSE === $this->validateApiRequest($request->all(),
                ['mobile' => 'required|regex:/^1[34578]\d{9}$/|unique:users'],[
                    'mobile.required'=>'请输入手机号',
                    'mobile.regex'=>'手机号格式不正确',
                    'mobile.unique'=>'手机号已存在'
                ])){
            return false;
        }

        $mobile = trim($request->get('mobile'));
       $code = str_pad(random_int(1,9999),4,0,STR_PAD_LEFT);


        try{
             $easySms->send($mobile,
                ['content'=>"【UKNOW】您的验证码是{$code}。如非本人操作,请忽略本短信"]             );

        }catch(\GuzzleHttp\Exception\ClientException $exception){

            $response = $exception->getResponse();
            $result =json_decode($response->getBody()->getContents(),true);
            $this->setMsg($result['msg']?? '短信发送异常');
            return false;
        }

        $key = 'verificationCode'.str_random(15);
        $expiredAt = now()->addMinutes(1);
        Cache::put($key,['mobile'=>$mobile,'code'=>$code],$expiredAt);

        return [
            'verification_key'=>$key,
            'expiredAt'=>$expiredAt->toDateTimeString(),
            'verification_code'=>$code
            ];
    }

7,对比验证码

public function userStore($mobile, $verification_key,$code,$password,$password_confirmation)
    {

        $params = [
            'mobile'=>$mobile,
            'verification_key'=>$verification_key,
            'code'=>$code,
            'password'=>$password,
            'password_confirmation'=>$password_confirmation
        ];
        //参数判断
        if (
            FALSE === $this->validateApiRequest($params, [
                'mobile'  => 'required|regex:/^1[34578]\d{9}$/|unique:users',
                'code'    => 'required',
                'verification_key'=>'required',
                'password'     => 'required|min:6|confirmed',
                'password_confirmation' => 'required',
            ], [
                'mobile.required' => '请输入手机号',
                'mobile.regex'    => '手机号格式不正确',
                'mobile.unique'   => '手机号已存在',
                'code.required'   => '请输入短信验证码',
                'password.required'    => '请输入密码',
                'password.min'         => '密码不得小于6位',
                'password.confirmed'   => '密码前后不一致',
                'password_confirmation.required'=>'请再次输入密码',
                'verification_key.required'=>'请输入短信验证码'
            ])
        ) {
            return false;
        }

        $verifyData = Cache::get($verification_key);
        if( !$verifyData){
            $this->setMsg('验证码已失效');
            return false;
        }
        if(!hash_equals($code,(string)$verifyData['code'])){
            $this->setMsg('验证码错误');
            return false;
        }

        Cache::forget($verification_key);
        $user = User::create([
            'mobile'=>$mobile,
            'password'=>bcrypt($password)
        ]);
        if(!$user){
            $this->setMsg('注册失败');
            return false;
        }
        return true;
    }

 

 
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/113030.html原文链接:https://javaforall.net

(0)
上一篇 2021年10月25日 下午9:00
下一篇 2021年10月25日 下午10:00


相关推荐

  • Java开发手册之日志规约[通俗易懂]

    Java开发手册之日志规约[通俗易懂]Java开发手册之日志规约

    2022年4月22日
    41
  • janus流媒体服务器搭建

    janus流媒体服务器搭建准备 ubuntu20 虚拟机注意 切换 root 用户 sudosu 否则以下很多命令要加 sudo linux 新版本推荐 apt 低版本 apt get 还能用 一安装工具 aptinstallgi tools 二安装 janus 依赖库 aptinstallli devapt

    2026年3月16日
    2
  • POJ 2996 Help Me with the Game (模拟)

    POJ 2996 Help Me with the Game (模拟)题目链接:http://poj.org/problem?id=2996POJ训练计划中的模拟都是非常棒的模拟,也非常有代表性。这个题讲的是给你一个国际象棋棋盘,敲代码打印出黑白两方的棋子。以及棋子的坐标。可是须要注意的国际棋盘的坐标问题例如以下图这个国际棋盘能够看到数字轴和字母轴的方向以及增减关系。所以在这个题的统计的时候须要进行坐标转换。由于已经做过类似的方法…

    2022年8月12日
    11
  • 电脑爱好者2012年全彩高清PDF

    电脑爱好者2012年全彩高清PDF电脑爱好者2012年第01期.pdf电脑爱好者2012年第02期全彩高清PDF免费高速下载.pdf电脑爱好者2012年第03期全彩高清PDF免费高速下载.pdf电脑爱好者2012年第04期全彩高清PD…

    2022年4月27日
    45
  • python 阅读器,文字转语音—-新技能你get到了吗

    python 阅读器,文字转语音—-新技能你get到了吗

    2021年9月17日
    57
  • 【金融市场基础知识】——中国的金融体系(一)[通俗易懂]

    【金融市场基础知识】——中国的金融体系(一)[通俗易懂]阅读之前看这里????:博主是一名正在学习证券知识的学生,在每个领域我们都应当是学生的心态,也不应该拥有身份标签来限制自己学习的范围,所以博客记录的是在学习过程中一些总结,也希望和大家一起进步,在记录之时,未免存在很多疏漏和不全,如有问题,还请私聊博主指正。博客地址:天阑之蓝的博客,学习过程中不免有困难和迷茫,希望大家都能在这学习的过程中肯定自己,超越自己,最终创造自己。目录中国的金融体系(一)一、中国金融市场的历史、现状及影响因素1、新中国成立以来我国金融市场的发展历史★2、我国金融市场的发展现状

    2022年5月27日
    71

发表回复

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

关注全栈程序员社区公众号