Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 960
rfc1484 Avatar asked Mar 02 '16 15:03

rfc1484


People also ask

Can you use query parameters in post?

POST should not have query param. You can implement the service to honor the query param, but this is against REST spec.

Can we use query string in post method?

A POST request can include a query string, however normally it doesn't - a standard HTML form with a POST action will not normally include a query string for example.

How do I send a POST request with guzzle?

Sending Requests You can create a request and then send the request with the client when you're ready: use GuzzleHttp\Psr7\Request; $request = new Request('PUT', 'http://httpbin.org/put'); $response = $client->send($request, ['timeout' => 2]);

How do you pass a parameter in a query?

To pass in parameter values, simply append them to the query string at the end of the base URL. In the above example, the view parameter script name is viewParameter1.


1 Answers

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()
like image 57
D.Dimitrioglo Avatar answered Sep 28 '22 08:09

D.Dimitrioglo