Giter VIP home page Giter VIP logo

google-analytics-api-php's Introduction

#Google Analytics API PHP

Simple class to set up Oauth 2.0 with Google and query the Google Analytics API v3 with PHP. Curl is required! The class supports getting the access tokens for web applications and service accounts registered in the Google APIs console.
See the documentation for further informations: https://developers.google.com/accounts/docs/OAuth2

##1. Basic Setup

  • Create a Project in the Google APIs Console: https://code.google.com/apis/console/
  • Enable the Analytics API under Services
  • Under API Access: Create an Oauth 2.0 Client-ID
  • Give a Product-Name, choose Web Application or Service Account depending on your needs
  • Web Application: Set a redirect-uri in the project which points to your apps url
  • Service Account: Download the private key (.p12 file)

##2. Set up Auth

Depending on the chosen application type, the setup is slightly different. This section describes both ways independently.

###2.1 Web applications

include('GoogleAnalyticsAPI.class.php');

$ga = new GoogleAnalyticsAPI(); 
$ga->auth->setClientId('your_client_id'); // From the APIs console
$ga->auth->setClientSecret('your_client_secret'); // From the APIs console
$ga->auth->setRedirectUri('redirect_uri'); // Url to your app, must match one in the APIs console

// Get the Auth-Url
$url = $ga->auth->buildAuthUrl();

Provide a link to the Auth-Url. The user has to log in with his Google Account, accept that your App will access the Analytics Data. After completing this steps, the user will be redirected back to the redirect-uri along with a code. This code is needed to get the tokens.

$code = $_GET['code'];
$auth = $ga->auth->getAccessToken($code);

// Try to get the AccessToken
if ($auth['http_code'] == 200) {
	$accessToken = $auth['access_token'];
	$refreshToken = $auth['refresh_token'];
	$tokenExpires = $auth['expires_in'];
	$tokenCreated = time();
} else {
	// error...
}

With the accessToken you can query the API for the given time (seconds) in $tokenExpires. If you need to query the API beyond this time, you should store the refreshToken along with a timestamp in the Database / Session. If the accessToken expires, you can get a new one with the refreshToken.

// Check if the accessToken is expired
if ((time() - $tokenCreated) >= $tokenExpires) {
	$auth = $ga->auth->refreshAccessToken($refreshToken);
	// Get the accessToken as above and save it into the Database / Session
}

###2.2 Service accounts

Copy the email address from the APIs console ([email protected]). Visit your GA admin and add this email as a user to your properties.

include('GoogleAnalyticsAPI.class.php');

$ga = new GoogleAnalyticsAPI('service');
$ga->auth->setClientId('your_client_id'); // From the APIs console
$ga->auth->setEmail('your_email_addy'); // From the APIs console
$ga->auth->setPrivateKey('/super/secure/path/to/your/privatekey.p12'); // Path to the .p12 file

To query the API, you need to obtain an access token. This token is valid one hour, afterwards you'll need to get a new token. You can store the token in the database/session.

$auth = $ga->auth->getAccessToken();

// Try to get the AccessToken
if ($auth['http_code'] == 200) {
	$accessToken = $auth['access_token'];
	$tokenExpires = $auth['expires_in'];
	$tokenCreated = time();
} else {
	// error...
}

##3. Find the Account-ID

Before you can query the API, you need the ID of the Account you want to query the data. The ID can be found like this:

// Set the accessToken and Account-Id
$ga->setAccessToken($accessToken);
$ga->setAccountId('ga:xxxxxxx');

// Load profiles
$profiles = $ga->getProfiles();
$accounts = array();
foreach ($profiles['items'] as $item) {
	$id = "ga:{$item['id']}";
	$name = $item['name'];
	$accounts[$id] = $name;
}
// Print out the Accounts with Id => Name. Save the Id (array-key) of the account you want to query data. 
// See next chapter how to set the account-id.
print_r($accounts);

##4. Query the Google Analytics API

Once you have a valid accessToken and an Account-ID, you can query the Google Analytics API. You can set some default Query Parameters that will be executed with every query.

// Set the accessToken and Account-Id
$ga->setAccessToken($accessToken);
$ga->setAccountId('ga:xxxxxxx');

// Set the default params. For example the start/end dates and max-results
$defaults = array(
	'start-date' => date('Y-m-d', strtotime('-1 month')),
	'end-date' => date('Y-m-d'),
);
$ga->setDefaultQueryParams($defaults);

// Example1: Get visits by date
$params = array(
	'metrics' => 'ga:visits',
	'dimensions' => 'ga:date',
);
$visits = $ga->query($params);

// Example2: Get visits by country
$params = array(
	'metrics' => 'ga:visits',
	'dimensions' => 'ga:country',
	'sort' => '-ga:visits',
	'max-results' => 30,
	'start-date' => '2013-01-01' //Overwrite this from the defaultQueryParams
); 
$visitsByCountry = $ga->query($params);

// Example3: Same data as Example1 but with the built in method:
$visits = $ga->getVisitsByDate();

// Example4: Get visits by Operating Systems and return max. 100 results
$visitsByOs = $ga->getVisitsBySystemOs(array('max-results' => 100));

// Example5: Get referral traffic
$referralTraffic = $ga->getReferralTraffic();

// Example6: Get visits by languages
$visitsByLanguages = $ga->getVisitsByLanguages();

