Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google OAuth2 error - Required parameter is missing: grant_type on refresh

I have built a prototype calendar synching system using the Google calendar API and it works well, except refreshing access tokens. These are the steps I have gone through:

1) Authorised my API and received an authorisation code.

2) Exchanged the authorisation code for Access Token and a RefreshToken.

3) Used the Calendar API until the Access Token expires.

At this point I try to use the Refresh Token to gain another Access Token, so my users don't have to keep granting access because the diary sync happens when they are offline.

Here's the PHP code, I'm using curl requests throughout the system.

$requestURL = "https://accounts.google.com/o/oauth2/token";
$postData = array("grant_type" => "refresh_token", 
                  "client_id" => $clientID,    
                  "client_secret" => $clientSecret, 
                  "refresh_token" => $refreshToken);

$headers[0] = 'Content-Type: application/json';

$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $requestURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));

$response = curl_exec($ch);
$responseArray = json_decode($response, TRUE);

The response i'm getting is:

[error] => invalid_request
[error_description] => Required parameter is missing: grant_type

No curl errors are reported.

I've tried header content-type: application/x-www-form-urlencoded, and many other things, with the same result.

I suspect it's something obvious in my curl settings or headers as every parameter mentioned in the Google documentation for this request is set. However, I'm going around in circles so would appreciate any help, including pointing out any obvious errors I've overlooked.

like image 701
Colin Martin Avatar asked Nov 19 '25 03:11

Colin Martin


1 Answers

your request should not post JSON data but rather query form encoded data, as in:

$requestURL = "https://accounts.google.com/o/oauth2/token";
$postData = "grant_type=refresh_token&client_id=$clientID&client_secret=$clientSecret&refresh_token=$refreshToken";

$headers[0] = 'Content-Type: application/x-www-form-urlencoded';

$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $requestURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);

$response = curl_exec($ch);
$responseArray = json_decode($response, TRUE);
like image 59
Hans Z. Avatar answered Nov 20 '25 16:11

Hans Z.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!