Laravel下的短信验证码注册

1.需求

通过短信验证码验证进行注册操作

2.准备工作

  1. 本篇文章用的是阿里云短信服务所以先去阿里云申请短信的签名和模板当签名和模板都通过审核后就可以正常使用短信业务。

  2. 创建AccessKey

    获取AccessKey ID和Access Key Secret

    至此我们在阿里云上的操作就结束了,现在开始在我们代码里进行配置。

3.正式操作

  • 创建一个laravel项目,具体创建方法参照laravel官方文档
  • 在你的laravel项目根目录下运行

composer require toplan/laravel-sms:~2.6

  • 注册服务提供器

在config/app.php文件中providers数组里加入:

Toplan\PhpSms\PhpSmsServiceProvider::class,
Toplan\Sms\SmsManagerServiceProvider::class,


在config/app.php文件中的aliases数组里加入

'PhpSms' => Toplan\PhpSms\Facades\Sms::class,
'SmsManager' => Toplan\Sms\Facades\SmsManager::class,

  • 生成配置文件和migration文件
php artisan vendor:publish --provider="Toplan\PhpSms\PhpSmsServiceProvider"
php artisan vendor:publish --provider="Toplan\Sms\SmsManagerServiceProvider"

执行完这一步后,config下会多出两个配置文件,分别为phpsms.phplaravel-sms.php

  • 配置参数

打开phpsms.php

然后再往下翻找到agents数组,因为是用的阿里云,所以就在Aliyun数组下进行配置

accessKeyIdaccessKeySecret 是在之前的阿里云准备工作里有获取到的
signName就是你阿里云短信服务的签名名称。将这些填入。

  • 然后打开laravel-sms.php,找到templates数组,将你的模板CODE填入(模板CODE就是你之前阿里云短信服务里申请的)

  • 将封装好的laravel-sms.js文件放入你laravel项目里的/public/js

  • laravel-sms.js代码如下

/*
 * send verify sms
 *---------------------------
 * top lan <[email protected]>
 * https://github.com/toplan/laravel-sms
 * --------------------------
 * Date 2015/06/08
 */
(function($){
    $.fn.sms = function(options) {
        var self = this;
        var btnOriginContent, timeId;
        var opts = $.extend(true, {}, $.fn.sms.defaults, options);
        self.on('click', function (e) {
            btnOriginContent = self.html() || self.val() || '';
            changeBtn(opts.language.sending, true);
            send();
        });

        function send() {
            var url = getUrl();
            var requestData = getRequestData();
            $.ajax({
                url     : url,
                type    : 'post',
                data    : requestData,
                success : function (data) {
                    if (data.success) {
                        timer(opts.interval);
                    } else {
                        changeBtn(btnOriginContent, false);
                        opts.notify.call(null, data.message, data.type);
                    }
                },
                error   : function(xhr, type){
                    changeBtn(btnOriginContent, false);
                    opts.notify.call(null, opts.language.failed, 'request_failed');
                }
            });
        }

        function getUrl() {
            return opts.requestUrl ||
                '/laravel-sms/' + (opts.voice ? 'voice-verify' : 'verify-code')
        }

        function getRequestData() {
            var requestData = { _token: opts.token || '' };
            var data = $.isPlainObject(opts.requestData) ? opts.requestData : {};
            $.each(data, function (key) {
                if (typeof data[key] === 'function') {
                    requestData[key] = data[key].call(requestData);
                } else {
                    requestData[key] = data[key];
                }
            });

            return requestData;
        }

        function timer(seconds) {
            var btnText = opts.language.resendable;
            btnText = typeof btnText === 'string' ? btnText : '';
            if (seconds < 0) {
                clearTimeout(timeId);
                changeBtn(btnOriginContent, false);
            } else {
                timeId = setTimeout(function() {
                    clearTimeout(timeId);
                    changeBtn(btnText.replace('{{seconds}}', (seconds--) + ''), true);
                    timer(seconds);
                }, 1000);
            }
        }

        function changeBtn(content, disabled) {
            self.html(content);
            self.val(content);
            self.prop('disabled', !!disabled);
        }
    };

    $.fn.sms.defaults = {
        token       : null,
        interval    : 60,
        voice       : false,
        requestUrl  : null,
        requestData : null,
        notify      : function (msg, type) {
            alert(msg);
        },
        language    : {
            sending    : '短信发送中...',
            failed     : '请求失败,请重试',
            resendable : '{{seconds}} 秒后再次发送'
        }
    };
})(window.jQuery || window.Zepto);
  • 在你需要使用验证码的地方引入该JS
<script src="laravel-sms.js"></script>

因为laravel-sms.js是用Jquery写的,所以需要在HTML界面的<body>里引入在线Jquery

<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>

然后紧接着写HTML界面

  • 在控制器里加入以下代码来验证短信验证码输入和发送的是否匹配
			//验证数据
            $validator = Validator::make($request->only('mobile', 'verifyCode'), [
              //验证规则
                'mobile' => 'confirm_mobile_not_change|confirm_rule:mobile_required',
                'verifyCode' => 'required|verify_code',
                //more...
            ],
            [
                //自定义错误消息
            'mobile.required'=>"手机号不能为空",
            'mobile.confirm_mobile_not_change'=>"手机号已变更,请重新发送验证码",
            'mobile.confirm_rule'=>"手机号不能为空",
            'verifyCode.required'=>"验证码不能为空",
            'verifyCode.verify_code'=>"验证码错误",
            ]);
            //如果不匹配输出错误
            if ($validator->fails()) {
                //验证失败后建议清空存储的发送状态,防止用户重复试错
                \SmsManager::forgetState();
                return redirect()->back()->withErrors($validator);
            }
            //如果匹配,你的逻辑
            ...

参考文章:https://github.com/toplan/laravel-sms

发布了17 篇原创文章 · 获赞 25 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_41800559/article/details/93890294