我遇到了一个奇怪的问题,我试图解决这个问题,但我已经尝试了一整天,但还是没有用,所以我希望也许其他人可以帮助我解决这个问题。
我构建了一个 CMS,登录后您会看到仪表板。 在此仪表板上,您可以点击一个按钮将您的帐户与 Google 连接 - 因为我希望我的客户能够连接他们的 Google Analytics 帐户。
一切正常,我有 token 和刷新 token ,一切似乎都正常。即使当我请求我的用户配置文件数据时,我也会将它作为一个数组打印在我的屏幕上。但是,当我尝试获取可供连接用户查看的帐户时,出现此错误:
Uncaught exception 'Google_Service_Exception' with message 'Error calling GET
https://www.googleapis.com/analytics/v3/management/accounts/~all/webproperties
key=xxxxxxxxxxxxxxxxxxxxxxxxxx: (401) Login Required'
我只是不明白为什么我会收到“需要登录”的消息。 你可以在下面看到我的脚本。
require_once('/Google/Client.php');
require_once('/Google/Service/Analytics.php');
// call object
$client = new Google_Client();
$client->setApplicationName("Google Analytics - CMS title");
$client->setClientId('xxxxxxxxxxxxxxxxx');
$client->setClientSecret('xxxxxxxxxxxxxxxx');
$client->setRedirectUri('xxxxxxxxxxxxxxxxxxx');
$client->setDeveloperKey('xxxxxxxxxxxxxxxxxxx');
$client->setApprovalPrompt('auto');
$client->setAccessType('offline');
$client->setScopes(array(
'https://www.googleapis.com/auth/userinfo.profile',
'https://www.googleapis.com/auth/analytics'
));
// decode
$token = $token; // this comes from my database and it's json encoded
// connect
$client->setAccessToken($token);
// call service
$service = new Google_Service_Analytics($client);
// get accounts from analytics
$accounts = $service->management_accounts->listManagementAccounts();
当我尝试 var_dump $accounts 时,我没有看到任何东西,因为错误已经发生(需要登录)
我想你现在会问我我的 token 是否正确,但这是因为我用其他 api 调用测试了它..它只是不适用于这个特定的分析请求。
我希望有人能帮我解决这个问题。
谢谢, Pim vd Molen
更新: 刚刚发生了一些非常奇怪的事情。我不知道这是怎么可能的,但错误只是变成了另一个错误:
Uncaught exception 'Google_Service_Exception' with message 'Error calling GET
https://www.googleapis.com/analytics/v3/management
/accounts?key=xxxxxxxxxxxxxxxxxx: (403) Access Not Configured.
Please use Google Developers Console to activate the API for your project.
当然,我已经启用了 Google Analytics 服务,但不知道还需要启用哪一个。
最佳答案
401 错误 clearly指出凭据是错误的。 token 可能对检索数据有效,但对于检索用户管理信息,您在请求该 token 时需要特定的授权,请查看 here在表中,您会看到要在 OAuth 请求中设置的 scope
参数的附加值。
关于php - Google Analytics API 登录需要错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21319095/