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