• yii2验证密码->*短信发送>手机短信发送频繁问题


    <?php
    
    namespace frontendmodels;
    
    use Yii;
    use yiiaseModel;
    
    class ChangeMobileSendRequestForm extends Model
    {
        public $mobile;
    
        /**
         * @inheritdoc
         */
        public function rules()
        {
            return [
                ['mobile', 'trim'],
                ['mobile', 'required'],
                ['mobile', 'match', 'pattern' => '/^1[3|5|7|8|][0-9]{9}$/'],
                ['mobile', 'unique', 'targetClass' => 'commonmodelsUser', 'message' => '该手机号已被注册!'],
                ['mobile', function ($attribute, $params) {
                    $session = Yii::$app->session;
                    if ($session->has('mobileChangeNext') && $session['mobileChangeNext'] > time()) {
                        $this->addError($attribute, '发送验证码过于频繁。');
                    }
                }]
            ];
        }
    
        /**
         * @inheritdoc
         */
        public function attributeLabels()
        {
            return [
                'mobile' => '手机号',
            ];
        }
    
        public function sendMsg($runValidation = true)
        {
            if ($runValidation && !$this->validate()) {
                return false;
            }
            
            $session = Yii::$app->session;
            $session['mobileChangeTimeout'] = time() + 600;
            $session['mobileChangeNext'] = time() + 60;
            $session['mobileChange'] = $this->mobile;
            $code=(string) mt_rand(100000, 999999);
            $session['mobileChangeVerifyCode'] = $code;
            $rest=Yii::$app->smser->send($this->mobile, "亲爱的用户,您的验证码是{$session['mobileChangeVerifyCode']},请于10分钟内使用。如非本人操作,请忽略该短信。");
            return ['rest'=>$rest,'code'=>$code];
        }
    }

    在控制器:

        public function actionSendMsg()
        {
            $model = new ChangeMobileSendRequestForm();
            Yii::$app->response->format = Response::FORMAT_JSON;
            
            $model->mobile = Yii::$app->request->post('mobile');
            $message = '';
            $res=$model->sendMsg();
            if ($res['rest']) {
                return ['status' => 'ok','code'=>$res['code']];
            } else {
                $message = $model->getFirstError('mobile') or $message = '验证码发送失败,请稍后再试!';
            }
            
            return ['status' => 'err', 'message' => $message];
        }

    view视图:

    <?php
    use yiihelpersHtml;
    use yiihelpersUrl;
    use yiiootstrapActiveForm;
    use frontendassetsCountdownAsset;
    
    /* @var $this yiiwebView */
    /* @var $form yiiootstrapActiveForm */
    
    CountdownAsset::register($this);
    
    $this->title = '手机';
    $this->params['breadcrumbs'][] = ['label' => '个人中心', 'url' => ['/i']];
    $this->params['breadcrumbs'][] = $this->title;
    ?>
    <?php if ($step === '1') :?>
    <div class="edit-form">
        <div class="callout callout-info">
            <p>当前手机号:<?= Yii::$app->user->identity->symbolMobile ?>,如需更换,请输入登录密码进行下一步。</p>
        </div>
        <?php $form = ActiveForm::begin([
            'layout' => 'horizontal',
            'fieldConfig' => [
                'template' => "{label}
    {beginWrapper}
    {input}
    {hint}
    {error}
    {endWrapper}",
                'horizontalCssClasses' => [
                    'label' => 'col-md-2',
                    'wrapper' => 'col-md-8',
                    'hint' => ''
                ]
            ]
        ]) ?>
            <?= $form->field($verifyPasswordForm, 'password')->passwordInput() ?>
            <div class="form-group">
                <div class="col-md-offset-2 col-md-8">
                    <?= Html::submitButton('下一步 <i class="fa fa-angle-double-right"></i>', ['class' => 'btn btn-warning', 'disabled' => true]) ?>
                </div>
            </div>
        <?php ActiveForm::end()?>
    </div>
    <?php elseif ($step === '2') :?>
    <div class="edit-form">
        <?php $form = ActiveForm::begin([
            'enableAjaxValidation' => true,
            'validateOnChange' => false,
            'validateOnBlur' => false,
            'layout' => 'horizontal',
            'fieldConfig' => [
                'template' => "{label}
    {beginWrapper}
    {input}
    {hint}
    {error}
    {endWrapper}",
                'horizontalCssClasses' => [
                    'label' => 'col-md-2',
                    'wrapper' => 'col-md-8',
                    'hint' => ''
                ]
            ]
        ]) ?>
            <div class="alert alert-success alert-msg-ok hidden" role="alert"></div>
            <div class="alert alert-danger alert-msg-err hidden" role="alert"></div>
            <?= $form->field($changeMobileForm, 'mobile') ?>
            <?= $form->field($changeMobileForm, 'verifyCode', ['template' => "{label}
    {beginWrapper}
    <div class="row">
    <div class="col-xs-6">
    {input}
    </div>
    <div class="col-xs-6">
    " . '<button type="button" class="btn btn-default btn-sendmsg2" data-mobile-target="#changemobileform-mobile" data-loading-text="验证码发送中..." autocomplete="off">发送验证码</button>' . "
    </div>
    </div>{hint}
    {error}
    {endWrapper}"]) ?>
            <div class="form-group">
                <div class="col-md-offset-2 col-md-8">
                    <?= Html::submitButton('<i class="fa fa-upload"></i> 提交', ['class' => 'btn btn-warning', 'disabled' => true]) ?>
                </div>
            </div>
        <?php ActiveForm::end()?>
    </div>
    <?php
    $urlSendMsg = Url::to(['/i/send-msg']);
    $js = <<<JS
    $('.btn-sendmsg2').click(function() {
        var target = $(this).attr('data-mobile-target');
        var mobile = $(target).val();
        var $form = $(this.form);
        $form.find('.alert-msg-err, .alert-msg-ok').addClass('hidden');
        $.ajax({
            url : '{$urlSendMsg}',
            type : 'post',
            data : {mobile : mobile},
            dataType : 'json',
            success : function (data) {
                if (data.status === 'ok') {
                    alert(data.code); //暂时文本发送取代短信发送
                    $form.find('.alert-msg-ok').html('验证码发送成功!<em>60</em> 秒后可再次发送!').removeClass('hidden');
                    $form.find('.btn-sendmsg2').prop('disabled', true);
                    $form.find('.alert-msg-ok em').countdown((new Date()).getTime() + 59000, function (event) {
                        $(this).text(event.strftime('%S'));
                    }).on('finish.countdown', function(event) {
                        $form.find('.alert-msg-ok').addClass('hidden');
                        $form.find('.btn-sendmsg2').prop('disabled', false);
                    });
                } else {
                    $form.find('.alert-msg-err').text(data.message).removeClass('hidden');
                }
            },
            error : function () {
                alert('验证码发送失败!');
            }
        });
    });
    JS;
    $this->registerJs($js);
    ?>
    <?php endif;?>
    <?php
    $script = <<<SCRIPT
    $("form input").bind("change keypress", function() {$(this.form).find("button").prop("disabled", false);$(this.form).find("input").unbind("change keypress")})
    SCRIPT;
    $this->registerJs($script);
  • 相关阅读:
    JavaScript三元运算符
    JavaScript相等运算符
    SQL 查询优化
    C# 平时碰见的问题【2】
    android 利用TrafficStats类获取本应用的流量
    android 输出.txt 文本换行问题
    【转载】input 中 type='text' 的提交问题
    Pycharm 使用 (一)
    SqlBulkCopy 插入100W条数据时 属性BatchSize的作用
    C# 平时碰见的问题【1】
  • 原文地址:https://www.cnblogs.com/xiong63/p/6733425.html
Copyright © 2020-2023  润新知