PHP 中的 "Login with Google" - Google+ API 关闭迁移 - 如何从 plus.people.get 迁移?

"Login with Google" in PHP - Google+ API shutdown migration - how to migrate away from plus.people.get?

我收到一封来自 Google 的警告邮件,提醒我 Google+ 的 EOL 应该会破坏我当前的 "Login with Google",但我不确定我到底应该更改什么.

让我向您展示我的(简化)登录代码:

google-login.php

new class {
    public function __construct() {
        $state = mt_rand();

        $client = new Google_Client();
        $client->setApplicationName(Config::Google['app_name']);
        $client->setClientId(Config::Google['id']);
        $client->setClientSecret(Config::Google['secret']);
        $client->setRedirectUri(sprintf('https://%s/members/google-callback.php', $_SERVER['HTTP_HOST']));
        $client->setScopes(['profile', 'email']);
        $client->setState($state);

        $_SESSION['state'] = $state;
        $url = $client->createAuthUrl(); // $url = https://accounts.google.com/o/oauth2/auth?response_type=code&access_type=online&client_id=CLIENT_ID.apps.googleusercontent.com&redirect_uri=https%3A%2F%2Fread2me.online%2Fmembers%2Fgoogle-callback.php&state=1588245f23f2a&scope=profile%20email&approval_prompt=auto

        header ("location: $url");
    }
};

google-callback.php

new class {
    private $newUser = false;

    public function __construct() {
        if (!isset($_GET['state']) || $_GET['state'] != $_SESSION['state'])
            die('State mismatch.');

        $client = new Google_Client();
        $client->setApplicationName(Config::Google['app_name']);
        $client->setClientId(Config::Google['id']);
        $client->setClientSecret(Config::Google['secret']);
        $client->setRedirectUri(sprintf('https://%s/members/google-callback.php', $_SERVER['HTTP_HOST']));
        $client->setScopes(['profile', 'email']);

        $plus = new Google_Service_Plus($client);

        if (isset($_GET['code'])) {
            $client->fetchAccessTokenWithAuthCode($_GET['code']);
            $_SESSION['token'] = $client->getAccessToken();
        }

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

        if (!$client->getAccessToken() || $client->isAccessTokenExpired()) {
            $state = mt_rand();
            $client->setState($state);
            $_SESSION['state'] = $state;
            $url = $client->createAuthUrl();

            header ("location: $url");
        }

        try {
            $me = $plus->people->get('me');
        } catch (Google_Exception $e) {
            \Rollbar::report_message($e->getMessage());
            print_r($e->getMessage());

            return;
        }

        $accessToken = $client->getAccessToken()['access_token'];
        $email = $me->getEmails()[0]->getValue();
        $name = $me->getDisplayName();
        $avatar = $me->getImage()->getUrl();
        $id = $me->getId();

        if ($this->isEmailInSystem($email) === false) {
            $this->newUser = true;
            $this->addUser($email, $name, 'google', $accessToken, $id, $avatar);
        }

        header ("location: " . '/');
    }
};

现在,我正在经历 up-to-date Sign In guide for PHP,但我不确定要更改什么 - 有什么想法吗?

谢谢

显然,行

$plus = new Google_Service_Plus($client);

$me = $plus->people->get('me');

您需要使用 google 电子邮件 API,请参阅 https://developers.google.com/gmail/api/quickstart/php,因此第一行将是

$service = new Google_Service_Gmail($client);

第二个……嗯……不确定删除 google 后是否会有任何头像加上……

最好的迁移是从 Plus API 迁移到 People API,它以类似(但不完全相同)的方式提供对用户个人资料的访问。

您将用新的 Goolge_Service_PeopleService 对象替换 $plus 对象的创建。像

$people = new Google_Service_PeopleService( $client );

获取个人资料比较复杂,因为您需要指定要从个人资料中获取哪些字段。但你可以这样做

$profile = $people->people->get(
  'people/me', 
  array('personFields' => 'names,emailAddresses,photos')
);

第一个参数需要 "people/me" 以指定您正在请求授权用户的个人资料。

第二个是查询参数数组。您需要从可用列表中指定您想要的 "personFields"(向下滚动 this page 直到您看到可用字段的描述)并将其指定为字符串中的逗号分隔列表.在我上面的示例中,我说明了如何获取姓名、电子邮件地址和照片。但是请查阅列表并进行实验。

您从 $profile 的结果中获得的确切字段将与您从 $plus 中获得的结果不同,但它们应该与您请求的字段相匹配。检查值以及它们的确切结构。

我 运行 遇到与 Google+ API 于 2019 年 3 月 7 日关闭相同的问题。

确保Google People API is enable in your google console 我使用了 google-api-php-client 库。

获得访问令牌后,这里是使用 people API

获取人员对象的代码
$accessToken = 'REPLACE_WITH_ACCESS_TOKEN';
$clientId = 'REPLACE_WITH_CLIENT_ID';
$clientSecret = 'REPLACE_WITH_CLIENT_SECRET';
$developerKey = 'REPLACE_WITH_DEVELOPER_KEY';    
    $client = new Google_Client();
    $client->setApplicationName("Application Name");
    $client->setClientId($clientId . '.apps.googleusercontent.com');
    $client->setClientSecret($clientSecret);
    $client->setDeveloperKey($developerKey);
    $client->setScopes(['https://www.googleapis.com/auth/userinfo.email','https://www.googleapis.com/auth/userinfo.profile']);
    $client->setAccessToken($accessToken);
    $guzzleClient = new \GuzzleHttp\Client(array( 'curl' => array( CURLOPT_SSL_VERIFYPEER => false, ), ));
    $client->setHttpClient($guzzleClient);
    $people = new Google_Service_PeopleService( $client );

    if ($client->getAccessToken()) {
        try {
            $me = $people->people->get(
                'people/me',
                array('personFields' => 'emailAddresses,names,photos')
            );

            $id       = preg_replace('/[^0-9]/', '', $me->getResourceName());
            $email    = $me->getEmailAddresses()[0]->value;
            $name     = $me->getNames()[0]->displayName;
            $avtar    = $me->getPhotos()[0]->getUrl();
        } catch (Google_Exception $e) {
            // error
            echo $e->getMessage();
        }
    }

我还禁用了 Google+ API 以确保该应用程序不再在任何地方使用它。

使用 latest 版本的 Google API PHP 客户端,您可以从 Google_Client 对象本身获取配置文件详细信息。

$token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
$attributes = $client->verifyIdToken($token['id_token'], GOOGLE_CLIENT_ID);
print_r($attributes);

参考这个article