Search code examples
postquery-stringguzzlegoogle-oauthguzzle6

How to make a Guzzle post using query string parameters


In a Google Oauth2 implementation I'm trying to exchange an authorization code for tokens using a guzzle call.

The following guzzle call works fine and returns the expected values:

 $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();

However this seems a dirty way to mount the post request.

I've tried the following way in order make it cleaner:

    $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();

However this second call generates a Malformed Json error message.

Any idea what I might be doing wrong or how can I debug what final url is being generated in the example above?


Solution

  • I tried without code parameter and it worked.

    $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()