问题是您尚未授权访问您的数据。既然你说这只是你想要访问的你自己的数据,我建议你研究一下服务帐户 https://developers.google.com/accounts/docs/OAuth2ServiceAccount。通过在中设置服务帐户谷歌 API 控制台 https://cloud.google.com/console/project?redirected=true它将允许您访问自己的数据,而无需始终登录和验证代码。
检查以下链接。阅读之前你开始确保你做到了这一切。
https://developers.google.com/analytics/devguides/config/mgmt/v3/mgmtExperimentsGuide#service https://developers.google.com/analytics/devguides/config/mgmt/v3/mgmtExperimentsGuide#service
- 在 Google Developers Console 中注册您的应用程序
- 授权访问 Google Analytics 数据。
- 创建 Analytics 服务对象
您已跳过前两个步骤,直接进入步骤 3 创建服务对象。完成步骤 1 后,您可以在步骤 2 中使用以下代码。
这是如何在 php 中使用服务帐户的示例服务帐户 http://code.google.com/p/google-api-php-client/source/browse/trunk/examples/prediction/serviceAccount.php
该示例项目适用于 PredictionService,而不是谷歌分析服务。您需要稍微编辑一下。
require_once '../../src/Google/Client.php';
require_once '../../src/Google/Service/Analytics.php';
// Set your client id, service account name, and the path to your private key.
// For more information about obtaining these keys, visit:
// https://developers.google.com/console/help/#service_accounts
const CLIENT_ID = 'INSERT_YOUR_CLIENT_ID';
const SERVICE_ACCOUNT_NAME = 'INSERT_YOUR_SERVICE_ACCOUNT_NAME';
// Make sure you keep your key.p12 file in a secure location, and isn't
// readable by others.
const KEY_FILE = '/super/secret/path/to/key.p12';
$client = new Google_Client();
$client->setApplicationName("Google Analytics Sample");
// Load the key in PKCS 12 format (you need to download this from the
// Google API Console when the service account was created.
$client->setAssertionCredentials(new Google_AssertionCredentials(
SERVICE_ACCOUNT_NAME(Email),
array('https://www.googleapis.com/auth/analytics.readonly'),
file_get_contents(KEY_FILE))
);
$client->setClientId(CLIENT_ID);
$service = new Google_Service_Analytics($client);
现在你有$service
您可以将其用于其余的通话。注意:我没有时间测试该代码,如果它不起作用,请告诉我,我会帮助您修复它。