php - Google API PHP SDK 获取用户信息的方法

标签 php sdk google-oauth google-admin-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 的类 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 范围。

关于php - Google API PHP SDK 获取用户信息的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28521239/

相关文章:

php - 将天数添加到显示奇数的时间戳

php - CodeIgniter current_url 不显示查询字符串

android - com.android.support 版本与完全相同的版本不匹配

python - 如何使用 OAuth 从 Python 应用程序访问 Google App Engine 端点 API?

php - 有没有办法从数据库返回用户测试中未正确完成的问题和答案?

php - 如何从数据库中获取数据

Android SDK 获取 URL 失败

android - Android SDK 教程练习中的 java.lang.NullPointerException 故障排除

node.js - 带有 Node js 的谷歌 oauth2

google-chrome-extension - 如何从扩展程序中撤销 Google 帐户访问权限