我正在使用Google API(按照Hello Analytics教程进行操作)以及授权问题。该过程正在验证我,但当我尝试从GA调用数据时,我收到一条错误消息,我必须登录才能进行此访问。 “授权”按钮消失了,因此我无法进行身份验证,并且“#34;获取会话”#34;按钮出现但导致错误。我的示例看起来与教程示例完全一样,直到处理结果为止,所以我真的不确定为什么会发生这种情况。任何帮助,将不胜感激。这是我的代码(客户端ID,api密钥和GA属性已被替换,原因很明显)。
var clientId = 'clientid';
var apiKey = 'apikey';
var scopes = 'https://www.googleapis.com/auth/analytics.readonly';
function makeApiCall() {
var apiQuery = gapi.client.analytics.data.ga.get({
'ids': 'id',
'start-date': '2014-06-01',
'end-date': '2014-07-01',
'metrics': 'ga:pageviews',
'dimensions': 'ga:pagePath',
'filters': 'ga:pagepath=~marketplace/seller/(*.?)/example'
});
console.dir(apiQuery);
apiQuery.execute(handleCoreReportingResults);
}
// This function is called after the Client Library has finished loading
function handleClientLoad() {
gapi.client.setApiKey(apiKey);
window.setTimeout(checkAuth,1);
}
function checkAuth() {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthResult);
}
function handleAuthResult(authResult) {
if (authResult) {
loadAnalyticsClient();
} else {
handleUnAuthorized();
}
}
// Authorized user
function handleAuthorized() {
var authorizeButton = document.getElementById('authorize-button');
var makeApiCallButton = document.getElementById('make-api-call-button');
makeApiCallButton.style.visibility = '';
authorizeButton.style.visibility = 'hidden';
makeApiCallButton.onclick = makeApiCall;
}
// Unauthorized user
function handleUnAuthorized() {
var authorizeButton = document.getElementById('authorize-button');
var makeApiCallButton = document.getElementById('make-api-call-button');
makeApiCallButton.style.visibility = 'hidden';
authorizeButton.style.visibility = '';
authorizeButton.onclick = handleAuthClick;
}
function handleAuthClick(event) {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthResult);
return false;
}
function loadAnalyticsClient() {
gapi.client.load('analytics', 'v3', handleAuthorized);
}
function handleCoreReportingResults(results) {
if (results.error) {
console.log('There was an error querying core reporting API: ' + results.message);
} else {
console.dir(results);
}
}
答案 0 :(得分:0)
我运行了你的代码,它对我来说很好。
这让我认为Google developer console中的项目设置存在问题。如果原因不匹配或类似情况,您将无法运行查询。你在本地服务器上运行吗?如果是这样,您必须确保在创建客户端ID时将localhost
(使用您正在使用的端口)添加为已批准的JavaScript源。
如果你真的发布了你所得到的错误,那将会非常有帮助,除此之外,我不确定我能帮到你。就像我说的,你的代码对我来说很好。
答案 1 :(得分:-1)
我目前无法运行此代码来帮助您调试它,但我最初的建议是不自己进行身份验证,而是使用新发布的{{3 }}
Embed API的主要卖点是它可以为您处理所有这些auth内容,因此您可以非常快速地启动并运行应用程序来查询API。
如果您想使用它,我建议您查看Google Analytics Embed API。之后,请查看getting started guide以查看一些示例。您可以查看任何演示的源代码,以查看它们是如何制作的,或者代码是在Github上。