首先,看一下微信的登入流程圖(推薦學習: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能開發小程式嗎的詳細內容。更多資訊請關注PHP中文網其他相關文章!