且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从Google OAuth PHP API获取用户信息

更新时间:2023-12-04 15:42:13

在您的情况下,不需要$google_developer_key.

The $google_developer_key is not needed in your case.

以下是使用 google-api-php-client 库:

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

别忘了-

  1. 通过 Google API控制台
  2. 获取Web客户端ID和密码.
  3. 在同一位置授权https://example.com/myapp/
  1. Get web client id and secret at Google API console
  2. Authorize the https://example.com/myapp/ at the same place

您可以在 *** GitHub 中找到更多示例.

You can find more examples at *** GitHub.