Guzzle encodes Json body but I need form data
I am trying to post to in Googles oAuth server
order to do some authentication. Google does want this information in form data ( Content-Type: application/x-www-form-urlencoded
), but my client guzzle seems to insist (as far as I can tell) on creating a JSON body. I am using Guzzle 4. *
I changed my url to PostCatcher.io url
so I can see what is coming out (because for the rest of my life I can't figure out how to see the actual raw HTTP request that burns, spits out) and it looks like JSON is coming out.
My code (I'm using a test url right now):
$client = new GuzzleClient();
$url = "https://www.googleapis.com/" . "oauth2/v3/token";
$test_url = 'http://postcatcher.in/catchers/55602457b92ce203000032ae';
$request = $client->createRequest('POST', $test_url);
$request->setHeader('Content-Type', 'application/x-www-form-urlencoded'); //should be redundant
$body = $request->getBody();
$body->setField('code', $code);
$body->setField('client_id', $this->client_id);
$body->setField('client_secret', $this->client_secret);
$body->setField('redirect_url', $this->redicrect_url);
$body->setField('grant_type', $this->grant_type);
try {
$response = $client->send($request);
$result = $response->getBody();
return $result;
} catch (\Exception $exc) {
return $exc->getCode() . ' ' . $exc->getMessage();
}
The documentation says that this should be enough. What am I missing?
source to share
I found the problem. I did an upgrade to Guzzle 5. * I suspect this is not actually a solution.
I just need to look at the content of the response. So in the exception sentence, I added:
if ($exc->hasResponse()) {
return $exc->getResponse()->json();
}
Which gave me an error message from google. The error message was "Missing parameter: redirect_uri". And that's because I wrote url
instead uri
.
Fixed this and now everything is fine.
source to share