php - 从 Google Api 请求用户电子邮件返回未经授权的 401 错误

标签 php http-headers file-get-contents oauth-2.0

我尝试连接到 google API,它返回: 无法打开流:HTTP 请求失败! HTTP/1.0 401 未授权 我请求访问 token 并返回 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);

是哪里写错了header,还是别的什么? 更新:$access_token 是我通过请求在 json 中获得的值。

最佳答案

  • 您不需要 GET 请求的内容类型 header 。
  • 您需要查询此 URL 以获取用户信息:https://www.googleapis.com/oauth2/v2/userinfo
  • 确保 $access_token 值包含正确授权的访问 token ,因为您需要您的用户通过 OAUth 2.0 流程。

所有这些都记录在那里:https://developers.google.com/accounts/docs/OAuth2Login

关于php - 从 Google Api 请求用户电子邮件返回未经授权的 401 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6558436/

相关文章:

php - 我怎样才能简化这个关于预订的查询?

php - 使用学说查询构建器表达查询

php - 如何在 Laravel 5 中测试自定义验证规则?

php - 强制下载 msi 文件

php - 更快的 fopen 或 file_get_contents?

javascript - Jquery AJAX 不传递 "POST"数据

php - 在 Excel 中查看多个 HTML 表格时无法设置 TD 宽度

node.js - 如何使用 Express/Nodejs 缓存单个资源

php - 使用file_get_contents()PHP函数的正确方法

php - 路由的 laravel file_get_contents 没有响应