1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > Laravel8 小程序手机号获取验证码登录

Laravel8 小程序手机号获取验证码登录

时间:2023-10-24 20:47:49

相关推荐

Laravel8 小程序手机号获取验证码登录

关于小程序的登录,那指定受不了JWT,大家要记得在框架中装好JWT去配置

下面就直接上代码

控制器:

<?phpnamespace App\Http\Controllers\api;use App\Http\Controllers\Controller;use App\Models\Fillable;use App\Models\User;use App\Service\SendCode;use App\Service\Token;use Illuminate\Http\Request;use Illuminate\Support\Facades\Validator;class LoginController extends Controller{protected $param;public function __construct(Request $request){$this->param = $request;}/*** 发送手机验证码*/public function sendCode(){$phone = $this->param['phone'];//验证if(!$phone || empty($phone)){return ['code'=>4000,'msg'=>'手机号不能为空','data'=>''];}//判断手机号格式$pregRes = preg_match_all('/^1[358]\d{9}$/',$phone);if(!$pregRes){return ['code'=>4000,'msg'=>'手机号格式不正确','data'=>''];}//判断该手机号是否为白名单$fillableId = Fillable::where('phone',$phone)->first();if(empty($fillableId)){return ['code'=>4000,'msg'=>'手机号无法登录','data'=>''];}//获取缓存$time = date('Y-m-d',cache()->get($phone.'_time'));$count = cache()->get($phone.'_count') ? : 0;//判断每天发送次数if($count>5){return ['code'=>4000,'msg'=>'发送已达上限','data'=>''];}//当天的时间$newDay = date('Y-m-d',time());if($newDay>$time){$count = 1;}else{$count++;}//生成验证码$captcha = rand(1300,9888);//发送手机号// $statusCode = (new SendCode())->sendCode($phone,$captcha);// //获取错误码对应的错误信息// $statusArr = config('code.status');// if($statusCode!=0){// return ['code'=>4005,'msg'=>$statusArr[$statusCode],'data'=>''];// }//存储到缓存中cache()->set($phone,$captcha,300);//5分钟后过期cache()->set($phone.'_time',time(),60*24);//记录最后一次发送时间cache()->set($phone.'_count',$count,60*24);//记录次数//return ['code'=>200,'msg'=>$statusArr[$statusCode],'data'=>$captcha];return ['code'=>200,'msg'=>'短信发送成功','data'=>$captcha];}/*** 手机号登录*/public function phoneLogin(){$param = $this->param->all();//验证$validate = Validator::make($param,['phone' => 'required','code' => 'required|min:4|max:4']);if($validate->fails()){$error = $validate->errors();return ['code'=>4000,'msg'=>$error->first(),'data'=>''];}//判断手机号格式$pregRes = preg_match_all('/^1[358]\d{9}$/',$param['phone']);if(!$pregRes){return ['code'=>4000,'msg'=>'手机号格式不正确','data'=>''];}//取出验证码$captcha = cache()->get($param['phone']);//验证码判断if($param['code'] != $captcha){return ['code'=>4002,'msg'=>'验证码错误','data'=>''];}//判断用户是否注册$userInfo = User::where('phone',$param['phone'])->first();if(!$userInfo){//执行注册$userInfo = User::create(['phone' => $param['phone']]);}//生成token$token = (new Token())->createToken($userInfo->id);cache()->set('uid',$userInfo->id,7200);return ['code'=>200,'msg'=>'登录成功','data'=>$token];}}

服务层的话,我封装了两个,一个是验证码的,另一个是验证token

<?phpnamespace App\Service;class SendCode{public function sendCode($phone,$captcha){$smsapi = "/";$user = config('code.user'); //短信平台帐号$pass = config('code.pass'); //短信平台密码$content="《测试 短信内容》你的验证码是:".$captcha;//要发送的短信内容// $sendurl = $smsapi."sms?u=".$user."&p=".$pass."&m=".$phone."&c=".urlencode($content);$sendurl = sprintf(config('code.url'),$user,$pass,$phone,urlencode($content));$result =file_get_contents($sendurl);return $result;}}

<?phpnamespace App\Service;use Firebase\JWT\JWT;class Token{protected $key;public function __construct(){$this->key = 'xululu';}/*** 生成token*/public function createToken($uid){$time = time();$payload = array("iss" => "","aud" => "","iat" => $time,"nbf" => $time,"exp" => $time+7200,"uid" => $uid);//生成$token = JWT::encode($payload, $this->key);return $token;}/*** 验证token*/public function validateToken($token){try {//验证$decoded = JWT::decode($token, $this->key, array('HS256'));//返回用户idreturn $decoded->uid;}catch (\Exception $e){return 'token过期';}}}

然后是前台小程序部分,这里的部分样式我是用了lin-ui,感兴趣的朋友可以去看一下

<view>要交友</view><view>社区交友大平台</view><view class="weui-cell weui-cell_input"><input class="weui-input" bindinput="phone" placeholder="手机号"/></view><view class="weui-cell weui-cell_input"><input class="weui-input" bindinput="code" placeholder="验证码"/><l-button size="mini" bindtap="sendCode" type="success">发送验证码</l-button></view><l-button class="btn" bindtap="login" size="medium">登录</l-button>

// pages/indexs/indexs.jsPage({/*** 页面的初始数据*/data: {phone: '',code: ''},/*** 生命周期函数--监听页面加载*/onLoad: function (options) {},phone(e) {let phone = e.detail.valuethis.setData({phone})},//同步验证码code(e) {this.setData({code: e.detail.value})},//发送验证码sendCode(){let phone = this.data.phone;wx.request({url: '/api/send',data:{phone},success:ret=>{wx.showToast({title: ret.data.msg,icon:'error'})}})},login() {let phone = this.data.phone;let code = this.data.code;wx.setStorageSync('phone', phone)wx.request({url: '/api/login',data:{phone,code},method:'POST',success:ret=>{let data = ret.data;if(data.code!=200){wx.showToast({title:data.msg,icon:'error'})return false;}//token存储到本地wx.setStorageSync('token',data.data);wx.showToast({title: '登录成功',icon: 'success',duration: 2000,success: function () {setTimeout(function () {//要延时执行的代码wx.navigateBack({delta: 1,})}, 2000) //延迟时间}})}})wx.showToast({title: '登录成功',icon: 'success',duration: 2000,success: function () {setTimeout(function () {//要延时执行的代码wx.navigateBack({delta: 1,})}, 2000) //延迟时间}})}})

{"usingComponents": {"l-button":"/miniprogram_npm/lin-ui/button"}}

.weui-cell{display: flex;flex-direction: row;flex-wrap: nowrap;margin: 20px;padding-bottom: 5px;border-bottom: 1px #ccc solid;}.btn{margin-left: 120px;margin-top: 30px;}

这样的一个手机号验证码登录就写完了,有不会的或者有错误的地方欢迎找我哦

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。