javascript - 使用 JavaScript 在未经同意的情况下访问 Google 分析页面

标签 javascript node.js google-analytics dashboard atlasboard

我正在使用 Atlasboard 创建仪表板.

我需要访问 Google 分析数据,例如页面浏览量等。我将在其中运行一些显示的查询 here .

有没有办法在不显示此同意页面的情况下访问我的 Google 分析数据? enter image description here

我正在使用 google-api-nodejs-client应用程序接口(interface)。

我找到了 this post有人提到使用服务帐户的地方。但无论如何我都找不到让这个在 JavaScript 中工作的方法。

任何帮助都会很棒!

最佳答案

我终于找到了解决这个问题的办法!!!这是解决方案:)

这是假设您已经拥有一个 Google 分析帐户,该帐户具有 View 等站点数据并且具有 requestgoogleapis安装的模块。

首先您需要在 console.developers.google.com 创建一个 Google 控制台帐户.

在 Google 控制台:

  • 创建一个具有合适名称的项目,例如仪表板1。
  • 从左侧菜单打开 API 和 Auth -> 打开 API 选项卡 -> 打开分析 API。
  • 打开凭据选项卡 -> 创建新的客户端 ID -> 选择服务帐户
  • key 应自动下载 -> 单击 key 并按照说明进行操作 -> 默认密码为“notasecret” -> 然后将输出一个 .pem 文件
  • 服务帐户将有一个电子邮件地址,例如123434234324f34f5fd4ww5f@developer.gserviceaccount.com

现在转到您的 Google 分析帐户 www.google.com/analytics :

在仪表板作业中(服务器端使用 nodejs):

使用这段代码:

    var fs = require('fs'),
        crypto = require('crypto'),
        request = require('request'); // This is an external module (https://github.com/mikeal/request)

    var authHeader = {
            'alg': 'RS256',
            'typ': 'JWT'
        },
        authClaimSet = {
            'iss': '#######SERVICE ACCOUNT EMAIL GOES HERE#######', // Service account email
            'scope': 'https://www.googleapis.com/auth/analytics.readonly', // We MUST tell them we just want to read data
            'aud': 'https://accounts.google.com/o/oauth2/token'
        },
        SIGNATURE_ALGORITHM = 'RSA-SHA256',
        SIGNATURE_ENCODE_METHOD = 'base64',
        GA_KEY_PATH = '#######DIRECTORY TO YOUR .PEM KEY#######', //finds current directory then appends private key to the directory
        gaKey;

    function urlEscape(source) {
        return source.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=+$/, '');
    }

    function base64Encode(obj) {
        var encoded = new Buffer(JSON.stringify(obj), 'utf8').toString('base64');
        return urlEscape(encoded);
    }

    function readPrivateKey() {
        if (!gaKey) {
            gaKey = fs.readFileSync(GA_KEY_PATH, 'utf8');
        }
        return gaKey;
    }

    var authorize = function(callback) {

        var self = this,
            now = parseInt(Date.now() / 1000, 10), // Google wants us to use seconds
            cipher,
            signatureInput,
            signatureKey = readPrivateKey(),
            signature,
            jwt;

        // Setup time values
        authClaimSet.iat = now;
        authClaimSet.exp = now + 60; // Token valid for one minute

        // Setup JWT source
        signatureInput = base64Encode(authHeader) + '.' + base64Encode(authClaimSet);

        // Generate JWT
        cipher = crypto.createSign('RSA-SHA256');
        cipher.update(signatureInput);
        signature = cipher.sign(signatureKey, 'base64');
        jwt = signatureInput + '.' + urlEscape(signature);

        // Send request to authorize this application
        request({
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            uri: 'https://accounts.google.com/o/oauth2/token',
            body: 'grant_type=' + escape('urn:ietf:params:oauth:grant-type:jwt-bearer') +
                '&assertion=' + jwt
        }, function(error, response, body) {
            if (error) {
                console.log(error);
                callback(new Error(error));
            } else {
                var gaResult = JSON.parse(body);
                if (gaResult.error) {
                    callback(new Error(gaResult.error));
                } else {
                    callback(null, gaResult.access_token);
                    console.log(gaResult);
                    console.log("Authorized");
                    ###########IF IT REACHES THIS STAGE THE ACCOUNT HAS BEEN AUTHORIZED##############
                }
            }
        });

    };



    var request = require('request'),
        qs = require('querystring');

    authorize(function(err, token) {
        if (!err) {
            // Query the number of total visits for a month
            ############requestConfig################
            var requestConfig = {
                'ids': 'ga:#######PROJECT ID GOES HERE#######',
                'dimensions': 'ga:country',
                'metrics': 'ga:users',
                'sort': '-ga:users',
                'start-date': '2014-04-08',
                'end-date': '2014-04-22',
                'max-results': '10'
            };

            request({
                method: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + token // Here is where we use the auth token
                },
                uri: 'https://www.googleapis.com/analytics/v3/data/ga?' + qs.stringify(requestConfig)
            }, function(error, resp, body) {
                console.log(body);
                var data = JSON.parse(body);
                console.log(data);
            });
        }
    });

记得输入您自己的服务电子邮件帐户、GA_KEY_PATH 和 IDS

您可以通过更改 requestConfig 来谷歌分析数据。我使用这个 Google Analytics 查询工具来帮助我:http://ga-dev-tools.appspot.com/explorer/

然后应该在控制台中输出数据。

希望这有帮助:)

关于javascript - 使用 JavaScript 在未经同意的情况下访问 Google 分析页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22990276/

相关文章:

javascript - 如何在 Javascript 中创建真正的模态警报/确认?

javascript - nodejs串口setCommState

javascript - 左 50% 和 margin-left negative 不起作用

php - 选择框不保留值

json - 多个异步 mongo 请求生成困惑的返回

javascript - 为什么 Babel 7 不编译 node_modules 文件?

google-analytics - 有没有办法将 Google Analytics(分析)媒体资源转移到新帐户?

html - 为什么我的 html 内容在不重启 javascript 服务器的情况下无法更新?

php - Google Analytics 未跟踪出站点击

javascript - iframe 内的 Google Analytics