如何使用Google API PHP SDK获取用户信息


How to get user information with Google API PHP SDK

我正试图为拥有谷歌账户的人在我的网站上添加一个登录选项。我已经能够实现这个Facebook,但在谷歌获取用户帐户信息时遇到了问题。

我使用的是位于此处的Google PHP SDK:https://github.com/google/google-api-php-client

$client = new Google_Client();
$client->setClientId($this->ci->config->item('client_id', 'google'));
$client->setClientSecret($this->ci->config->item('client_secret', 'google'));
$client->setRedirectUri($this->ci->config->item('callback_uri', 'google'));
$client->addScope('https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/plus.login');
$this->client->createAuthUrl();

但现在我该如何访问用户的电子邮件地址和其他基本信息?

我在GooglePHPSDK中看到了Google_Service_IdentityToolkit类中一个名为getAccountInfo()的方法。然而,它需要的参数是postBody,但我不确定如何获得/构建它。

这将返回一个Google_Service_Oauth2_Userinfoplus对象,其中包含您可能正在查找的信息:

$oauth2 = new 'Google_Service_Oauth2($client);
$userInfo = $oauth2->userinfo->get();
print_r($userInfo);

其中$clientGoogle_Client 的实例

输出:

Google_Service_Oauth2_Userinfoplus Object
(
    [internal_gapi_mappings:protected] => Array
        (
            [familyName] => family_name
            [givenName] => given_name
            [verifiedEmail] => verified_email
        )
    [email] => 
    [familyName] => 
    [gender] => 
    [givenName] => 
    [hd] => 
    [id] => 123456
    [link] => https://plus.google.com/123456
    [locale] => en-GB
    [name] => someguy
    [picture] => https://lh3.googleusercontent.com/-q1Smh9d8d0g/AAAAAAAAAAM/AAAAAAAAAAA/3YaY0XeTIPc/photo.jpg
    [verifiedEmail] => 
    [modelData:protected] => Array
        (
        )
    [processed:protected] => Array
        (
        )
)

还要注意,您还需要请求https://www.googleapis.com/auth/userinfo.profile作用域。

您应该能够通过构建Google_Service_OAuth2对象来获取此信息,将Google_Client作为参数传递,然后从中获取用户信息。

$oauth2 = new Google_Service_Oauth2($client);
$userInfo = $oauth2->userinfo;