适用于Google AnalyticsAPI的jQuery AJAX标头身份验证

时间:2012-07-19 15:50:47

标签: javascript jquery google-analytics basic-authentication google-analytics-api

我正在构建一个从GA中提取数据的仪表板。为此,我需要通过Google帐户获取访问令牌,然后我需要使用包含此经过身份验证的令牌的标头来查询GA。

继承我的代码:

$.ajax({
    async: false,
    url: "https://www.google.com/accounts/ClientLogin?accountType=GOOGLE&Email=EMAIL&Passwd=PASSWORD&service=analytics",
    success : function(data) {
        var auth = data.substring(data.indexOf("Auth=") + 5);
        console.log(auth);
        $.ajax({
            type: 'get',
            headers: {
                "Content-type": "application/x-www-form-urlencoded",
                "Authorization": "GoogleLogin Auth=" + auth,
                "GData-Version": "2",
            },
            url: "https://www.google.com/analytics/feeds/data?ids=ga:PROFILE&start-date=2011-08-16&end-date=2012-06-16&max-results=10000",
       });
    }
});

不幸的是这种方法不起作用。如果有人能给我指示如何使这种工作或更好的方式来验证这些请求,那将非常感激。

1 个答案:

答案 0 :(得分:0)

它不起作用,因为ClientLogin要求post请求而不是get。它也是deprecated

您似乎也违反了same-origin policy的ajax请求。

使用OAuth 2 version with a refresh token。您可以使用您网站上的client libraries之一,并将ajax请求发布到您自己的网页。