使用PHP中的Google API OAuth获取用户信息

时间:2018-12-21 09:00:35

标签: php google-api google-oauth google-api-php-client google-oauth2

我已经在我的php网站中使用Google_Client登录到Google。

登录成功,但是我试图获取已登录但未获取的用户详细信息。

下面是我的代码。

$gClient = new Google_Client();
$gClient->setApplicationName('Login to -------');
$gClient->setClientId(GOOGLE_CLIENT_ID);
$gClient->setClientSecret(GOOGLE_CLIENT_SECRET);
$gClient->addScope(Google_Service_Oauth2::USERINFO_PROFILE);
$gClient->addScope(Google_Service_Oauth2::USERINFO_EMAIL);
$gClient->addScope(Google_Service_Oauth2::PLUS_LOGIN);
$gClient->setAccessType('offline');        // offline access
$gClient->setIncludeGrantedScopes(true);   // incremental auth
$gClient->setRedirectUri(WEB_PANEL_PATH);
$google_code = $gh->read('code');
$objOAuthService = new Google_Service_Oauth2($gClient);
if (!empty($google_code)) {
  $gClient->authenticate($google_code);
  $_SESSION['access_token'] = $gClient->getAccessToken();
  $outputjson['active'] = $_SESSION['access_token'];
}
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
  $gClient->setAccessToken($_SESSION['access_token']);
}
if($gClient->getAccessToken()) {
  $userData = $objOAuthService->userinfo->get();
  if(!empty($userData)) {
  }
  $outputjson['user_data'] = $userData;
  $outputjson['access_token'] = $gClient->getAccessToken();
}else{
  $outputjson['login_url'] = $gClient->createAuthUrl();
}
$outputjson['session'] = $_SESSION;
$outputjson['success'] = '1';

$ userData 始终为空。

它正在向oauth2 / v2 / userinfo发送请求,但未获取任何数据。

[methods:Google_Service_Resource:private] => Array
(
    [get] => Array
    (
        [path] => oauth2/v2/userinfo
        [httpMethod] => GET
        [parameters] => Array
        (
        )
    )
)

1 个答案:

答案 0 :(得分:2)

尝试执行以下操作

var_dump($oauth->userinfo->get());

应该给你这样的东西

Array
(
    [id] => 1045636599999999999
    [name] => Linda Lawton
    [given_name] => Linda
    [family_name] => Lawton
    [locale] => dk
)

应该允许您执行$userData->parameters[0]$userData->parameters[id]