2014-04-10 19 views
8

Tôi đang tạo trang tổng quan bằng cách sử dụng Atlasboard.Truy cập Google analytics mà không có trang chấp thuận bằng cách sử dụng JavaScript

Tôi cần truy cập dữ liệu Google Analytics, chẳng hạn như lượt xem trang, nơi tôi sẽ chạy một số truy vấn được hiển thị here.

Có cách nào để truy cập dữ liệu Google Analytics của tôi mà không có trang chấp thuận này xuất hiện không? enter image description here

Tôi đang sử dụng google-api-nodejs-client api.

Tôi tìm thấy this post nơi ai đó đề cập đến việc sử dụng tài khoản dịch vụ. Nhưng tôi không thể tìm thấy anyway để có được điều này làm việc trong JavaScript.

Mọi trợ giúp sẽ tuyệt vời!

+1

Theo hiểu biết của tôi, bạn không thể sử dụng tài khoản dịch vụ có JavaScript. Điều này rất có thể là do vấn đề bảo mật. Tôi đề nghị chuyển sang ngôn ngữ kịch bản lệnh phía máy chủ – DaImTo

+0

Ok, chúc mừng! Tôi sẽ tiến hành nghiên cứu thêm một chút và đăng các phát hiện của tôi ở đây! – smj2393

Trả lời

10

Tôi cuối cùng cũng đã tìm được giải pháp cho vấn đề này !!! Đây là giải pháp :)

Giả sử bạn đã có tài khoản Google Analytics có dữ liệu trang web chẳng hạn như lượt xem và đã cài đặt mô-đun requestgoogleapis.

Trước tiên, bạn cần tạo tài khoản Google console tại console.developers.google.com.

Tại Google console:

  • Tạo một dự án với một tên phù hợp ví dụ dashboard1.
  • Mở API & Xác thực từ menu bên trái -> mở tab API -> bật API phân tích.
  • Mở tab thông tin xác thực -> tạo id ứng dụng khách mới -> chọn tài khoản dịch vụ
  • Khóa phải tự động tải xuống -> nhấp vào khóa và làm theo hướng dẫn -> mật khẩu mặc định là "không cần lưu ý" -> sau đó xuất ra tệp .pem
  • Tài khoản dịch vụ sẽ có địa chỉ email, ví dụ: [email protected]

Bây giờ đi đến phân tích tài khoản Google tại www.google.com/analytics:

Trong công việc bảng điều khiển (phía máy chủ sử dụng nodejs):

Sử dụng mã này:

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); 
      }); 
     } 
    }); 

NHỚ ĐẾN ĐẦU VÀO BẠN ĐANG RIÊNG EMAIL DỊCH VỤ TÀI KHOẢN, GA_KEY_PATH VÀ IDS

Bạn có thể phân tích dữ liệu Google bằng cách thay đổi reque stConfig. Tôi đã sử dụng công cụ truy vấn Google Analytics này để trợ giúp tôi: http://ga-dev-tools.appspot.com/explorer/

Dữ liệu sau đó sẽ được xuất trong bảng điều khiển.

Hope this helps :)

4

Ngoài các câu trả lời của smj2393, và cho những ai muốn tạo ra một URL cụ thể để lấy JSON được cung cấp bởi các API của Google Analytics, đây là một mẫu của một Node nhanh tuyến đường. Bạn cần cài đặt gói npm chính thức của API Google API (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(); 
     } 
    }); 
    }); 
} 

Tuyến đường này sẽ hiển thị JSON đại diện cho số phiên và số lần xem trang theo thiết bị (máy tính để bàn, thiết bị di động và máy tính bảng). Bạn có thể vượt qua start_date hoặc end_date với tham số GET.

Hy vọng trợ giúp này.

Các vấn đề liên quan