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

11

我正试图为拥有Google账号的用户在我的网站上添加登录选项。我已经成功实现了Facebook的登录,但在使用Google时遇到了获取用户账户信息的问题。

我正在使用位于此处的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();

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

我在Google PHP SDK中看到一个名为Google_Service_IdentityToolkit的类中有一个名为getAccountInfo()的方法。但是,它需要的参数是postBody,但我不确定如何获取/构建它。

2个回答

18

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

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

其中$client是一个Google_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范围。


2
点赞。你知道我怎么能从用户那里获取一些额外的信息吗?例如他的电话号码,地址等等..!我应该使用任何特定的库吗? - Shafizadeh
1
很棒的解决方案。但有一个技术问题...Google_Client中应设置基本的登录范围,只需设置'email'和/或'profile'(取决于您需要哪些信息),因为一段时间以来'https://www.googleapis.com/auth/userinfo.profile'已被弃用,但为了向后兼容而保留。更多信息请参见官方网站https://developers.google.com/identity/protocols/googlescopes#google_sign-in。 - The Vojtisek
此 API 已被弃用。您需要切换到 Google_Client。 - Peter Fox

5
你可以通过构建一个 Google_Service_OAuth2 对象来获取这些信息,将 Google_Client 作为参数传递,然后从中获取用户信息。
$oauth2 = new Google_Service_Oauth2($client);
$userInfo = $oauth2->userinfo;

1
自从您发布这个答案以来,情况似乎已经发生了变化。现在是 Google_Service_Oauth2(小写字母a)和 userinfo(小写字母i)。 - antriver
1
@antriver,你真的解决了我的整个问题。在Wamp中,大小写敏感性并不重要,但当我将它移动到Lamp时,它崩溃了。所以Linux很挑剔,而Windows则不在乎。 - Matthew Auld

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接