Question

I am trying to use Google's OAuth2 API. In their generic documentation, they mention a call called UserInfo: http://code.google.com/apis/accounts/docs/OAuth2Login.html#userinfocall , which would allow me to retrieve user ids, email, name and other basic stuff.

However I cannot find it in their PHP client library: https://code.google.com/p/google-api-php-client/

Where is it?

Was it helpful?

OTHER TIPS

The Google OAuth2 API has changed - here is how you fetch user information nowadays:

<?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.

I have posted a solution that works for me, a patch to the Google PHP client library to retrieve UserInfo, in this similar question: How to identify a Google OAuth2 user?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top