简体   繁体   中英

Get events data from Google Analytics API with PHP

I want to get events of one of my apps that uses Google Analytics. I am little confused with example given in the official documentation . I make it work but i don't understand how to use it for my case.

require_once 'GA/vendor/autoload.php';

// Start a session to persist credentials.
session_start();

// Create the client object and set the authorization configuration
// from the client_secretes.json you downloaded from the developer console.
$client = new Google_Client();
$client->setAuthConfigFile('client_secrets.json');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);

// If the user has already authorized this app then get an access token
// else redirect to ask the user to authorize access to Google Analytics.
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
  // Set the access token on the client.
  $client->setAccessToken($_SESSION['access_token']);

  // Create an authorized analytics service object.
  $analytics = new Google_Service_Analytics($client);

After this code I want to get events data - how should I specify counter id, and event info?

Using Query Explorer I managed to created query that I need:

googleapis.com/analytics/v3/data/ga?ids=ga%3A111111&start-date=30daysAgo&end-date=2016-05-11&metrics=ga%3AtotalEvents&dimensions=ga%3AeventLabel

I am not sure what you mean by counter id. You have your analytics service you just need to make the request now.

$params = array('dimensions' => 'ga:AeventLabel');  
// requesting the data  
$data = $analytics->data_ga->get("ga:89798036", "30daysAgo", "2016-05-11", "ga:totalEvents", $params );
// displaying the data
foreach ($data->getRows() as $row) {        
            print "ga:AeventLabel ".$row[0]." ga:totalEvents ".$row[1]";     
        }

I use this class with the following code and it works well:

require 'GoogleAPI/gapi.class.php';
define('ga_profile_id','YOUR-DEV-ID');

$ga = new gapi('YOUR-DEV-ID@developer.gserviceaccount.com','GoogleAPI/cert.p12');

$ga->requestReportData('YOUR-APP-ID',array('eventAction'),array('visitors'),null,"eventAction==loginViaWebsite",$"2016-05-11","2016-05-11");
$logins = $ga->getResults();
if($logins) $logins = $logins[0]->getMetrics();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM