Google Analytics API V3现在支持由.p12签名的JWT请求返回的OAuth2令牌。也就是说, 。
目前仅提取4年的每日数据, 仅此而已。
转到Google API控制台并创建一个新应用
在“ 服务” 标签中,翻转 Google Analytics(分析) 开关
在“ API访问” 选项卡中,单击“ 创建OAuth2.0客户端ID”
输入您的姓名,上传徽标,然后单击 下一步
选择 服务帐户 选项,然后按 创建客户ID
下载您的私钥
现在,您回到“ API访问” 页面。您会看到名为“ 服务帐户” 的部分,其中包含 客户ID 和 电子邮件地址
复制电子邮件地址(类似 ####@developer.gserviceaccount.com )
访问您的GA管理员,
这是必须的;否则,您将得到隐秘的错误。
通过Github 获取最新的Google PHP客户端API
git submodule add https://github.com/google/google-api-PHP-client.git google-api-PHP-client-read-only
// api dependencies
require_once(PATH_TO_API . 'Google/Client.PHP');
require_once(PATH_TO_API . 'Google/Service/Analytics.PHP');
// create client object and set app name
$client = new Google_Client();
$client->setApplicationName(APP_NAME); // name of your app
// set assertion credentials
$client->setAssertionCredentials(
new Google_Auth_AssertionCredentials(
APP_EMAIL, // email you added to GA
array('https://www.googleapis.com/auth/analytics.readonly'),
file_get_contents(PATH_TO_PRIVATE_KEY_FILE) // keyfile you downloaded
));
// other settings
$client->setClientId(CLIENT_ID); // from API console
$client->setAccessType('offline_access'); // this may be unnecessary?
// create service and get data
$service = new Google_Service_Analytics($client);
$service->data_ga->get($ids, $startDate, $endDate, $metrics, $optParams);
下面的原始解决方法
看来,尽管文档含糊不清,但大多数Google API仍不支持服务帐户,包括Google Analytics(分析)。它们无法消化由.p12签名的JWT请求返回的OAuth2令牌。因此,截至目前,您 不能将Google Analytics(分析)API V3与服务帐户一起使用 。
在Google API控制台中,创建一个 应用程序。
请按照下列步骤谷歌PHP客户端API的例子来生成client_auth_url
使用client_id
,client_secret
和redirect_uri
使用cURL 登录到Google。(请务必使用Cookie文件!)
client_auth_url
在cURL中打开并填写表格。请确保您设置curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
并 curl_setopt($ch, CURLOPT_HEADER, 1);
为authorization_code
将在Location:
响应的头。
5.用你的client_id
,client_secret
,redirect_uri
从第4步,激活代码,发布到请求谷歌的的OAuth2令牌机。确保您包含grant_type= "authorization_code"
在您的帖子字段中。
6.您现在有一个refresh_token
永不过期的工作台access_token
!发布到请求谷歌的的OAuth2令牌机与你client_id
,client_secret
,redirect_uri
,和refresh_token
当你的access_token
到期,你会得到一个新的。