timgws/google-analytics-api

一个简单的类,用于使用PHP查询Google Analytics API v3

dev-master 2016-03-13 04:18 UTC

This package is auto-updated.

Last update: 2024-09-08 11:38:12 UTC


README

这是一个简单的类,用于使用OAuth 2.0与Google进行交互,并通过PHP查询Google Analytics API v3。需要cURL和OpenSSL!

该类支持获取在Google APIs控制台中注册的 网络应用服务帐户 的访问令牌。

有关更多信息,请参阅Google OAuth2文档.

报告问题

尽管我已尽力,但我仍未达到完美的状态。您可以自由地

入门!

这是对 wanze/Google-Analytics-API-PHP 的重构。您应该在composer.json文件中添加此存储库!

timgws/Google-Analytics-API-PHP的“如何”指南

1. 基本设置

  • 在Google APIs控制台中创建一个项目: https://code.google.com/apis/console/
  • 在服务下启用Analytics API
  • 在API访问下:创建一个OAuth 2.0客户端ID
  • 提供一个产品名称,根据需要选择 网络应用服务帐户
  • 网络应用:在项目中设置一个重定向URI,指向您的应用程序的URL
  • 服务帐户:下载私钥(.p12文件)

2. 设置授权

根据选择的应用程序类型,设置略有不同。本节分别描述了两种方式。

2.1 网络应用

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

提供一个Auth-Url的链接。用户必须使用他的Google帐户登录,接受您的应用程序将访问Analytics数据。完成这些步骤后,用户将被重定向回重定向URI,并带有代码。此代码用于获取令牌。

$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...
}

使用accessToken,您可以在 $tokenExpires 给定的时间内查询API。如果您需要在此时间之外查询API,您应该将refreshToken连同时间戳一起存储在数据库/会话中。如果accessToken过期,您可以使用refreshToken获取新的accessToken。

// 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 服务帐户

从API控制台复制电子邮件地址(xxxxxxxx@developer.gserviceaccount.com)。访问您的GA管理员并将此电子邮件地址添加为用户到您的属性。

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

要查询API,您需要获取访问令牌。此令牌有效期为 一小时,之后您将需要获取新的令牌。您可以在数据库/会话中存储令牌。

$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. 查找帐户ID

在您查询API之前,您需要查询数据的帐户ID。ID可以按如下方式找到

// 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. 查询Google Analytics API

一旦您有了有效的accessToken和帐户ID,您就可以查询Google Analytics API。您可以为每次查询设置一些默认查询参数。

// 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();

旧GAPI包装器

gapi_wrapper/ 中包含了一个尘封的GAPI包装器

资源