如何使用查询字符串参数制作 Guzzle 帖子

rfc*_*484 6 post query-string guzzle google-oauth guzzle6

在 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();
Run Code Online (Sandbox Code Playgroud)

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

我尝试了以下方法以使其更清洁:

    $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();
Run Code Online (Sandbox Code Playgroud)

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

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

D.D*_*glo 11

我试过没有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()
Run Code Online (Sandbox Code Playgroud)