Rishin S Babu
Rishin S Babu

Reputation: 1693

Using Google authentication API with PHP

Instead of printing the userinfo, the following code is printing the details of the access token granted by Google. The code is very simple yet I am not able to figure out the exact cause of this

    <?php
$url = 'https://accounts.google.com/o/oauth2/token';
$fields = array(
        'code'=>urlencode($_GET['code']),
        'client_id'=>urlencode('###########.apps.googleusercontent.com'),
        'client_secret'=>urlencode('###########'),
        'redirect_uri'=>urlencode('http://######odie.co.in/googlogin'),
        'grant_type'=>urlencode('authorization_code'),
                    );


foreach($fields as $key=>$value) {
     $fields_string .= $key.'='.$value.'&';
     }
rtrim($fields_string,'&');

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);

//execute post
$result = curl_exec($ch);


//close connection
curl_close($ch);
$data =  json_decode($result);

print_r(file_get_contents(' https://www.googleapis.com/oauth2/v1/userinfo?access_token='.$data['access_token']));
?>

Upvotes: 2

Views: 923

Answers (2)

Dino Babu
Dino Babu

Reputation: 5809

refer this. its very simple.

Simple PHP Library for Google Authentication API

Upvotes: 1

richoffrails
richoffrails

Reputation: 1033

You need to add CURLOPT_RETURNTRANSFER, true to your curl_setopt.

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

Upvotes: 2

Related Questions