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

<?php

namespace frontend\models;

use Yii;
use yii\base\Model; 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' => '\common\models\User', '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 yii\helpers\Html;
use yii\helpers\Url;
use yii\bootstrap\ActiveForm;
use frontend\assets\CountdownAsset; /* @var $this yii\web\View */
/* @var $form yii\bootstrap\ActiveForm */ 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}\n{beginWrapper}\n{input}\n{hint}\n{error}\n{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}\n{beginWrapper}\n{input}\n{hint}\n{error}\n{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}\n{beginWrapper}\n<div class=\"row\">\n<div class=\"col-xs-6\">\n{input}\n</div>\n<div class=\"col-xs-6\">\n" . '<button type="button" class="btn btn-default btn-sendmsg2" data-mobile-target="#changemobileform-mobile" data-loading-text="验证码发送中..." autocomplete="off">发送验证码</button>' . "\n</div>\n</div>{hint}\n{error}\n{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);
上一篇:spring boot +dubbo 踩坑记录


下一篇:Windows安装绿色版git管理软件GitStack 2.3.8