Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Google API Token

I need to get the Google validation token to use with Google APIs, but my code does not work.

$client_id = '495225261106.apps.googleusercontent.com';
$client_secret = urlencode('MY_SECRET_CDE');
$redirect_uri = urlencode('http://MYPAGE.net/test.php');
//$grant_type = urlencode('authorization_code'); //it does not work either.
$grant_type = 'authorization_code';

$post_string = "code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp6&client_id={$client_id}&client_secret={$client_secret}&redirect_uri={$redirect_uri}&grant_type={$grant_type}";

//echo_key_value('post_string',$post_string);

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://accounts.google.com/o/oauth2/token');
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$result = curl_exec($ch);   // Execute the HTTP command
$errmsg = curl_error($ch); 

if($errmsg) echo $errmsg;

The output is:

{"error":"invalid_grant"}
like image 985
Expert wanna be Avatar asked Nov 04 '22 23:11

Expert wanna be


2 Answers

You may find it easier to use Google APIs, especially OAuth stuff, via one of the official client libraries.

Here's a link to the PHP one: http://code.google.com/p/google-api-php-client/

And a link to the docs on OAuth 2.0 with the library (with some great example code): http://code.google.com/p/google-api-php-client/wiki/OAuth2

like image 111
mimming Avatar answered Dec 17 '22 01:12

mimming


Don't you have to put " curl_setopt($ch, CURLOPT_POST, true); " before using postfields? Mine is working and except that and I didn't used urlencode on my secret, it's the same

like image 28
JanDesch Avatar answered Dec 17 '22 00:12

JanDesch