微信小程序实现手机号登录
本文实例为大家分享了微信小程序实现手机号登录的具体代码,供大家参考,具体内容如下
1.wxml
<form bindsubmit="formsubmit"> <view>手机号<input type="text" placeholder="请输入手机号" bindinput="getphone" name="phone"/></view> <view> 验证码<input type="text" placeholder="请输入验证码" name="code"/> <button disabled="{{disabled}}" bindtap="click">{{message}}</button> </view> <button form-type="submit">登录</button> </form>
2.js(正则验证、倒计时、验证码)
/** * 页面的初始数据 */ data: { phone:'', message:"获取验证码", disabled:false }, getphone:function(e){ this.setData({ phone:e.detail.value }) }, click(){ var that = this let phone = this.data.phone; console.log(phone) if(!(/^(13|15|17|18|19)\d{9}$/.test(phone))){ wx.showToast({ title: '手机号不正确', icon:'none' }) } if((/^(13|15|17|18|19)\d{9}$/.test(phone))){ //定时任务 var souse = 30 var timer = setInterval(function(){ that.setData({ message:souse + "秒后重试", disabled:true }) souse -- if(souse == 0){ that.setData({ message:"发送验证码", disabled:false }) clearInterval(timer) } },1000) wx.request({ url: 'http://www.wenk.com/index.php/admin/sendCode', //仅为示例,并非真实的接口地址 data: { phone }, success (res) { console.log(res) } }) } },
3.提交表单
formsubmit(e){ console.log(e) let phone = e.detail.value.phone let code = e.detail.value.code wx.request({ url: 'http://www.wenk.com/admin/login', //仅为示例,并非真实的接口地址 method:'post', data: { code, phone }, success (res) { let id = res.data.data.id wx.setStorageSync('id',id) wx.navigateTo({ url: '/pages/list/list', }) } }) },
4.验证码API接口
public function sendCode() { $phone = input('phone'); //限制用户30秒内只能发送一次 $send_time = Cache::get('time_key'); //判断是否发送过 if (time() - $send_time < 30){ return json(['code' => 500,'msg'=> '30秒内只能发送一次','data' => []]); } if (empty($send_time)){ $time = time(); Cache::set('time_key',$time,30); } //调用验证码接口 $res = Cond::sendCode($phone);//封装的逻辑层 if (!$res){ return json(['code' => 200,'msg' => '发送成功','data' => $res]); } }
5.登录API接口
public function login() { $data = input(); $user = (new \app\admin\model\Login())->where('phone',$data['phone'])->find(); if ($user == null){ //如果第一次登录,这里则改为添加入库 return json(['code' => 2001,'msg' => '账号不存在','data' => []]); } $code = Cache::get('code'); if ($code != $data['code']){ return json(['code' => 2001,'msg' => '验证码错误','data' => []]); } // $id = $user['id']; // $token = Jwt::jwt(); return json(['code' => 200,'msg' => '登陆成功','data' => $user]); }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
赞 (0)