[英]Testing for Google Analytics JavaScript calls on a page using CasperJS?
[英]Access Google analytics without consent page using JavaScript
我正在使用Atlasboard創建儀表板。
我需要訪問Google分析數據,例如網頁瀏覽量等,我會在此處顯示一些查詢。
有沒有辦法在沒有此同意頁面的情況下訪問我的Google分析數據?
我正在使用google-api-nodejs-client api。
我找到了這個帖子 ,有人提到使用服務帳戶。 但我無論如何都無法找到這個在JavaScript中工作。
任何幫助都會很棒!
我終於設法找到了解決這個問題的方法! 這是解決方案:)
這假設您已經擁有一個Google分析帳戶,該帳戶包含視圖等網站數據,並安裝了請求和googleapis模塊。
首先,您需要在console.developers.google.com上創建一個Google控制台帳戶。
在Google控制台:
現在轉到www.google.com/analytics上的Google分析帳戶:
在儀表板作業中(使用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分析數據。 我使用此Google Analytics查詢工具來幫助我: http : //ga-dev-tools.appspot.com/explorer/
然后應該在控制台中輸出數據。
希望這可以幫助 :)
除了smj2393的答案,以及想要創建特定URL以檢索由Google AnalyticsAPI提供的JSON的用戶,以下是Node Express路由的示例。 您需要安裝官方Google API Node npm軟件包( https://www.npmjs.org/package/googleapis )。
var google = require('googleapis');
var analytics = google.analytics('v3');
var ENV = process.env;
//get key.p12 in Google Developer console
//Extract it with : openssl pkcs12 -in key.p12 -nodes -nocerts > key.pem
//Get GOOGLE_API_EMAIL in Google Developer console (Service Account)
//Get GOOGLE_ANALYTICS_VIEW_ID in Google Analytics Console : Admin -> View -> View Parameters -> View ID
//Add GOOGLE_API_EMAIL in the Google Analytics account users
var authClient = new google.auth.JWT(
ENV.GOOGLE_API_EMAIL,
'./keys/googlekey.pem', //path to .pem
null,
// Scopes can be specified either as an array or as a single, space-delimited string
['https://www.googleapis.com/auth/analytics.readonly']);
module.exports = function(req, res, next) {
var startDate = (req.query.start_date) ? req.query.start_date : '7daysAgo';
var endDate = (req.query.end_date) ? req.query.end_date : 'yesterday';
authClient.authorize(function(err, tokens) {
if (err) {
console.log(err);
return;
}
// Make an authorized request to list analytics files.
// list of dimensions and metrics : https://developers.google.com/analytics/devguides/reporting/core/dimsmets
analytics.data.ga.get({
auth: authClient,
"ids":'ga:'+ENV.GOOGLE_ANALYTICS_VIEW_ID,
"start-date":startDate,
"end-date":endDate,
"metrics":"ga:sessions,ga:pageviews",
"dimensions":"ga:deviceCategory"
}, function(err, result) {
console.log(err);
console.log(result);
if(!err){
res.json(result);
}
else{
next();
}
});
});
}
此路由將顯示一個JSON,表示按設備(桌面,移動設備和平板電腦)的會話數和pageView數。 您可以使用GET參數傳遞start_date或end_date。
希望這有幫助。
查看Atlasboard Atlassian軟件包中的google-analytics
作業。 它使用Google API Node.js客戶端 npm包:
您可以使用它與實時或經典Google AnalyticsAPI進行對話。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.