从谷歌oAuth2 php模块

时间:2015-12-07 13:34:47

标签: php google-api google-oauth

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

如果我将范围设置为email,我会收到存储在Google帐户中的电子邮件(不是Google plus中的电子邮件)。如果我将范围设置为“个人资料”,我会将Google中的givenName和familyName存储在Google plus个人资料中。我需要此名称,因为大多数用户没有Google Plus个人资料。

我尝试将它们组合在一起,但我得到的是电子邮件或姓名,而不是两者。

  • 我试过了$client->setScopes('profile','email'); - 它只带来了姓名,而不是电子邮件
  • 我尝试了$client->setScopes('email','profile'); - 它只会带来电子邮件,名称字段为空。
  • 我还尝试使用$google_client->setScopes(array('https://www.googleapis.com/auth/plus.login'));进行设置 像这里:How to get user details corectly with google api但只得到一个或另一个,从来没有。 就像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中组合个人资料和电子邮件以获取电子邮件和姓名的正确方法是什么?

感谢。

2 个答案:

答案 0 :(得分:0)

好的,找到了答案。

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

我在这里发现并讨论了这个错误: 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;
  }

答案 1 :(得分:0)

有同样的问题。你需要将它们两者结合起来:

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

不喜欢这个

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

通过这种方式,您不必乱用其他oAuth配置文件。