Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Google Analytics API - Simple example

I am trying to set some basic example of using Google Analytics with this library: https://github.com/google/google-api-php-client

For starter I have:

<?php

require_once 'Google/Client.php';
require_once 'Google/Service/Analytics.php';
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setDeveloperKey("MY_SECRET_API"); //security measures
$service = new Google_Service_Analytics($client);

$results = $service->data_ga;

echo '<pre>';
print_r($results);
echo '</pre>';

Q: How to get data from Google Analytics from this query ?

/*
  https://www.googleapis.com/analytics/v3/data/
  ga?ids=ga%123456
  &dimensions=ga%3Acampaign
  &metrics=ga%3Atransactions
  &start-date=2013-12-25
  &end-date=2014-01-08
  &max-results=50
 */
like image 740
Ing. Michal Hudak Avatar asked Jan 09 '14 15:01

Ing. Michal Hudak


1 Answers

$client->setDeveloperKey("MY_SECRET_API");

First of all, for as far as I experienced this won't work for authentication, you'll need to use a OAuth2 authentication. There are two options to do this, using client ID for web application or using a service account. Authorization api

After you have this, you can make a call like this. (I use a service account here)

First authenticate:

$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);

Make a call:

$ids = 'ga:123456'; //your id
$startDate = '2013-12-25';
$endDate = '2014-01-08';
$metrics = 'ga:transactions';

$optParams = array(
    'dimensions' => 'ga:campaign',
    'max-results' => '50'
);

$results = $service->data_ga->get($ids, $startDate, $endDate, $metrics, $optParams);

//Dump results
echo "<h3>Results Of Call:</h3>";

echo "dump of results";
var_dump($results);

echo "results['totalsForAllResults']";
var_dump($results['totalsForAllResults']);

echo "results['rows']";
foreach ($results['rows'] as $item) {
    var_dump($item);
}
like image 168
Prutpot Avatar answered Oct 11 '22 08:10

Prutpot