"error": "invalid_grant", "error_description": "Bad Request" when i am trying to login with gmail

380 Views Asked by At

this is my get access token method protected function getAccessToken($code) { $request = new \XLite\Core\HTTP\Request(static::TOKEN_REQUEST_URL);

$request->body = array(
    'code'          => $code,
    'client_id'     => $this->getClientId(),
    'client_secret' => $this->getClientSecret(),
    'redirect_uri'  => $this->getRedirectUrl(),
    'grant_type'    => 'authorization_code',
);


$response = $request->sendRequest();

$accessToken = null;
if (200 == $response->code) {
    $data = json_decode($response->body, true);
    $accessToken = $data['access_token'];
}

return $accessToken;

}

and here i got the response in my logs:

[06:35:13.000000] array (
  'request response from google' => 
  (object) array(
     '__CLASS__' => 'PEAR2\\HTTP\\Request\\Response',
     'code' => 400,
     'headers' => 
    (object) array(
       '__CLASS__' => 'PEAR2\\HTTP\\Request\\Headers',
       'iterationStyle' => 'lowerCase',
       'fields:protected' => 'Array(13)',
       'camelCase:protected' => NULL,
       'lowerCase:protected' => NULL,
    ),
     'cookies' => 
    array (
    ),
     'body' => '{
  "error": "invalid_grant",
  "error_description": "Bad Request"
}',
     'scheme' => 'https',
     'host' => 'accounts.google.com',
     'path' => '/o/oauth2/token',
     'uri' => 'https://accounts.google.com/o/oauth2/token',
     'port' => 443,
  ),
)

you can see the in response body if you required any thing else let me know

1

There are 1 best solutions below

2
Linda Lawton - DaImTo On

The post body is sent as a query string not an array

POST https://accounts.google.com/o/oauth2/token
code=AuthorizationCode&client_id=ClientId}&client_secret={ClientSecret}&redirect_uri=RedirectURI&grant_type=authorization_code

remember the code will expire in five minutes and can only be used once.

I beleave in php you should be using http-build-query for your post data.