后台:
public function code()
{
$phone=\request()->get('phone');
$phoneReg='/^1[3-9]\d{9}$/';
$code=Cache::get('code'.$phone);
if ($phone==''){
return ['code'=>2001,'msg'=>'手机号不能为空'];
}
if (!preg_match($phoneReg,$phone)){
return ['code'=>2001,'msg'=>'手机号格式2错误'];
}
$time=Cache::get('time'.$phone);
if (time()-$time<10){
return ['code'=>2001,'msg'=>'10s后重新发送'];
}else{
$code=rand(1111,9999);
Cache::set('code'.$phone,$code);
Cache::set('time'.$phone,time());
}
$num=Cache::get('num'.$phone);
if ($num>3){
return ['code'=>2001,'msg'=>'获取次数过多,请你改天再试'];
}else{
Cache::set('num'.$phone,1);
Cache::increment('num'.$phone);
}
// $msg=$this->dispatch(new smsJob($phone));
// dd($code);
Cache::put('num'.$phone,0,60*60*24);
return ['code'=>200,'msg'=>'发送成功','data'=>$code];
}
小程序前端:
code(){
var phone=this.data.phone
if(phone==''){
wx.showToast({
title: '手机号不能为空',
icon: 'none',
});
return false
}
var phoneReg=/^1[3-9]\d{9}$/
if(!phoneReg.test(phone)){
wx.showToast({
title: '手1机号格式错误',
icon: 'none',
});
return false
}
wx.request({
url: 'http://www.ly.com/api/code',
data: {phone},
header: {'content-type':'application/json'},
method: 'GET',
dataType: 'json',
responseType: 'text',
success: (result)=>{
wx.showToast({
title:result.data.msg ,
icon: 'none',
});
console.log(result)
if(result.data.code==200){
var that=this
var num=60
var timer= setInterval(function(){
num--
that.setData({
codeName:num+'s后重新发送',
disabled:true
})
if(num<=0){
clearInterval(timer)
that.setData({
codeName:'重新发送',
disabled:false
})
}
},1000)
}
},
fail: ()=>{},
complete: ()=>{}
});
},