时间:2021-07-01 10:21:17 帮助过:14人阅读
首先,看一下微信的登录流程图 (推荐学习:PHP视频教程)
步骤:在客户端获取当前登录微信用户的登录凭证(code)。使用该凭证向微信服务器换取该微信用户的唯一标识(openid)和会话密钥(session_key)。引用微信加解密,获取用户信息。
注意:
1.未进行登录验证。
2.引用加解密是,路径要正确。
//未授权用户,请求微信接口,进行授权,获取用户信息 public function saveUser() { $appid = "自己的appid" ; $code = $this->input->post('code'); if (empty($code)){ return $this->fail('','code不能为空'); } $encryptedData = $this->input->post('encryptedData'); if (empty($encryptedData)){ return $this->fail('','encryptedData不能为空'); } $iv = $this->input->post('iv'); if (empty($iv)){ return $this->fail('','iv不能为空'); } $apiData = $this->getApiData($code); if(!isset($apiData['errcode'])){ $sessionKey = $apiData['session_key']; //获取sessionKey 进行解密 $userifo = new WXBizDataCrypt($appid, $sessionKey); $errCode = $userifo->decryptData($encryptedData, $iv, $data ); //保存 if ($errCode == 0) { $data = json_decode($data,true); $userData = [ 'nickname' =>$data['nickName'], 'headimg' =>$data['avatarUrl'], 'unionid' =>$data['unionId'], 'openid' =>$data['openId'], 'c_time' =>time(), ]; $result = $this->AppUserModel->get(['openid'=>$data['openId']]); if ($result){ $this->AppUserModel->update($userData,['openid'=>$data['openId']]); $returnData['uid']=$result['id']; return $this->success($returnData,'已授权'); }else{ $userDataId = $this->AppUserModel->add($userData); if ($userDataId){ $returnData['uid']=$userDataId; return $this->success($returnData,'已授权'); }else{ return $this->fail('','授权失败'); } } } }else{ return $this->fail($apiData,'获取用户信息失败'); } }
//获取openid public function getApiData($code) { $appid = "自己的appid" ; $secret = "自己的secret"; $URL = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code"; $apiData=file_get_contents($URL); return json_decode($apiData,true); }
未避免多次获取。在登录之前先进行验证。
//获取用户是否已经授权 public function userId() { $code = $this->input->get('code'); if (empty($code)){ return $this->fail('','code不能为空'); } $apiData = $this->getApiData($code); if (!isset($apiData['errcode'])){ $openID= $apiData['openid']; $userData = $this->AppUserModel->get(['openid'=>$openID]); if (empty($userData)) { return $this->fail('','未授权'); }else{ //这边保存sessionKey ,方便后面手机号码授权 $sessionKey = $apiData['session_key']; $mc = &load_cache('redis'); $mc->save('session_key', $sessionKey, 3600); $returnData = [ 'uid'=>$userData['id'], 'type'=>$userData['type'] ]; return $this->success($returnData,'已授权'); } }else { return $this->fail('','获取openid失败'); } }
以上就是php能开发小程序吗的详细内容,更多请关注Gxl网其它相关文章!