I want to fetch Google Analytics data for my website via Google Analytics API. First, I went to developers console, I enabled Analytics API, then under credentials section I created new ClientID (Service account).
Now, this is my code
include "assets/src/templates/base.php";
require_once 'assets/src/Google/autoload.php';
$client_id = 'xxx.apps.googleusercontent.com'; //Client ID
$service_account_name = '[email protected]'; //Email Address
$key_file_location = 'zzz/key.p12'; //key.p12
echo pageHeader("Service Account Access");
if (strpos($client_id, "googleusercontent") == false
|| !strlen($service_account_name)
|| !strlen($key_file_location)) {
echo missingServiceAccountDetailsWarning();
exit;
}
$client = new Google_Client();
$client->setApplicationName("app");
$service = new Google_Service_Analytics($client);
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/analytics.readonly'),
$key
);
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();
$result = $service->data_ga->get(
'ga:AAA',
'2015-03-03',
'2015-03-03',
'ga:sessions');
?>
where AAA is my ViewID.
So, my problem is this: When I access this script on server it says
*"Fatal error: Uncaught exception 'Google_Service_Exception' with message 'Error calling GET https://www.googleapis.com/analytics/v3/data/ga?ids=ga%3A91249839&start-date=2015-03-03&end-date=2015-03-03&metrics=ga%3Asessions: (403) User does not have any Google Analytics account.' in C:\xampp\htdocs\test\assets\src\Google\Http\REST.php:110 Stack trace:
0 C:\xampp\htdocs\test\assets\src\Google\Http\REST.php(62): Google_Http_REST::decodeHttpResponse(Object(Google_Http_Request),
Object(Google_Client)) #1 [internal function]: Google_Http_REST::doExecute(Object(Google_Client), Object(Google_Http_Request)) #2 C:\xampp\htdocs\test\assets\src\Google\Task\Runner.php(174): call_user_func_array(Array, Array) #3 C:\xampp\htdocs\test\assets\src\Google\Http\REST.php(46): Google_Task_Runner->run() #4 C:\xampp\htdocs\test\assets\src\Google\Client.php(590): Google_Http_REST::execute(Object(Google_Client), Object(Google_Http_Request)) #5 C:\xampp\htdocs\test\assets\src\Google\Service\Resource.php(231): Google_Client->execute(Object(Google_Htt in C:\xampp\htdocs\test\assets\src\Google\Http\REST.php on line 110"*
Any suggestions?
Thank you in advance!
Regards, golobich
Edit: I've tried Google Books api and auth is working ok. (I've changed that link in $cred ofcourse.