PHP通过Google API使用Service Account获取analytics数据

想使用google api来获取analytics数据,但是自带的demo中的Service Account无法运行,只能自己根据?Google OAuth 2.0 for Server to Server 协议来解决。 分为4步 1. 创建证书Developers Console创建project。再为project创建Service Account。 QQ20140312-1QQ20140312-2 点击”Create Client ID“后,会下载一个p12文件,保存到服务器。 2. 给Client ID授权 在你的analycits的管理界面中,选择你要授权的视图,点击用户管理 QQ20140312-3 为你申请的Client ID中的email授权QQ20140312-4
3. 编写代码 将以下代码中的iss换成你刚刚创建的Client ID中的email,将代码中的“privatekey.p12”替换成你的p12文件地址,执行代码,将获取token

$encode1 = urlencode(base64_encode('{"alg":"RS256","typ":"JWT"}'));
$encode2 = urlencode(base64_encode(json_encode(array(
	 "iss"=>"xxxxxxxxxxxx@developer.gserviceaccount.com",
	 "scope"=>"https://www.googleapis.com/auth/analytics.readonly",
	 "aud"=>"https://accounts.google.com/o/oauth2/token",
	 "exp"=>strtotime('+1hour'),
	 "iat"=>time(),
))));

$text = "$encode1.$encode2";
openssl_pkcs12_read(file_get_contents('privatekey.p12'), $certs, 'notasecret');
$privateKey = openssl_pkey_get_private($certs["pkey"]);

openssl_sign($text, $sign, $privateKey, 'sha256');
$sign = urlencode(base64_encode($sign));
$url_encode = "$encode1.$encode2.$sign";

$url = 'https://accounts.google.com/o/oauth2/token';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//设置是否返回信息
curl_setopt($ch, CURLOPT_USERAGENT, 'Google Analytics Sample Application google-api-php-client/0.6.5');
curl_setopt($ch, CURLOPT_POST, 1);//设置为POST方式
curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=$url_encode");//POST数据
$respData = curl_exec($ch);
echo $respData;

4. 获取数据 将以下代码中的$access_token替换成刚刚获取的token,将8888888替换成你自己的视图id

$access_token = '0.2xxxxxxxxxxxxxxx';
$params = array(
 'ids' => 'ga:88888888',
 'dimensions' => 'ga:eventAction,ga:eventLabel',
 'metrics' => 'ga:totalEvents',
 'sort' => '-ga:totalEvents',
 'start-date' => "7daysAgo",
 'end-date' => 'today',
 'max-results' => 25,
);
$url = 'https://www.googleapis.com/analytics/v3/data/ga?' . http_build_query($params);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//设置是否返回信息
curl_setopt($ch, CURLOPT_USERAGENT, 'Google Analytics Sample Application google-api-php-client/0.6.5');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('authorization: Bearer ' . $access_token));
$respData = curl_exec($ch);

备注:PHP版本必须大于等于5.3.0

One Reply to “PHP通过Google API使用Service Account获取analytics数据”

发表评论

电子邮件地址不会被公开。

*