'https://www.googleapis.com/auth/analytics.readonly',
'tokenCredentialUri' => 'https://oauth2.googleapis.com/token',
'authorizationUri' => $keys->{'web'}->{'auth_uri'},
'clientId' => $keys->{'web'}->{'client_id'},
'clientSecret' => $keys->{'web'}->{'client_secret'},
'redirectUri' => 'http://' . $_SERVER['HTTP_HOST'] . '/',
]);
if (isset($_SESSION['access_token']) && $_SESSION['access_token']
&& isset($_SESSION['refresh_token']) && $_SESSION['refresh_token']) {
// This is the final step of the OAuth2 authorization process, where an
// OAuth2 access token is available and can be used to set up a client.
$oauth->setAccessToken($_SESSION['access_token']);
$oauth->setRefreshToken($_SESSION['refresh_token']);
try {
// Make an API call.
$client = new BetaAnalyticsDataClient(['credentials' => $oauth]);
$request = (new RunReportRequest())
->setProperty('properties/' . $property_id)
->setDateRanges([
new DateRange([
'start_date' => '2020-03-31',
'end_date' => 'today',
]),
])
->setDimensions([new Dimension([
'name' => 'city',
]),
])
->setMetrics([new Metric([
'name' => 'activeUsers',
])
]);
$response = $client->runReport($request);
// Print results of an API call.
print 'Report result:
';
foreach ($response->getRows() as $row) {
print $row->getDimensionValues()[0]->getValue()
. ' ' . $row->getMetricValues()[0]->getValue() . '
';
}
} catch (ApiException $e) {
// Print an error message.
print $e->getMessage();
}
} elseif (isset($_GET['code']) && $_GET['code']) {
// If an OAuth2 authorization code is present in the URL, exchange it for
// an access token.
$oauth->setCode($_GET['code']);
$oauth->fetchAuthToken();
// Persist the acquired access token in a session.
$_SESSION['access_token'] = $oauth->getAccessToken();
// Persist the acquired refresh token in a session.
$_SESSION['refresh_token'] = $oauth->getRefreshToken();
// Refresh the current page.
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
} else {
// Redirect to Google's OAuth 2.0 server.
$auth_url = $oauth->buildFullAuthorizationUri();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
}
// [END analyticsdata_quickstart_oauth2]