Google Analytics - Access api without login

Kiran picture Kiran · Sep 1, 2014 · Viewed 11.6k times · Source

I had successfully configured google analytics api and get successful data.

I want to access analytics api without gmail login.

i.e. I will hard code credentials to for login, but how to do it with PHP?

Is there any api function to achive this task (for PHP)

Thanks!

Answer

Matt picture Matt · May 11, 2015

The Hello Analytics API: PHP Quickstart Guide for Service Accounts will walk you through the steps necessary to create and add a service account to your existing Google Analytics Account/Property/View.

Once you download have the php client libs and the p12 file downloaded from developer console you can create an authorized analytics service object as follows:

// Creates and returns the Analytics service object.

// Load the Google API PHP Client Library.
require_once 'google-api-php-client/src/Google/autoload.php';

// Use the developers console and replace the values with your
// service account email, and relative location of your key file.
$service_account_email = '<Replace with your service account email address.>';
$key_file_location = '<Replace with /path/to/generated/client_secrets.p12>';

// Create and configure a new client object.
$client = new Google_Client();
$client->setApplicationName("HelloAnalytics");
$analytics = new Google_Service_Analytics($client);

// Read the generated client_secrets.p12 key.
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
    $service_account_email,
    array(Google_Service_Analytics::ANALYTICS_READONLY),
    $key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
  $client->getAuth()->refreshTokenWithAssertion($cred);
}

return $analytics;

With the returned service object you can now make calls to the Google Analytics APIs:

// Calls the Core Reporting API and queries for the number of sessions
// for the last seven days.
$analytics->data_ga->get(
   'ga:' . $profileId,
   '7daysAgo',
   'today',
   'ga:sessions');