小程序前端代码
function WXlogin(){ wx.login({ success: function (code) { wx.getUserInfo({ success:function(userInfo){ //发起请求 wx.request({ url: domain+\'wxopen/wxapp/login\', method:"POST", data:{ code: code.code, encryptedData: userInfo.encryptedData, iv: userInfo.iv, rawData: userInfo.rawData, signature: userInfo.signature, appid:extConfig.appid }, success:function(res){ console.log(res,\'login\') wx.setStorageSync(\'session_3rd\', res.data);//存token } }) } }) } }); } //重新登陆更新 function reLogin(sess_3rd){ console.log(sess_3rd,\'s3rd\') //发起请求 wx.request({ url: domain + \'wxopen/wxapp/reLogin\', method: "POST", data: { session: sess_3rd, }, success: function (res) { console.log(res, \'relogin\') if(res.data == 0){ WXlogin();//重新登陆 }else{ wx.setStorageSync(\'session_3rd\', res.data);//存token } } }) }
后端PHP代码
function login(){ $code = input(\'code\');//登陆凭证 $encryptedData = input(\'encryptedData\');// $iv = input(\'iv\');// $rawData = input(\'rawData\');// $signature = input(\'signature\');// $appid = input(\'appid\'); //第三方token,换取session_key $comp_token = $this->component->getAccessToken(); $url =\'https://api.weixin.qq.com/sns/component/jscode2session?appid=\'.$appid.\'&js_code=\'.$code.\'&grant_type=authorization_code&component_appid=\'.$this->appid.\'&component_access_token=\'.$comp_token; $result = send_get($url); $result = json_decode($result,true); trace($result,\'登陆返回\'); //根据业务需要对数据包进行签名校验,确保数据的完整性。 $signature2 = sha1( $rawData.$result[\'session_key\']); if ($signature != $signature2){ return [\'msg\'=>\'签名检验失败\',\'status\'=>0]; } //解密获得用户的完整敏感信息 $pc = new wxappBizDataCrypt($appid, $result[\'session_key\']); $errCode = $pc->decryptData($encryptedData, $iv, $data ); if ($errCode == 0) { $data = json_decode($data,true); $data[\'appid\'] = $data[\'watermark\'][\'appid\']; $session_3rd = bin2hex(random_bytes(9)); $data[\'session_3rd\'] = $session_3rd; //检查用户是否存在,进行增加更新操作 $userInfo = new UserInfo(); $users = $userInfo::get([\'openid\'=>$result[\'openid\']]); if ($users){ $ret = $userInfo->allowField(true)->isUpdate(true)->save($data,[\'openid\'=>$result[\'openid\']]); }else{ $ret = $userInfo->allowField(true)->isUpdate(false)->save($data); } if ($ret) return $session_3rd; } return 0; } //登陆过期,重新登陆 function reLogin(){ $session = input(\'session\'); $users = $this->user->where([\'session_3rd\'=>$session])->find(); if ($users){ $session_3rd = bin2hex(random_bytes(9)); $ret = $this->user->where(\'id\',$users[\'id\'])->update([\'session_3rd\'=>$session_3rd]);//更新3rd return $session_3rd; }else{ return 0; } }
请发表评论