自动获取用户的openid (openid 唯一)
在做登录前我们首先要知道openid 是唯一的
session_key 是每次从新进入的时候还会刷新的(就是注销或删除等)
// 登录 let token = wx.getStorageSync('token') if(!token){ wx.login({ success: res => { // 发送 res.code 到后台换取 openId, sessionKey, unionId let code = res.code wx.request({ url: 'http://www.test.com/integral/login?code='+code, success:res=>{ wx.setStorageSync('token',res.data.data) } }) } }) }
后端
public function login(Request $request){ $code = $request->get('code'); $userInfo = sprintf(config('wx_login.login'),$code); $data = (new Curl())->geturl($userInfo); $getUserInfo = User::where('openid',$data['openid'])->first(); if(!$getUserInfo){ User::insert($data); $getUserInfo = User::where('openid',$data['openid'])->first(); $token = (new Token())->createToken($getUserInfo['id']); return ['code'=>3000,'msg'=>'注册成功','data'=>$token]; } $token = (new Token())->createToken($getUserInfo['id']); return ['code'=>3000,'msg'=>'登录成功','data'=>$token]; }
cnfig
return[ 'login'=>'https://api.weixin.qq.com/sns/jscode2session?appid=微信小程序号&secret=秘钥&js_code=%s&grant_type=authorization_code' ];
Service (封装一个curl)
function geturl($url){ $headerArray =array("Content-type:application/json;","Accept:application/json"); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch,CURLOPT_HTTPHEADER,$headerArray); $output = curl_exec($ch); curl_close($ch); $output = json_decode($output,true); return $output; }
Token 我这里使用的是JWT
链接 PHP token验证_lmy2020start的博客-CSDN博客