PHPackages                             timgws/google-analytics-api - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. timgws/google-analytics-api

ActiveLibrary[API Development](/categories/api)

timgws/google-analytics-api
===========================

Simple class to query the Google Analytics API v3 with PHP

019.8k1PHP

Since Mar 13Pushed 10y ago1 watchersCompare

[ Source](https://github.com/timgws/Google-Analytics-API-PHP)[ Packagist](https://packagist.org/packages/timgws/google-analytics-api)[ RSS](/packages/timgws-google-analytics-api/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (1)

Google Analytics API PHP
========================

[](#google-analytics-api-php)

This is a simple class to use OAuth 2.0 with Google and query the Google Analytics API v3 with PHP. cURL and OpenSSL are required!

The class supports getting the access tokens for either **web applications** and **service accounts** registered in the Google APIs console.

[See the Google OAuth2 documentation for further information](https://developers.google.com/accounts/docs/OAuth2).

Reporting issues
================

[](#reporting-issues)

Despite my best efforts, I still have not reached a state of perfection. Feel free to either:

- **[Add new issues to the bug tracker](https://github.com/timgws/Google-Analytics-API-PHP/issues)**
- **[Add a pull request](https://github.com/timgws/Google-Analytics-API-PHP/pulls)**

Getting Started!
================

[](#getting-started)

This is a refactor of `wanze/Google-Analytics-API-PHP`. You should add this repository into your composer.json file!

"How to" guide for timgws/Google-Analytics-API-PHP
--------------------------------------------------

[](#how-to-guide-for-timgwsgoogle-analytics-api-php)

### 1. Basic Setup

[](#1-basic-setup)

- Create a Project in the Google 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

[](#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

[](#21-web-applications)

```
include('vendor/autoload.php');
use timgws\GoogleAnalytics\API as Analytics;

$ga = new Analytics();
$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

[](#22-service-accounts)

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

```
include('vendor/autoload.php');
use timgws\GoogleAnalytics\API as Analytics;

$ga = new Analytics('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

[](#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

[](#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();
```

Old GAPI wrapper
================

[](#old-gapi-wrapper)

A dusty GAPI wrapper is included in `gapi_wrapper/`

### Resources

[](#resources)

- [Metrics &amp; 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/)

###  Health Score

25

—

LowBetter than 37% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity20

Limited adoption so far

Community14

Small or concentrated contributor base

Maturity41

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 77.8% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

### Community

Maintainers

![](https://www.gravatar.com/avatar/e950378ef4ed66fb3df70c8b59a7bf9ba5df39c8b6be3f85a4ae484af4992d77?d=identicon)[timgws](/maintainers/timgws)

---

Top Contributors

[![timgws](https://avatars.githubusercontent.com/u/1050232?v=4)](https://github.com/timgws "timgws (35 commits)")[![wanze](https://avatars.githubusercontent.com/u/2118742?v=4)](https://github.com/wanze "wanze (8 commits)")[![jeroenmoors](https://avatars.githubusercontent.com/u/1665245?v=4)](https://github.com/jeroenmoors "jeroenmoors (1 commits)")[![WouterSioen](https://avatars.githubusercontent.com/u/1398405?v=4)](https://github.com/WouterSioen "WouterSioen (1 commits)")

### Embed Badge

![Health badge](/badges/timgws-google-analytics-api/health.svg)

```
[![Health](https://phpackages.com/badges/timgws-google-analytics-api/health.svg)](https://phpackages.com/packages/timgws-google-analytics-api)
```

###  Alternatives

[stripe/stripe-php

Stripe PHP Library

4.0k143.3M480](/packages/stripe-stripe-php)[twilio/sdk

A PHP wrapper for Twilio's API

1.6k92.9M272](/packages/twilio-sdk)[facebook/php-business-sdk

PHP SDK for Facebook Business

90821.9M34](/packages/facebook-php-business-sdk)[meilisearch/meilisearch-php

PHP wrapper for the Meilisearch API

74513.7M114](/packages/meilisearch-meilisearch-php)[google/gax

Google API Core for PHP

265103.1M454](/packages/google-gax)[google/common-protos

Google API Common Protos for PHP

173103.7M50](/packages/google-common-protos)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
