2
votes

I am trying to use the Google People API, which allows me to retrieve a user's contacts. Here's my code:

$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));
}

When the $connections line is called, the following error is thrown:

Uncaught exception 'Google_Service_Exception' with message 'Error calling GET https://people.googleapis.com/v1/people/me: (403) The caller does not have permission to request "people/me". Request requires one of the following scopes: [profile, https://www.googleapis.com/auth/plus.login].

I can't figure out why the error is occurring since the scope is set above.

All help is appreciated!

1

1 Answers

1
votes

I just used your code without issue. My guess is that $_SESSION['access_token'] contains an access token that doesn't have the correct scopes authorized. Go through the auth flow again to make sure you you get a new access token with the correct scopes authorized.