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

hea*_*t23 8 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();
Run Code Online (Sandbox Code Playgroud)

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

我在Google PHP SDK中看到了一个getAccountInfo()在类中调用的方法Google_Service_IdentityToolkit.但是,它需要的参数是,postBody但我不知道如何获得/构建它.

ant*_*ver 9

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

$oauth2 = new \Google_Service_Oauth2($client);
$userInfo = $oauth2->userinfo->get();
print_r($userInfo);
Run Code Online (Sandbox Code Playgroud)

在哪里$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
        (
        )

)
Run Code Online (Sandbox Code Playgroud)

另请注意,您还需要请求https://www.googleapis.com/auth/userinfo.profile范围.

  • 赞成。您知道如何从用户那里获得一些其他信息吗?即他的电话号码,他的地址等..!我应该使用任何特定的库吗? (2认同)

Woo*_*gie 5

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

$oauth2 = new Google_Service_Oauth2($client);
$userInfo = $oauth2->userinfo;
Run Code Online (Sandbox Code Playgroud)