Google API Oauth 2.0 cron job? - php

I have created a php script that uses the Google Analytics API, I want to run it with a cron job once an hour. It works fine in my browser, but I need to sign in from time to time with my gmail account and grant access.
How can I save my gmail login data in the php script, so it signs in automatically? This script will only use my login data, so it can be hard coded.
<?php
require_once 'Google/autoload.php';
session_start();
// ******************************************************** //
// Get these values from https://console.developers.google.com
// Be sure to enable the Analytics API
// ******************************************************** //
$client_id = 'xxxxxxxx';
$client_secret = 'xxxxxxxx';
$redirect_uri = 'http://example.com/xxxx';
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
$client->setAccessType('offline'); // Gets us our refreshtoken
//For loging out.
if ($_GET['logout'] == "1") {
unset($_SESSION['token']);
}
// Step 2: The user accepted your access now you need to exchange it.
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
// Step 1: The user has not authenticated we give them a link to login
if (!$client->getAccessToken() && !isset($_SESSION['token'])) {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
// Step 3: We have access we can now create our service
if (isset($_SESSION['token'])) {
print "<a class='logout' href='".$_SERVER['PHP_SELF']."?logout=1'>LogOut</a><br>";
print "Access from google: " . $_SESSION['token']."<br>";
$client->setAccessToken($_SESSION['token']);
$service = new Google_Service_Analytics($client);
// request user accounts
$accounts = $service->management_accountSummaries->listManagementAccountSummaries();
foreach ($accounts->getItems() as $item) {
echo "<b>Account:</b> ",$item['name'], " " , $item['id'], "<br /> \n";
foreach($item->getWebProperties() as $wp) {
echo '-----<b>WebProperty:</b> ' ,$wp['name'], " " , $wp['id'], "<br /> \n";
$views = $wp->getProfiles();
if (!is_null($views)) {
// note sometimes a web property does not have a profile / view
foreach($wp->getProfiles() as $view) {
echo '----------<b>View:</b> ' ,$view['name'], " " , $view['id'], "<br /> \n";
} // closes profile
}
} // Closes web property
} // closes account summaries
}
//Adding Dimensions
$params = array('dimensions' => 'ga:pagePath', 'metrics' => 'ga:timeOnPage,ga:uniquePageviews');
// requesting the data
$data = $service->data_ga->get("ga:xxxxxxxx", date("Y-m-d"), date("Y-m-d"), "ga:users,ga:sessions", $params );
?><html>
<?php echo date("Y-m-d") . " - ".date("Y-m-d"). "\n";?>
<table>
<tr>
<?php
//Printing column headers
foreach($data->getColumnHeaders() as $header){
print "<td>".$header['name']."</td>";
}
?>
</tr>
<?php
//printing each row.
foreach ($data->getRows() as $row) {
if($row[1]<7.0 && $row[2]>100 ){
$length = strlen($row[0]);
if($length<12){
$row[0] = substr($row[0], 3);
print $row[0];
$short_url=$row[0];
$blocked=1;
//PDO
// configuration
$dbhost = "localhost";
$dbname = "xxxxxxxxx";
$dbuser = "xxxxxxxxx";
$dbpass = "xxxxx";
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// query
$sql = "UPDATE urls SET blocked = :blocked WHERE short_url = :short_url";
$q = $conn->prepare($sql);
$q->execute(array(':short_url'=>$short_url,
':blocked'=>$blocked ));
}
print "<tr><td>".$row[0]."</td><td>".$row[1]."</td><td>".$row[2]."</td><td>".$row[3]."</td></tr>";
}
}
//printing the total number of rows
?>
<tr><td colspan="2">Rows Returned <?php print $data->getTotalResults();?> </td></tr>
</table>
</html>
?>

Use a service account instead.
A service account doesn’t need to prompt a user for access because you have to set it up. Go to the Google Analytics website in the Admin section for the Account you want to retrieve data from. This is very important it must be at the account level add this email address as a new user. just give them read access.
<?php
require_once 'Google/autoload.php';
session_start();
/************************************************
The following 3 values an befound in the setting
for the application you created on Google
Developers console. Developers console.
The Key file should be placed in a location
that is not accessable from the web. outside of
web root. web root.
In order to access your GA account you must
Add the Email address as a user at the
ACCOUNT Level in the GA admin.
************************************************/
$client_id = '[Your client id]';
$Email_address = '[YOur Service account email address Address]';
$key_file_location = '[Locatkon of key file]';
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$key = file_get_contents($key_file_location);
// seproate additional scopes with a comma
$scopes ="https://www.googleapis.com/auth/analytics.readonly";
$cred = new Google_Auth_AssertionCredentials($Email_address,
array($scopes),
$key);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$service = new Google_Service_Analytics($client);
//Adding Dimensions
$params = array('dimensions' => 'ga:userType');
// requesting the data
$data = $service->data_ga->get("ga:89798036", "2014-12-14", "2014-12-14", "ga:users,ga:sessions", $params );
?>
<html>
Results for date: 2014-12-14<br>
<table border="1">
<tr>
<?php
//Printing column headers
foreach($data->getColumnHeaders() as $header){
print "<td><b>".$header['name']."</b></td>";
}
?>
</tr>
<?php
//printing each row.
foreach ($data->getRows() as $row) {
print "<tr><td>".$row[0]."</td><td>".$row[1]."</td><td>".$row[2]."</td></tr>";
}
?>
<tr><td colspan="2">Rows Returned <?php print $data->getTotalResults();?> </td></tr>
</table>
</html>
code ripped from Google Service account Php

Related

Connecting to Google Calendar v3 API with PHP

I am completely lost... All I'm trying to do is get rid of this error message and log into Google API. I've created all the keys and added them to /src/Google/Config.php.
PHP Fatal error: Uncaught exception 'Google_Service_Exception' with message 'Error calling GET
https://www.googleapis.com/calendar/v3/users/me/calendarList/0qfrti6gst4q8hpl89utm8elno%40grou p.calendar.google.com?key=AIzaSyAiR_4OsoheCPbd7tU2u3QrqbEW_a2uVCc: (401) Login Required'
in C:\\Bitnami\\wampstack\\apache2\\htdocs\\yac\\google-api-php-
client\\src\\Google\\Http\\REST.php:79\nStack ...
Here's my (most likely) incorrect script:
session_start();
set_include_path( get_include_path() . PATH_SEPARATOR . 'google-api-php-client/src' );
include_once('google-api-php-client/src');
require_once('google-api-php-client/src/Google/Client.php');
require_once ('google-api-php-client/src/Google/Service/Calendar.php');
$client = new Google_Client();
$client->setApplicationName("YAC_Calendar");
$client->setDeveloperKey(<MY KEY>);
$service = new Google_Service_Calendar($client);
$calendarListEntry = $service->calendarList->get('0qfrti6gst4q8hpl89utm8elno#group.calendar.google.com');
echo $calendarListEntry->getSummary();
you need to login using Oauth before you can access the calendar. The only example I have on hand right now is one using Google Analytics API with PHP if you have any switching it over to Calendar let me know I will see if I can get a working example for that.
<?php
require_once 'Google/Client.php';
require_once 'Google/Service/Analytics.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setDeveloperKey("{devkey}");
$client->setClientId('{clientid}.apps.googleusercontent.com');
$client->setClientSecret('{clientsecret}');
$client->setRedirectUri('http://www.daimto.com/Tutorials/PHP/Oauth2.php');
$client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
//For loging out.
if ($_GET['logout'] == "1") {
unset($_SESSION['token']);
}
// Step 2: The user accepted your access now you need to exchange it.
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
// Step 1: The user has not authenticated we give them a link to login
if (!$client->getAccessToken() && !isset($_SESSION['token'])) {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
// Step 3: We have access we can now create our service
if (isset($_SESSION['token'])) {
print "<a class='logout' href='".$_SERVER['PHP_SELF']."?logout=1'>LogOut</a><br>";
$client->setAccessToken($_SESSION['token']);
$service = new Google_Service_Analytics($client);
// request user accounts
$accounts = $service->management_accountSummaries->listManagementAccountSummaries();
foreach ($accounts->getItems() as $item) {
echo "Account: ",$item['name'], " " , $item['id'], "<br /> \n";
foreach($item->getWebProperties() as $wp) {
echo ' WebProperty: ' ,$wp['name'], " " , $wp['id'], "<br /> \n";
$views = $wp->getProfiles();
if (!is_null($views)) {
foreach($wp->getProfiles() as $view) {
// echo ' View: ' ,$view['name'], " " , $view['id'], "<br /> \n";
}
}
}
} // closes account summaries
}
print "<br><br><br>";
print "Access from google: " . $_SESSION['token'];
?>
Code from my tutorial Google Oauth2 php

How to list Management Profiles with Google Analytics PHP API?

I am trying to retrieve the Google Analytics Management Profiles using the latest PHP client API (https://github.com/google/google-api-php-client).
I have the following code snippet:
// we've got the token, so set it
$google_client->setAccessToken($_SESSION['access_code']);
if ($google_client->getAccessToken()) {
$profiles = $google_analytics_service->management_profiles->listManagementProfiles("~all", "~all");
print "<h1>Profiles</h1><pre>" . print_r($profiles, true) . "</pre>";
}
/* $url = 'https://www.googleapis.com/analytics/v3/management/accounts/~all/webproperties/~all/profiles'; */
/* // json decode as array */
/* $analytics_auth = json_decode($_SESSION['access_code'], true); */
/* $ch = curl_init($url . '?access_token=' . $analytics_auth['access_token']); */
/* curl_exec($ch); */
/* curl_close($ch); */
The error message I get with the above is:
Error calling GET https://www.googleapis.com/analytics/v3/management/accounts/~all/webproperties/~all/profiles?key=AIza[SNIP]: (403) Access Not Configured
Note: However I decided to run the same with cURL and it returns a JSON array with the profiles (the commented code). Is this a bug, or me? What I do notice is that my access_token starts with "ya29".
I think you are missing a step:
<?php
require_once 'Google/Client.php';
require_once 'Google/Service/Analytics.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setDeveloperKey("{developerkey}");
$client->setClientId('{clientID}.apps.googleusercontent.com');
$client->setClientSecret('{Client secret}');
$client->setRedirectUri('http://www.daimto.com/Tutorials/PHP/Oauth2.php');
$client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
//For loging out.
if ($_GET['logout'] == "1") {
unset($_SESSION['token']);
}
// Step 2: The user accepted your access now you need to exchange it.
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
// Step 1: The user has not authenticated we give them a link to login
if (!$client->getAccessToken() && !isset($_SESSION['token'])) {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
// Step 3: We have access we can now create our service
if (isset($_SESSION['token'])) {
print "<a class='logout' href='".$_SERVER['PHP_SELF']."?logout=1'>LogOut</a><br>";
$client->setAccessToken($_SESSION['token']);
$service = new Google_Service_Analytics($client);
// request user accounts
$accounts = $service->management_accountSummaries->listManagementAccountSummaries();
foreach ($accounts->getItems() as $item) {
echo "Account: ",$item['name'], " " , $item['id'], "<br /> \n";
foreach($item->getWebProperties() as $wp) {
echo ' WebProperty: ' ,$wp['name'], " " , $wp['id'], "<br /> \n";
$views = $wp->getProfiles();
if (!is_null($views)) {
foreach($wp->getProfiles() as $view) {
// echo ' View: ' ,$view['name'], " " , $view['id'], "<br /> \n";
}
}
}
} // closes account summaries
}
print "<br><br><br>"; // fix syntax
print "Access from google: " . $_SESSION['token'];
?>
Due to issue with the session_start and headers its a bit out of order. I added some comments to help you understand what its doing. Its a simple script but you can test it here Dummy Example for Hal9k
The 403 problem was because the correct IP address wasn't set for the server applications key. This can be set in the Google Developers' Console. It's odd, however, that using cURL bypassed this.
Public API access
Use of this key does not require any user action or consent, does not grant access to any account information, and is not used for authorization.
Key for server applications API key: AI[snip]
IPs: 91.[snip] 109.[snip] Make sure correct IP address is set here

Get post from Google+ without browser's authentication in google's account via PHP

I'm want to get google+ posts via PHP, but google requires my login via browser.
It's possible provide the account's authentication via PHP, allowing me to get the posts without login every time I want to get the posts?
The code is:
<?php
require_once 'src/Google_Client.php';
require_once 'src/contrib/Google_PlusService.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Google+ PHP Starter Application");
// Visit https://code.google.com/apis/console?api=plus to generate your
// client id, client secret, and to register your redirect uri.
$client->setClientId('clientid');
$client->setClientSecret('clientsecret');
$client->setRedirectUri('http://localhost/OLA/google+/simple.php/b.html');
$client->setDeveloperKey('apikey');
$plus = new Google_PlusService($client);
if (isset($_GET['logout'])) {
unset($_SESSION['token']);
}
if (isset($_GET['code'])) { // login stuff <-------
if (strval($_SESSION['state']) !== strval($_GET['state'])) {
die("The session state did not match.");
}
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if ($client->getAccessToken()) {
//$me = $plus->people->get('me');
//print "Your Profile: <pre>" . print_r($me, true) . "</pre>";
$params = array('maxResults' => 100);
$activities = $plus->activities->listActivities('me', 'public', $params);
//print "Your Activities: <pre>" . print_r($activities, true) . "</pre>";
$params = array(
'orderBy' => 'recent',
'maxResults' => '20'//20
);
$q = "tag";
$results = $plus->activities->search($q, $params);
//code ....
// The access token may have been updated lazily.
$_SESSION['token'] = $client->getAccessToken();
} else {
// This is the part that logs me in via browser <------
$state = mt_rand();
$client->setState($state);
$_SESSION['state'] = $state;
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
?>
Yep, just call as you would and use the simple API access key - you can retrieve public information, but you will have to supply to long numeric ID for the user you're retrieving posts for rather than using the string 'me'. Take a look at the latest version of the library as well: https://github.com/google/google-api-php-client as well. You need to setup your client as you were doing, with an API key from a project which has the Google+ enabled on https://developers.google.com/console
$client = new Google_Client();
$client->setApplicationName("Post Fetcher");
$client->setDeveloperKey('PUT_YOUR_API_KEY_HERE_OR_IT_WONT_WORK');
$plus = new Google_Service_Plus($client);
$activities = $this->plus->activities
->listActivities("118051310819094153327", "public");

Google Analytics Daily Upload Script not working

I have been working my way through the Hello Analytics Tutorial here - https://developers.google.com/analytics/solutions/articles/hello-analytics-api
and I have been using Ewan Hemings Example here - http://www.ewanheming.com/upload-cost-data-google-analytics to try and upload my external cost data into Google analytics's.
I have been testing the POST data using the API Explorer - https://developers.google.com/apis-explorer/#s/analytics/v3/analytics.management.dailyUploads.upload and the post master app. Although it is not returning any errors the data is not appearing in my Analytics.
I can print the data to the screen and its seems to be formatted correctly so I am a bit stumped. Any help would be apprenticed, even if you could offer a suggestion for debugging.
<?php
// The filename of the performance report
$reportFile = "Bing.csv";
// Hard code the source and medium
$source = "acme ads";
$medium = "cpc";
// Upload file headers
$headers = array(
"ga:source",
"ga:medium",
"ga:campaign",
"ga:adGroup",
"ga:adContent",
"ga:keyword",
"ga:impressions",
"ga:adClicks",
"ga:adCost"
);
$headerRow = implode(",", $headers);
// Create an array to store the data to upload
$uploadFiles = array();
// Open the performance report
$fp = fopen($reportFile, "r");
// Process each row in the file
while ($row = fgetcsv($fp)) {
// Attempt to create a date from the first column of the row
$date = isset($row[0]) ?
date_create_from_format('M d, Y', $row[0]) : null;
// If the date creation was successful, this is a data row
if ($date instanceof DateTime) {
// Extract the columns from the row
$campaign = $row[1];
$adgroup = $row[2];
$headline = $row[3];
$keyword = $row[4];
$impressions = $row[5];
$clicks = $row[6];
$cost = $row[7];
// Don't upload rows with no impressions
if ($impressions > 0) {
// Format the date
$uploadDate = date_format($date, 'Y-m-d');
// If there isn't a file for the upload date, then create one
if (!isset($uploadFiles[$uploadDate])) {
// Add the headers to the file
$uploadFiles[$uploadDate] = "$headerRow\n";
}
// Add the row to the file
$uploadRow = array(
"\"$source\"",
"\"$medium\"",
"\"$campaign\"",
"\"$adgroup\"",
"\"$headline\"",
"\"$keyword\"",
$impressions,
$clicks,
$cost
);
$uploadFiles[$uploadDate] .= implode(",", $uploadRow) . "\n";
}
}
}
fclose($fp);
require_once 'src/Google_Client.php';
require_once 'src/contrib/Google_AnalyticsService.php';
session_start();
$client = new Google_Client();
$client->setApplicationName('Hello Analytics API Sample');
// Visit //code.google.com/apis/console?api=analytics to generate your
// client id, client secret, and to register your redirect uri.
$client->setClientId('69673577u537j57n57j7jjm0.apps.googleusercontent.com');
$client->setClientSecret('67qg6646744724724gK');
$client->setRedirectUri('http://www.mywebsite.co.uk/analytics/GAUpload.php');
$client->setDeveloperKey('AIz42172147246h46h630JuY');
$client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
// Magic. Returns objects from the Analytics Service instead of associative arrays.
$client->setUseObjects(true);
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if (!$client->getAccessToken()) {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
} else {
$analytics = new Google_AnalyticsService($client);
foreach (array_keys($uploadFiles) as $uploadDate) {
$analytics->management_dailyUploads->upload('46856856853', 'UA-4276753-1', 'o867567568560XJY4qg', '2013-09-02', 1, 'cost', array("reset" => true, "data" => $uploadFiles[$uploadDate], 'mimeType' => 'application/octet-stream', 'uploadType' => 'media'));
}
}
?>

OAuth with Google Analytics API reports invalid token

the following code runs through well, but some times reports "Invalid token". It happens, when I have foreign website in my ID list. But when I log in with email/password pair, it runs well till the end. Any idea what is wrong?
Cheers:
Bob
<?php
/*
API ACCESS PANEL:
https://code.google.com/apis/console/
*/
session_start(); #the includes are as follows, using also gapi.class.php
require_once 'src/apiClient.php';
require_once 'src/contrib/apiAnalyticsService.php';
ini_set('display_errors', '1');
$client = new apiClient();
$client->setApplicationName("Google Analytics PHP Starter Application");
/*
Visit https://code.google.com/apis/console?api=analytics to generate your client id, client secret, and to register your redirect uri.
*/
$client->setClientId('');# MUST SET UP!
$client->setClientSecret('');# MUST SET UP!
$client->setRedirectUri('http://localhost/analytics/chart_server.php');# MUST SET UP!
$client->setDeveloperKey('');# MUST SET UP!
// requestReportData first parameter, an Analytics Profil ID must defined here:
$ga_profile_id='';# MUST SET UP!
//////////////////////////////////////////////////////////////////////////////
$service = new apiAnalyticsService($client);
// logout
if (isset($_GET['logout'])) {
unset($_SESSION['token']);
exit;
}
// get the tooken from Google, store into the session, call back this script with header-location
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
exit;
}
// if we got token in the session-ben, passing to $client (this is the OAuth client)
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
// if the token valid, then we have access:
if ($client->getAccessToken()){
#$props = $service->management_webproperties->listManagementWebproperties("~all");
/*
print "Web Properties " . print_r($props, true);
*/
print("auth OK");//ok
print_r($client->getAccessToken()); // print out for test
$_SESSION['token'] = $client->getAccessToken();// stor eback to the session
} else { // Authorize with OAuth cause we have no valid access token
#https://www.google.com/analytics/feeds/
#https://www.googleapis.com/auth/analytics.readonly
$scope="https://www.google.com/analytics/feeds/"; // we'd like to access this
$authUrl = $client->createAuthUrl($scope);
header("Location: ".$authUrl); /* Redirect browser */
# print "<a class='login' href='$authUrl'>Connect Me!</a>";
exit;
}
// test printout, OAuth account object:
$accounts = $service->management_accounts->listManagementAccounts();
print "List of accounts" . print_r($accounts, true) .;
//////////////////////////////////////////////////////////////////////////////////////////////
// Here is the Google Analytics API call, and the "TOKEN INVALID 401" error message //
//////////////////////////////////////////////////////////////////////////////////////////////
require 'gapi.class.php';
$ga = new gapi(null,null,$_SESSION['token']); // access token instead of mail, password pair
#$token=$ga->getAuthToken();# $_SESSION['token']
// http://code.google.com/p/gapi-google-analytics-php-interface/wiki/GAPIDocumentation
// requestReportData($report_id, $dimensions, $metrics, $sort_metric=null, $filter=null, $start_date=null, $end_date=null, $start_index=1, $max_results=30)
$dimensions=array('browser','date');// x coord
$metrics=array('visits','pageLoadTime','uniquePageviews'); // y coord
$sort_metric="-date"; #descending order
$filter = '';
$startDate = '2012-04-01';
$endDate = '2012-04-12';
$start_index=1;
$max_results=50;
#$ga->requestReportData($accProfiles[$profileNum]->getProfileId(),$dimensions,$metrics,$sort_metric,$filter, $start_date, $end_date, $start_index, $max_results );
$ga->requestReportData($ga_profile_id, $dimensions, $metrics, $sort_metric, $filter, $startDate, $endDate, $start_index, $max_results );
$results=$ga->getResults();
// test:
echo "Google Analytics data ";print_r($results);
#echo "#####".$ga->getMetrics();
// Set the JSON header
//header("Content-type: text/json");
#echo json_encode( array($dim, $met1, $met2, $met3 ) );
?>
Just forget the gapi.class.php. It is slow, and works only with USR/PSW.
The apiAnalyticsService is also slow, but works with tokens well.
Try changing your scope from this:
$scope="https://www.google.com/analytics/feeds/";
to this:
$scope="https://www.googleapis.com/auth/analytics.readonly";

Categories