PHP开发APP传code授权登入
/** * 获取微信用户信息 */ public function getWechatInfoByAPP($code) { if (!$code) returnMsg(501); $app_id = ''; // 开放平台APP的id $app_secret = ''; // 开放平台APP的secret $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$app_id}&secret={$app_secret}&code={$code}&grant_type=authorization_code"; $data = $this->curl_get($url); //{ // "access_token": "ACCESS_TOKEN", // "expires_in": 7200, // "refresh_token": "REFRESH_TOKEN", // "openid": "OPENID", // "scope": "SCOPE", // "unionid": "o6_bmasdf6_2sgVt7hZDFPfL" //} if ($data['code'] != 200 || !isset($data['data'])) { return ['code' => "500", 'msg' => "登录错误" . $data['errmsg']]; } $data = $data['data']; if (isset($data['errcode']) && $data['errcode']) { return ['code' => "502", 'msg' => "code错误," . $data['errmsg']]; } // 请求用户信息 $info_url = "https://api.weixin.qq.com/sns/userinfo?access_token={$data['access_token']}&openid={$data['openid']}"; $user_info = $this->curl_get($info_url); if ($user_info['code'] != 200 || !isset($user_info['data'])) { return ['code' => "500", 'msg' => "登录错误" . $user_info['errmsg']]; } $data = $user_info['data']; if (!isset($data['openid']) || !isset($data['nickname']) || !isset($data['headimgurl'])) { return ['code' => "500", 'msg' => "APP登录失败,网络繁忙"]; } return ['code' => 200, 'data' => $data]; } // API public function appLogin() { $code = $_POST['code']; $user_wechat_info = $this->getWechatInfoByAPP($code); print_r($user_wechat_info); } // curl get请求 public function curl_get($url) { $header = [ 'Accept: application/json', ]; $curl = curl_init(); // 设置抓取的url curl_setopt($curl, CURLOPT_URL, $url); // 设置头文件的信息作为数据流输出 curl_setopt($curl, CURLOPT_HEADER, false); // 超时设置,以秒为单位 curl_setopt($curl, CURLOPT_TIMEOUT, 1); // 超时设置,以毫秒为单位 // curl_setopt($curl, CURLOPT_TIMEOUT_MS, 500); // 设置请求头 curl_setopt($curl, CURLOPT_HTTPHEADER, $header); // 设置获取的信息以文件流的形式返回,而不是直接输出。 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 执行命令 $data = curl_exec($curl); $error = curl_error($curl); curl_close($curl); // 显示错误信息 if ($error) { return ['code' => 500, 'msg' => $error]; } else { return ['code' => 200, 'msg' => 'success', 'data' => json_decode($data, true)]; } }