从google oAuth2 php模块获取电子邮件和givenName+familyName



我正在使用以下页面代码:https://github.com/google/google-api-php-client/blob/a88dcec6833ac2de4798c13a24abe30c90feb057/examples/idtoken.php从谷歌获取电子邮件地址和givenName和familyName,以便谷歌登录。

如果我将范围设置为email,我会将电子邮件存储在Google帐户中(而不是Google plus中的帐户)。如果我将范围设置为"个人资料",我会在谷歌中存储givenName和familyName,而不是在谷歌+个人资料中。我需要这个名字,因为大多数用户没有GooglePlus个人资料。

我试着把它们组合在一起,但我要么收到电子邮件,要么收到名字,从来没有同时收到。

  • 我尝试了$client->setScopes('profile','email');——它只显示Name,而不显示电子邮件
  • 我尝试了$client->setScopes('email','profile');——它只会带来电子邮件,"名称"字段为空
  • 我还尝试使用$google_client->setScopes(array('https://www.googleapis.com/auth/plus.login'));进行设置比如这里:如何使用googleapi简洁地获取用户详细信息,但只能获取其中一个,而不能同时获取两者。这就像setScopes没有添加作用域,而是只使用列表中的第一个

这是使用的代码:

$_SESSION['access_token'] = $client->getAccessToken();
$token_data = $client->verifyIdToken()->getAttributes();
$oAuth2 = new Google_Service_Oauth2($client);
$oAttr = $oAuth2->userinfo->get();
$test_me = $oAuth2->userinfo_v2_me->get();;
/* the next part doesn't bring names or emails because the user doesn't have g+
$plus = new Google_Service_Plus($client);  
$me = $plus->people->get('me');
$firstname = $me['name']['givenName'];
$lastname = $me['name']['familyName'];
*/

知道在setScopes中组合配置文件和电子邮件以获得电子邮件和姓名的正确方法是什么吗?

谢谢。

好的,找到了答案。

看起来像是github的"官方"版本(https://github.com/google/google-api-php-client/blob/master/src/Google/Client.php)有一个错误。

我发现了这个bug,并在这里进行了讨论:https://github.com/google/google-api-php-client/issues/6

显然,setScopes内部数组的串联无法正常工作。

该项目有一个分叉,有一个版本可以工作,但如果我替换整个Client.php文件,它会在其他地方中断,所以我只替换函数:(由于我不能发布更多的2个链接,分叉项目可以通过谷歌功能名称找到)

底线是:我更改了函数prepareScopes,现在我可以同时获得信息(电子邮件和姓名)。

以下是在Client.php文件中工作的函数:

  public function prepareScopes()
  {
    if (empty($this->requestedScopes)) {
      foreach ($this->availableScopes as $service => $serviceScopes) {
        array_push($this->requestedScopes, $serviceScopes[0]);
      }
    }
    $scopes = implode(' ', $this->requestedScopes);
    return $scopes;
  }

也有同样的问题。你需要像这样将两者结合起来:

$client ->setScopes('profile email');

不像这个

$client ->setScopes('profile', 'email');

通过这种方式,您不必麻烦处理其他oAuth配置文件。

相关内容

最新更新