【问题标题】:How to get user information with Google API PHP SDK如何使用 Google API PHP SDK 获取用户信息
【发布时间】:2015-04-15 18:32:07
【问题描述】:

我正在尝试在我的网站上为拥有 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 中看到 getAccountInfo() 类中的 Google_Service_IdentityToolkit 方法。但是,它需要的参数是postBody,但我不确定如何获取/构建它。

【问题讨论】:

    标签: php sdk google-oauth google-admin-sdk


    【解决方案1】:

    这将返回一个 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_Client 中设置的基本登录范围应该只是“电子邮件”和/或“个人资料”(取决于您需要什么信息)。我认为,'googleapis.com/auth/userinfo.profile' 已被弃用,但为了向后兼容而保留。更多信息在官网developers.google.com/identity/protocols/…
    【解决方案2】:

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

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

    【讨论】:

    • 自从您发布此答案以来,案例似乎已经发生了变化。现在是Google_Service_Oauth2(小写a)和userinfo(小写i)
    • @antriver 你确实解决了我的整个问题。使用 Wamp 时,区分大小写并不重要,当我将它移到灯上时,它就崩溃了。所以linux是强迫症,windows不在乎。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-10
    • 1970-01-01
    • 1970-01-01
    • 2013-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多