###Metrics & Dimensions Reference: https://developers.google.com/analytics/devguides/reporting/core/dimsmets

###Google Analytics Query Explorer for testing queries and results: http://ga-dev-tools.appspot.com/explorer/

google-analytics-api-php's People

Contributors

jeroenmoors avatar wanze avatar woutersioen avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

google-analytics-api-php's Issues

i want to get account_id after login

when someone person login with google , after login i want there account id , web property id and view id auto.

please help me how can i fetch there Analytics id , beacuse i want every user see there Analytices deatils after login.

thanks

ERROR connecting to Analytics API

Since 22th october, I keep getting "ERROR connecting to Analytics API".
Everything was working fine since months, and I did not change anything.

Any idea how to debug this ?

Thanks...

typo in manual

// Example5: Get referral traffic
$referralTraffic = $ga->getRefferralTraffic();

should be named as in class
getReferralTraffic($params=array()) {

getting accessToken error with Analytics

Hi. I made everything correct, created an Service account, added it as a full authenticated user on GA profile, and use Client ID, Email address and Private Key correctly. But i can't get a accessToken from Analytics service. Could you help me about this issue please?

untitled

Not receiving 'access token' with all the right credentials

Hey there, here's the error I'm receiving when using the basic example:

Sorry, something wend wrong retrieving the oAuth tokens

I've entered my credentials as according to API Console and for some reason I'm not getting an access token.

getting accessToken error with Analytics

Hello,

I am having the same issue as mahony0, where the script is throwing back :

var_dump($ga) returns :

object(GoogleAnalyticsAPI) (5) {
["auth"]=>
object(GoogleOauthService) (5) {
["email":protected]=>
string(75) "[email protected]"
["privateKey":protected]=>
string(55) "XXXXX-privatekey.p12"
["password":protected]=>
string(10) "notasecret"
["assoc":protected]=>
bool(true)
["clientId":protected]=>
string(72) "874775054712- XXXXX.apps.googleusercontent.com"
}
["accessToken":protected]=>
string(0) ""
["accountId":protected]=>
string(0) ""
["assoc":protected]=>
bool(true)
["defaultQueryParams":protected]=>
array(3) {
["start-date"]=>
string(10) "2013-10-11"
["end-date"]=>
string(10) "2013-11-11"
["metrics"]=>
string(9) "ga:visits"
}
}

Fatal error: Uncaught exception 'Exception' with message 'You must provide an accessToken' in /home/ftp/XXXXX/GoogleAnalyticsAPI.class.php:162
Stack trace:
/home/ftp/XXXXX/test2.php(29): GoogleAnalyticsAPI->getProfiles()
{main}
thrown in /home/ftp/XXXXX/GoogleAnalyticsAPI.class.php on line 162

and $auth = $ga->auth->getAccessToken();
print_r($auth) returns :

Array
(
[http_code] => 200
[access_token] => ya29.AHES6ZRZR2DkYIs5MvKEiLhtXXXXXXX1d1o1hmg
[token_type] => Bearer
[expires_in] => 3600
)

I tried the work around with the curl function but still the same issue, not sure why this issue occurs as I am getting an access token. I tried on a php 5.4 and 5.3 version same issue.

What do you think is the issue here? Let me know if you need more info to try to tackle this issue.

Thanks.

Something wend wrong retrieving the oAuth tokens

Hi,

I am running this script in my local machine with 127.0.0.1 URL but I am getting below URL:

Sorry, something wend wrong retrieving the oAuth tokens

Please guide me to resolve this error.

strtotime() and date() functions

I'm getting this after trying to run my script:

Warning: strtotime(): It is not safe to rely on the system's timezone settings. You are >required to use the date.timezone setting or the date_default_timezone_set() >function. In case you used any of those methods and you are still getting this >warning, you most likely misspelled the timezone identifier. We selected >'Europe/Berlin' for 'CEST/2.0/DST' instead in >/path/to/GoogleAnalytics>API.class.php on line 68```

Warning: date(): It is not safe to rely on the system's timezone settings. You are >required to use the date.timezone setting or the date_default_timezone_set() >function. In case you used any of those methods and you are still getting this >warning, you most likely misspelled the timezone identifier. We selected >'Europe/Berlin' for 'CEST/2.0/DST' instead in >/path/to/GoogleAnalyticsAPI.class.php on line 68

php -v

PHP 5.3.15 with Suhosin-Patch (cli) (built: Aug 24 2012 17:45:44)
Copyright (c) 1997-2012 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2012 Zend Technologies

Maybe a default timezone with a 'global' variable should be enough.
Great class anyway :)

Can we automate this step using PHP or JavaScript

##1. Basic Setup

Create a Project in the Google APIs Console: https://code.google.com/apis/console/
Enable the Analytics API under Services
Under API Access: Create an Oauth 2.0 Client-ID
Give a Product-Name, choose Web Application or Service Account depending on your needs
Web Application: Set a redirect-uri in the project which points to your apps url
Service Account: Download the private key (.p12 file)

Authentication problem

I am getting authentication problem, will you please guide me regarding this. Check screenshot please.
analytical_autentication

Invalid grant_type for service account auth

I am using service account method to auth, but even if everything is correct, I got an error after call $ga->auth->getAccessToken();.
The http_code is 400, and I got the error invalid_grant.

Is there something else to do ?

Ok just my server clock was not set properly.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.