I am developing an app that allows users to see my own Google Analytics Data using Google API v3. Everything I researched seems to indicate that users need to login into their Google accounts and grant my app the access before I can start querying the API; however, that's not what I want, I just need my users to see my own Analytics data. How can authorize the API to access my data. I have the client ID and Client Secret, but the OAuth that's implemented by Google's API v3 is asking for an authorization token, which can only be obtained by getting the user to login into their google account (is that right?) Is there a way to just login into my own Google Analytics account and display that information to the users?
问题:
回答1:
I believe what you want to do is set up a Service Account: https://developers.google.com/analytics/devguides/config/mgmt/v3/mgmtAuthorization
"Useful for automated/offline/scheduled access to Google Analytics data for your own account. For example, to build a live dashboard of your own Google Analytics data and share it with other users.
There are a few steps you need to follow to configure service accounts to work with Google Analytics:
- Register a project in the APIs Console.
- In the Google APIs Console, under the API Access pane, create a client ID with the Application Type set to Service Account.
- Sign-in to Google Analytics and navigate to the Admin section.
- Select the account for which you want the application to have access to.
- Add the email address, from the Client ID created in the APIs Console from step #2, as a user of the selected Google Analytics account.
- Follow the instructions for Service Accounts to access Google Analytics data: https://developers.google.com/accounts/docs/OAuth2ServiceAccount"
回答2:
You can use a refresh token
for offline access. Once you get the refresh token
, you can save it to a file or database and use that to access the data without an authorization redirect.
See Using a Refresh Token in the docs.
Also see: How can we access specific Google Analytics account data using API?
回答3:
Here is a full Google Analytics reporting example implementation with service account including setup notes. Just wrote it after reading your question, I had the same problem.
<?php
// Service account code from http://stackoverflow.com/questions/18258593/using-a-service-account-getaccesstoken-is-returning-null
// Analytics code from https://code.google.com/p/google-api-php-client/source/browse/trunk/examples/analytics/simple.php?r=474
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_AnalyticsService.php';
// Set your client id, service account name (AKA "EMAIL ADDRESS"), and the path to your private key.
// For more information about obtaining these keys, visit:
// https://developers.google.com/console/help/#service_accounts
const CLIENT_ID = 'CLIENT ID';
const SERVICE_ACCOUNT_NAME = 'SERVICE ACCOUNT NAME (IS "EMAIL ADDRESS")';
const KEY_FILE = 'KEY FILE';
const SCOPE = 'https://www.googleapis.com/auth/analytics.readonly';
// OPEN GOOGLE ANALYTICS AND GRANT ACCESS TO YOUR PROFILE, THEN PASTE IN YOUR SERVICE_ACCOUNT_NAME
$key = file_get_contents(KEY_FILE);
$auth = new Google_Auth_AssertionCredentials(
SERVICE_ACCOUNT_NAME,
array(SCOPE),
$key
);
$client = new Google_Client();
$client->setScopes(array(SCOPE));
$client->setAssertionCredentials($auth);
$client->getAuth()->refreshTokenWithAssertion();
$accessToken = $client->getAccessToken();
$client->setClientId(CLIENT_ID);
$service = new Google_Service_Analytics($client);
?>
<!DOCTYPE html>
<html>
<head>
<title>Google Experiments Dashboard</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" media="screen">
</head>
<body class="container">
<h1>Your experiments</h1>
<table class="table"><tr><th><th>Experiment<th>Page<th>Started<th>Status
<?php
$progressClasses = array('progress-bar progress-bar-success','progress-bar progress-bar-info','progress-bar progress-bar-warning', 'progress-bar progress-bar-danger');
$profiles = $service->management_profiles->listManagementProfiles("~all", "~all");
foreach ($profiles['items'] as $profile) {
$experiments = $service->management_experiments->listManagementExperiments($profile['accountId'], $profile['webPropertyId'], $profile['id']);
foreach ($experiments['items'] as $experiment) {
echo "<tr>";
if ($experiment['status'] == 'RUNNING')
echo '<td><a class="btn btn-xs btn-success"><i class="glyphicon glyphicon-ok"></i></a>';
else
echo '<td><a class="btn btn-xs btn-danger"><i class="glyphicon glyphicon-remove"></i></a>';
$expHref = "https://www.google.com/analytics/web/?pli=1#siteopt-experiment/siteopt-detail/a{$profile['accountId']}w{$experiment['internalWebPropertyId']}p{$experiment['profileId']}/%3F_r.drilldown%3Danalytics.gwoExperimentId%3A{$experiment['id']}/";
echo "<td><a href='$expHref' target='_blank'>{$experiment['name']}</a>";
echo "<td>{$experiment['variations'][0]['url']}";
echo "<td>".date('Y-m-d',strtotime($experiment['startTime']));
echo "<td>";
echo '<div class="progress" style="width:400px">';
foreach ($experiment['variations'] as $i => $variation) {
echo '<a href="'.$variation['url'].'" target="_blank"><div class="'.$progressClasses[$i].'" role="progressbar" style="width: '.(100*$variation['weight']).'%">'.$variation['name'].'</div></a>';
}
echo '</div>';
}
}
?>
Code with more documentation at https://gist.github.com/fulldecent/6728257