无法打开流:HTTP 请求失败! HTTP/1.0 400 错误请求 - OAuth 2.0 POST

问题描述 投票:0回答:3

我正在为我的大学项目使用 YouTube API,但不断收到错误消息。在这里,我将它们发送到授权页面进行登录,当它们允许访问时,它会发回 $_GET['code'] 字符串。然后我将其与其他一些数据一起发送,它应该发回一个 JSON 对象。相反,我只是得到

警告:file_get_contents(https://accounts.google.com/o/oauth2/token) [function.file-get-contents]:无法打开流:HTTP 请求 失败的! HTTP/1.0 400 错误请求位于 http://www.example.net/callback.php 第 27 行

为了安全起见,我已将我的域名替换为 example.net

 urlencode($_GET['code']),
                'client_id' => urlencode('111522767640.apps.googleusercontent.com '),
                'client_secret' => urlencode('秘密'),
                'redirect_uri' => urlencode('http://example.net/callback.php'),
                'grant_type' => urlencode('授权码')
            )
        );

        $参数=
        数组('http' =>
            大批(
                '方法' => 'POST /o/oauth2/token HTTP/1.1',
                'header' => '主机:accounts.google.com
'。
                            '内容类型:application/x-www-form-urlencoded',
                '内容' => $postdata
            )
        );

        $context =stream_context_create($params);
        $result = file_get_contents('https://accounts.google.com/o/oauth2/token', false,$context);
        var_dump($_SESSION);
        var_dump($结果);
    }
    else //如果未设置代码,则用户一定是错误地来到这里或拒绝访问该程序
    {
        // header( '位置:www.example.net/error.php' ) ;
    }

?>
post https google-api file-get-contents http-status-code-400
3个回答
0
投票

file_get_contents
将向指定的 url 发出
GET
请求,但
oauth2/token
需要
POST
请求。

请参阅参考资料 Google OAuth2PHP HTTP


0
投票

如果您使用的是oauth2,请转到libraries/oauth2/provider.php并取消注释第182行显示的代码

            $ci = get_instance();
            $ci->load->spark('curl/1.2.1');
            $ci->curl
                ->create($url)
                ->post($params, array('failonerror' => false));

            $response = $ci->curl->execute();

0
投票

以下是如何正确执行 Google oAuth:

$config = (object) array(
  'CLIENT_ID' => 'AAAAA',
  'CLIENT_SECRET' => 'BBBBB',
  'REFRESH_TOKEN' => 'CCCCC',
);
$sJSON = file_get_contents('https://www.googleapis.com/oauth2/v4/token',FALSE,
  stream_context_create(array('http'=>array(
      'ignore_errors' => TRUE, // see errors in response instead of empty on error
      'method' => 'POST',
      'header' => array(
        'Content-Type: application/x-www-form-urlencoded'
      ),
      'content' => http_build_query(array(
        'grant_type' => 'refresh_token',
        'client_id' => $config->CLIENT_ID,
        'client_secret' => $config->CLIENT_SECRET,
        'refresh_token' => $config->REFRESH_TOKEN
      ))
  )))
);

然后您可以使用

json_decode()
$sJSON
解析为对象,然后检索
access_token
属性。

对于那些想知道如何获得

CLIENT_ID
CLIENT_SECRET
REFRESH_TOKEN
的人,请观看 此视频。这并不容易。就我而言,我需要为 Google Adwords API 执行此操作。因此,我必须从 https://ads.google.com/home/tools/manager-accounts 获取我的开发者令牌和登录客户 ID。然后,我必须使用 本指南 前往 https://console.developers.google.com/apis/credentials 来生成客户端 ID 和客户端密钥。然后,我按照此指南学习如何获取我的刷新令牌。

© www.soinside.com 2019 - 2024. All rights reserved.