Reputation: 1
I am trying to create a reporting system that will utilize google analytics API. However, since my PHP script will be started with a cron job (not a browser), I can't use the OAuth method and I don't want to refresh the token every hour (especially night time). I hope that I can automate the process.
I hope that you can help.
Here is what I have as code, however, it is not working: I catch an exception "(401) Login Required".
<?php
include_once "templates/base.php";
echo pageHeader("Simple API Access");
require_once realpath(dirname(__FILE__) . '/../autoload.php');
$client = new Google_Client();
$client->setApplicationName("MY_APP_NAME");
$apiKey = "MY_OWN_API";
if ($apiKey == '<YOUR_API_KEY>') {
echo missingApiKeyWarning();
}
$client->setDeveloperKey($apiKey);
$client->setAccessType('offline');
$service = new Google_Service_Analytics($client);
echo '<pre>';
$analytics_id = 'ga:ANALYTICS_ID';
$lastWeek = date('Y-m-d', strtotime('-1 week'));
$today = date('Y-m-d');
try {
$results = $service->data_ga->get($analytics_id, $lastWeek, $today, 'ga:visits');
echo '<b>Number of visits this week:</b> ';
echo $results['totalsForAllResults']['ga:visits'];
} catch (Exception $e) {
echo 'There was an error : - ' . $e->getMessage();
}
echo pageFooter(__FILE__);
Thank you in advance!
Upvotes: 0
Views: 131
Reputation: 127
OAuth is required in order to use Google API service. However you can use "OAuth 2.0 for Server to Server", in here ISS email address is required what you can get from Google Developer Console. Follow the instruction in this links : 'https://developers.google.com/accounts/docs/OAuth2ServiceAccount'.
I am using the same procedure to have OAuth from the backend and it is working like charm. Good Luck.
Upvotes: 1