[英]How to get user information with Google API PHP SDK
I am trying to add a login option to my website for people with Google accounts. 我正在尝试为拥有Google帐户的人添加登录选项到我的网站。 I have been able to implement this Facebook but having issues getting user account information with Google.
我已经能够实现这个Facebook但在向Google获取用户帐户信息时遇到问题。
I am using the Google PHP SDK located here: https://github.com/google/google-api-php-client 我使用的是位于此处的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();
But now how do I access the user's email address and other basic information? 但是现在我如何访问用户的电子邮件地址和其他基本信息?
I see in the Google PHP SDK a method called getAccountInfo()
in the class Google_Service_IdentityToolkit
. 我在Google PHP SDK中看到了类
Google_Service_IdentityToolkit
名为getAccountInfo()
的方法。 However, the parameter it requires is postBody
but I am not sure how to get/build that. 但是,它需要的参数是
postBody
但我不知道如何获取/构建它。
This will return a Google_Service_Oauth2_Userinfoplus object with the info you're probably looking for: 这将返回一个Google_Service_Oauth2_Userinfoplus对象,其中包含您可能正在查找的信息:
$oauth2 = new \Google_Service_Oauth2($client);
$userInfo = $oauth2->userinfo->get();
print_r($userInfo);
Where $client
is an instance of Google_Client
其中
$client
是Google_Client
一个实例
Outputs: 输出:
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
(
)
)
Also note that you need to request the https://www.googleapis.com/auth/userinfo.profile
scope as well. 另请注意,您还需要请求
https://www.googleapis.com/auth/userinfo.profile
范围。
You should be able to get this info by constructing a Google_Service_OAuth2 object, passing in the Google_Client as a paramater, then get the user info from there. 您应该能够通过构建Google_Service_OAuth2对象来获取此信息,将Google_Client作为参数传递,然后从那里获取用户信息。
$oauth2 = new Google_Service_Oauth2($client);
$userInfo = $oauth2->userinfo;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.