<?php function getService() { require_once 'vendor/autoload.php'; $service_account_email = 'xxx'; $key_file_location = '/'; $client = new Google_Client(); $client->setApplicationName("MyAnalyticsApp"); $analytics = new Google_Service_Analytics($client); $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; } function getFirstprofileId(&$analytics){ $accounts = $analytics->management_accounts->listManagementAccounts(); if(count($accounts->getItems()) > 0){ $items = $accounts->getItems(); $firstAccountId = $items[0]->getId(); $properties = $analytics->management_webproperties ->listManagementWebproperties($firstAccountId); if (count($properties->getItems()) > 0){ $items = $properties->getItems(); $firstPropertyId = $items[0]->getId(); $profiles = $analytics->management_profiles ->listManagemetProfiles($firstAccountId, $firstPropertyId); if(count($profiles->getItems()) > 0){ $items = $profiles->getItems(); return $items[0]->getId(); } else { throw new Exception('No views (profiles) found for this user.'); } } else { throw new Exception('No properties found for this user.'); } } else { throw new Exception('No accounts found for this user.'); } } function getResult(&$analytics, $profileId){ return $analytics->data_ga->get( 'ga:' . $profileId, '7daysAgo', 'today', 'ga:sessions'); } function printResults(&$results){ if (count($results->getRows()) > 0){ $profileName = $results->getProfileInfo()->getProfileName(); $rows = $results->getRows(); $sessions = $rows[0][0]; print "First view (profile) found: $profileName\n"; print "Total sessions: $sessions\n"; } else { print "No results found.\n"; } } $analytics = getService(); $profile = getFirstProfileId($analytics); $results = getResults($analytics, $profile); printResults($results); ?>