Get Userinfo from Google OAuth 2.0 PHP API

30,404

Solution 1

Was missing scopes

$client->setScopes(array('https://www.googleapis.com/auth/userinfo.email','https://www.googleapis.com/auth/userinfo.profile'));

Works like a charm now!

Solution 2

I'm not sure if it helps, but since the Google API PHP Client was updated, I get userinfo in this way:

        $oauth = new Google_Service_Oauth2($googleClient);

        var_dump($oauth->userinfo->get());

Solution 3

The Google API PHP client library has changed - here is how you fetch user information:

<?php

require_once('google-api-php-client-1.1.7/src/Google/autoload.php');

const TITLE = 'My amazing app';
const REDIRECT = 'https://example.com/myapp/';

session_start();

$client = new Google_Client();
$client->setApplicationName(TITLE);
$client->setClientId('REPLACE_ME.apps.googleusercontent.com');
$client->setClientSecret('REPLACE_ME');
$client->setRedirectUri(REDIRECT);
$client->setScopes(array(Google_Service_Plus::PLUS_ME));
$plus = new Google_Service_Plus($client);

if (isset($_REQUEST['logout'])) {
        unset($_SESSION['access_token']);
}

if (isset($_GET['code'])) {
        if (strval($_SESSION['state']) !== strval($_GET['state'])) {
                error_log('The session state did not match.');
                exit(1);
        }

        $client->authenticate($_GET['code']);
        $_SESSION['access_token'] = $client->getAccessToken();
        header('Location: ' . REDIRECT);
}

if (isset($_SESSION['access_token'])) {
        $client->setAccessToken($_SESSION['access_token']);
}

if ($client->getAccessToken() && !$client->isAccessTokenExpired()) {
        try {
                $me = $plus->people->get('me');
                $body = '<PRE>' . print_r($me, TRUE) . '</PRE>';
        } catch (Google_Exception $e) {
                error_log($e);
                $body = htmlspecialchars($e->getMessage());
        }
        # the access token may have been updated lazily
        $_SESSION['access_token'] = $client->getAccessToken();
} else {
        $state = mt_rand();
        $client->setState($state);
        $_SESSION['state'] = $state;
        $body = sprintf('<P><A HREF="%s">Login</A></P>',
            $client->createAuthUrl());
}

?>

<!DOCTYPE HTML>
<HTML>
<HEAD>
        <TITLE><?= TITLE ?></TITLE>
</HEAD>
<BODY>
        <?= $body ?>
        <P><A HREF="<?= REDIRECT ?>?logout">Logout</A></P>
</BODY>
</HTML>

Do not forget to -

  1. Get web client id and secret at Google API console
  2. Authorize the https://example.com/myapp/ at the same place

You can find official examples at Youtube GitHub.

UPDATE 2017:

You can add the fields to be retrieved with:

const FIELDS       = 'id,name,image';
$me = $plus->people->get('me', array('fields' => FIELDS));
Share:
30,404

Related videos on Youtube

Kshitiz
Author by

Kshitiz

I'm a self-motivated tech entrepreneur based out of Singapore with over 10 years of experience in the building software products. I am passionate about solving real-world problems, with a knack for programming. My experience has been somewhat unique compared to most of my peers. Over the past 10 years of my career, I have started up three different tech companies and got an amazing opportunity to build and launch multiple products from the ground up at various points of my life. Being a founder and tech lead for most of my endeavors, I excel at picking up new stacks/technologies and executing to serve unmet customer needs. My focus area for the post-covid universe has been to set up and lead our fully remote team to ship incremental improvements and features on top of our Vue.js and Node.js based SaaS application.

Updated on July 09, 2022

Comments

  • Kshitiz
    Kshitiz almost 2 years

    I am trying to use Google Oauth API to get userinfo. It works perfectly for Google Plus API but I am trying to create a backup in case the user doesn't have google plus account. The authentication process is correct and I even get the $userinfo object but how exactly do I access the properties. I tried $userinfo->get() but it only return the id of the user.

    Am I doing something wrong? Here is the code that I am using...

    require_once '../../src/Google_Client.php';
    require_once '../../src/contrib/Google_Oauth2Service.php';
    
    session_start();
    
    $client = new Google_Client();
    $client->setApplicationName("Google+ PHP Starter Application");
    // Visit https://code.google.com/apis/console to generate your
    // oauth2_client_id, oauth2_client_secret, and to register your oauth2_redirect_uri.
     $client->setClientId('*********************');
     $client->setClientSecret('**************');
     $client->setRedirectUri('***************');
     $client->setDeveloperKey('**************');
    $plus = new Google_Oauth2Service($client);
    
    if (isset($_REQUEST['logout'])) {
      unset($_SESSION['access_token']);
    }
    
    if (isset($_GET['code'])) {
      $client->authenticate($_GET['code']);
      $_SESSION['access_token'] = $client->getAccessToken();
      header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
    }
    
    if (isset($_SESSION['access_token'])) {
      $client->setAccessToken($_SESSION['access_token']);
    }
    
    if ($client->getAccessToken()) 
    {
        $userinfo = $plus->userinfo;
        print_r($userinfo->get());
    
    } else 
    {
        $authUrl = $client->createAuthUrl();
    }
    ?>
    <!doctype html>
    <html>
    <head>
      <meta charset="utf-8">
      <link rel='stylesheet' href='style.css' />
    </head>
    <body>
    <header><h1>Google+ Sample App</h1></header>
    <div class="box">
    
    <?php if(isset($personMarkup)): ?>
    <div class="me"><?php print $personMarkup ?></div>
    <?php endif ?>
    
    <?php
      if(isset($authUrl)) {
        print "<a class='login' href='$authUrl'>Connect Me!</a>";
      } else {
       print "<a class='logout' href='?logout'>Logout</a>";
      }
    ?>
    </div>
    </body>
    </html>
    

    Thanks...

    **EDIT*** Was missing Scopes--Added

     $client->setScopes(array('https://www.googleapis.com/auth/userinfo.email','https://www.googleapis.com/auth/userinfo.profile'));
    

    works now...

    • Kush
      Kush over 11 years
      What's the error you're getting?
    • Kshitiz
      Kshitiz over 11 years
      I am not getting any errors, I am just not sure if I am using the object correctly [$userinfo = $plus->userinfo;]. After this how do I access the user's info from the $userinfo object. I tried $userinfo->get() but that returns only ID
    • vikas devde
      vikas devde about 11 years
      where to add that missing scopes?
    • Kshitiz
      Kshitiz about 11 years
      after creating the object of the client $client = Google_OAUTH_Client_Class::getGoogleClient(); $client->setScopes(array(......));
  • Mark
    Mark over 9 years
    I used to use this method, but this is the way it was done in previous versions, not in the current versions.