widop / google-analytics

Google certificate-based authentication in server-to-server interactions with google analytics for PHP 5.3+
MIT License
27 stars 20 forks source link

[Improvement] Enable Real Time Data API #14

Open nivv opened 9 years ago

nivv commented 9 years ago

First of all, thanks for a great package!

Today I was looking into getting real time data from the Google Analytics API. It's pretty straightforward. The only thing you need to change is the URL in the Query class.

From:

//Widop\GoogleAnalytics\Query;
const URL = 'https://www.googleapis.com/analytics/v3/data/ga';

To:

//Widop\GoogleAnalytics\Query;
const URL = 'https://www.googleapis.com/analytics/v3/data/realtime';

Maybe there could be an option to override the default when we want to query the realtime api?

This is how it works after changing the URL in the Query class

$this->query->setStartDate(new \DateTime('-1hour'));
$this->query->setEndDate(new \DateTime());
$this->query->setMetrics(array('rt:activeUsers'));
$response = $this->getResponse();
dd($response->getTotalsForAllResults());
//Outputs: array: [ "rt:activeUsers" => "5"]

I've made a pull request for this functionality. See #15. (The current URL is still default: https://www.googleapis.com/analytics/v3/data/ga)

When using the proposed PR you could go about it as this:

$this->query->setServiceURL('https://www.googleapis.com/analytics/v3/data/realtime');
$this->query->setStartDate(new \DateTime('-1hour'));
$this->query->setEndDate(new \DateTime());
$this->query->setMetrics(array('rt:activeUsers'));
$response = $this->getResponse();
dd($response->getTotalsForAllResults());
//Outputs: array: [ "rt:activeUsers" => "5"]
bdelbasso commented 9 years ago

+1

statista-oss commented 9 years ago

+1