2

我正在尝试使用 Google People API,它允许我检索用户的联系人。这是我的代码:

$scriptUri = "http://".$_SERVER["HTTP_HOST"].$_SERVER['PHP_SELF'];
$client = new Google_Client();
$client->setClientId('OMITTED');
$client->setClientSecret('OMITTED');
$client->setRedirectUri($scriptUri);
//$client->setAccessType('offline');

$client->setScopes(array('https://www.googleapis.com/auth/plus.login', 'https://www.googleapis.com/auth/contacts.readonly', 'profile'));

if (isset($_GET['oauth'])) {
  // Start auth flow by redirecting to Google's auth server
  $auth_url = $client->createAuthUrl();
  header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else if (isset($_GET['code'])) {
  // Receive auth code from Google, exchange it for an access token, and
  // redirect to your base URL
  $client->authenticate($_GET['code']);
  $_SESSION['access_token'] = $client->getAccessToken();
  $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
} else if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
  // You have an access token; use it to call the People API
  $client->setAccessToken($_SESSION['access_token']);
  $people_service = new Google_Service_People($client);
  $connections = $people_service->people->get('people/me');
  // TODO: Use service object to request People data
} else {
  $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/?oauth';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

调用 $connections 行时,会引发以下错误:

未捕获的异常“Google_Service_Exception”和消息“调用 GET https://people.googleapis.com/v1/people/me时出错:(403) 调用者无权请求“people/me”。请求需要以下范围之一:[profile, https://www.googleapis.com/auth/plus.login]

由于上面设置了范围,我无法弄清楚为什么会发生错误。

感谢所有帮助!

4

1 回答 1

1

我只是毫无问题地使用了您的代码。我的猜测是它$_SESSION['access_token']包含一个没有授权正确范围的访问令牌。再次检查身份验证流程,以确保您获得了具有正确授权范围的新访问令牌。

于 2016-06-02T00:00:23.287 回答