我尝试连接到 google API,它返回:
failed to open stream: HTTP request failed! HTTP/1.0 401 Unauthorized
我请求访问令牌,它返回了我 xxx,之后我通过以下 PHP 代码连接到 Google API:
$opts = array('http' =>
array(
'method' => 'GET',
'header' => "Authorization: OAuth $access_token\r\nContent-Type: application/json\r\n",
)
);
$context = stream_context_create($opts);
$result = file_get_contents('https://www.googleapis.com/userinfo/email?alt=json',false,$context);
哪里有错误,是我写错了标题,还是其他什么? 更新: $access_token 是我通过请求以 json 形式获得的值。
$access_token
值包含正确授权的访问令牌,因为您需要用户经历 OAUth 2.0 流程。所有这些都记录在那里:https://developers.google.com/accounts/docs/OAuth2Login
检查如何在 php 中执行此操作,但是当将您的客户端登录到 Google 时,您必须设置 RequestPermission 参数,以便您可以从用户的个人资料中获取信息
请求权限:'https://www.googleapis.com/auth/userinfo.profile'
我使用 Angular(类型脚本)使用类似的方法,并在控制台上遇到“GET https://www.googleapis.com/oauth2/v3/userinfo 401(未经授权)”错误,我不知道是什么这里错误的是访问令牌是正确的并且令牌尚未过期!
私有 userInfoUrl = 'https://www.googleapis.com/oauth2/v3/userinfo';
getUserInfo(accessToken: string): Observable { const headers = new HttpHeaders().set('授权',
Bearer ${accessToken}
);
返回 this.http.get(this.userInfoUrl, { headers });
}