Get Userinfo from Google OAuth 2.0 PHP API Get Userinfo from Google OAuth 2.0 PHP API php php

Get Userinfo from Google OAuth 2.0 PHP API


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!


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());


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

<?phprequire_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));