【问题标题】:How to make a Guzzle post using query string parameters如何使用查询字符串参数制作 Guzzle 帖子
【发布时间】:2016-06-15 12:24:33
【问题描述】:

在 Google Oauth2 实现中,我尝试使用 guzzle 调用将授权码交换为令牌。

以下 guzzle 调用工作正常并返回预期值:

 $result = $this->client->post(
        'https://www.googleapis.com/oauth2/v3/token?code=<authorization_code>&redirect_uri=<redirect_uri>&client_id=<client_id>&client_secret=<client_secret>&grant_type=authorization_code')
->getBody()->getContents();

然而,这似乎是挂载发布请求的一种肮脏方式。

为了让它更干净,我尝试了以下方法:

    $result = $this->client->post(
        'https://www.googleapis.com/oauth2/v3/token',
        [
            'query' =>
                [
                    'code' => <authorization_code>,
                    'redirect_uri' => <redirect_uri>,
                    'client_id' => <client_id>,
                    'client_secret' => <client_secret>
                    'grant_type' => 'authorization_code',
                ]
        ]
    )->getBody()->getContents();

但是,第二次调用会生成 Malformed Json 错误消息。

知道我可能做错了什么,或者如何调试上面示例中生成的最终 url?

【问题讨论】:

  • 我的第一个猜测是正在发送的请求在某种程度上并不相同。我将从使用“调试”请求选项开始。将 true 值作为选项传递给您的客户端实例化或在您的发布请求中。

标签: post query-string guzzle google-oauth guzzle6


【解决方案1】:

我尝试不使用code 参数,它成功了。

$client = new \GuzzleHttp\Client();

$response = $client->post('https://www.googleapis.com/oauth2/v3/token', [
    'query' => [
        'client_id' => '...apps.googleusercontent.com',
        'client_secret' => 'secret',
        'refresh_token' => 'token',
        'grant_type' => 'refresh_token'
    ]
]);

$token = $response->getBody()->getContents()

【讨论】:

    【解决方案2】:

    您是否尝试过使用数组和http://php.net/json_encode

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-05
      • 2021-09-24
      • 2020-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-15
      • 1970-01-01
      相关资源
      最近更新 更多