如何使用Google API PHP SDK获取用户信息 [英] How to get user information with Google API PHP SDK

查看:83
本文介绍了如何使用Google API PHP SDK获取用户信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为拥有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中有一个名为getAccountInfo()的方法。但是,它需要的参数是postBody,但我不确定如何获取/构建该参数。

推荐答案

这将返回一个包含您可能要查找的信息的GOOGLE_SERVICE_OAUT2_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 API PHP SDK获取用户信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