Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google API OAuth 2.0 CURL returning "Required parameter is missing: grant_type"

I'm trying to implement Google's OAuth 2.0 authentication for a web server application.

I can obtain the code from Google ok, but when I post this back to try and get an access token, it always give me the error "Required parameter is missing: grant_type. Error 400" even though the grant_type is there.

Also if I specify the content-length to be anything other than 0, it throws other errors.

Here's the code that's doing this curl post:

$url = 'https://accounts.google.com/o/oauth2/token';
$ch = curl_init($url);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
curl_setopt($ch, CURLOPT_FAILONERROR, false);  
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); 

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/x-www-form-urlencoded',
    'Content-length: 0'
));

curl_setopt($ch, CURLOPT_POSTFIELDS, array( 
    'code='. urlencode($code),
    'client_id=' . urlencode($clientID),
    'client_secret=' . urlencode($clientSecret),
    'redirect_uri=http%3A%2F%2Flocalhost%2Fexperiments%2FnewGALogin.php',
    'grant_type=authorization_code'
)); 
like image 980
hud Avatar asked Jan 19 '23 06:01

hud


1 Answers

try

curl_setopt($ch, CURLOPT_POSTFIELDS, array( 
    'code' => $code,
    'client_id' => $clientID,
    'client_secret' => $clientSecret,
    'redirect_uri' => 'http%3A%2F%2Flocalhost%2Fexperiments%2FnewGALogin.php',
    'grant_type' => 'authorization_code'
)); 

or

curl_setopt($ch, CURLOPT_POSTFIELDS,
    'code=' . urlencode($code) . '&' .
    'client_id=' . urlencode($clientID) . '&' .
    'client_secret=' . urlencode($clientSecret) . '&' .
    'redirect_uri=http%3A%2F%2Flocalhost%2Fexperiments%2FnewGALogin.php' . '&' .
    'grant_type=authorization_code'
); 
like image 57
Utku Yıldırım Avatar answered Jan 20 '23 19:01

Utku Yıldırım