getSessionKey($code); if (empty($sessionData['openid']) || empty($sessionData['session_key'])) { // throw new Exception('获取openid或session_key失败'); // return false; // return $this->msg(10001); return ['code'=>10002,'msg'=>'获取openid或session_key失败']; } // 2. 解密用户信息 $userInfo = $this->decryptData($encryptedData, $iv, $sessionData['session_key']); if(array_key_exists('phoneNumber',$userInfo)){ return ['code'=>0,'msg'=>'seccess','data'=>$userInfo]; }else{ return ['code'=>10002,'msg'=>'解密用户信息失败']; } // if (empty($userInfo['phoneNumber'])) { // // throw new Exception('获取手机号失败'); // }else{ // } // // 3. 保存或更新用户信息 // $user = User::where('openid', $sessionData['openid'])->find(); // if (!$user) { // $user = new User(); // $user->openid = $sessionData['openid']; // } // $user->phone = $userInfo['phoneNumber']; // $user->save(); // 返回成功信息 // return ['code' => 0, 'msg' => '登录成功', 'data' => $user]; // } catch (Exception $e) { // // 返回错误信息 // return ['code' => 500, 'msg' => $e->getMessage()]; // } } /** * 通过code获取openid和session_key * * @param string $code * @return array * @throws Exception */ private function getSessionKey($code) { $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$this->app_id}&secret={$this->app_secret}&js_code={$code}&grant_type=authorization_code"; $result = file_get_contents($url); $data = json_decode($result, true); if (isset($data['openid']) && isset($data['session_key'])) { return $data; } else { return ['code'=>10002,'msg'=>'获取openid或session_key失败']; } } /** * 解密用户信息 * * @param string $encryptedData * @param string $iv * @param string $sessionKey * @return array * @throws Exception */ private function decryptData($encryptedData, $iv, $sessionKey) { // require_once 'wx_crypt/WXBizDataCrypt.php'; // 引入微信解密类 // require_once env('root_path') . 'extend/wx_crypt/WXBizDataCrypt.php'; // dump(ROOT_PATH . 'extend\wx_crypt\wxBizDataCrypt.php'); require_once ROOT_PATH . 'extend\wx_crypt\wxBizDataCrypt.php'; $pc = new \WXBizDataCrypt($this->app_id, $sessionKey); $errCode = $pc->decryptData($encryptedData, $iv, $data); if ($errCode == 0) { return json_decode($data, true); } else { return ['code'=>10002,'msg'=>'解密用户信息失败('.$errCode.')']; // throw new Exception('解密失败: ' . $errCode); } } // 注册 }