>

응답 데이터를 얻으려면 Google 웹 로그 분석에서 승인해야합니다.

var google = require('googleapis'), 
  q = require('q'), 
  SERVICE_ACCOUNT_EMAIL = '[email protected]account.com', 
  SERVICE_ACCOUNT_KEY_FILE = __dirname + '/google-services-private-key.pem';
  var def = q.defer(); 
  var gAnalytics = google.analytics('v3'); 
  var authClient = new google.auth.JWT( SERVICE_ACCOUNT_EMAIL, SERVICE_ACCOUNT_KEY_FILE, null, ['https://www.googleapis.com/auth/analytics.readonly']); 
  console.log(authClient) 
  authClient.authorize(function (err, tokens) { 
    if (err) { 
      console.log("err is: " + err, tokens); 
      return; 
    }

하지만 승인하지 못합니다

오류가 발생했습니다

JWT { transporter: DefaultTransporter {}, clientId_: undefined, clientSecret_: undefined, redirectUri_: undefined, opts: {},
credentials: { refresh_token: 'jwt-placeholder', expiry_date: 1 },
email: '[email protected]account.com', keyFile: '/home/aaa/Desktop/ampretailer/server/google-services-private-key.pem', key: null, scopes: [ 'https://www.googleapis.com/auth/analytics.readonly' ], subject: undefined, gToken: [Function: GoogleToken] } err is: Error: invalid_grant: Invalid JWT Signature. { access_token: null, token_type: 'Bearer', expiry_date:null }

  • 답변 # 1

    v3 대신 Google 애널리틱스 v4를 사용하는 것이 좋습니다. V3 사용에는 액세스 할 수없는 여러 측정 기준과 측정 항목이 있습니다.

    'use strict';
    const { google } = require('googleapis');
    const sampleClient = require('../sampleclient');
    const analyticsreporting = google.analyticsreporting({
      version: 'v4',
      auth: sampleClient.oAuth2Client
    });
    async function runSample () {
      const res = await analyticsreporting.reports.batchGet({
        resource: {
          reportRequests: [{
            viewId: '65704806',
            dateRanges: [
              {
                startDate: '2018-03-17',
                endDate: '2018-03-24'
              }, {
                startDate: '14daysAgo',
                endDate: '7daysAgo'
              }
            ],
            metrics: [
              {
                expression: 'ga:users'
              }
            ]
          }]
        }
      });
      console.log(res.data);
      return res.data;
    }
    // if invoked directly (not tests), authenticate and run the samples
    if (module === require.main) {
      const scopes = ['https://www.googleapis.com/auth/analytics'];
      sampleClient.authenticate(scopes)
        .then(c => runSample())
        .catch(e => console.error);
    }
    // export functions for testing purposes
    module.exports = {
      runSample,
      client: sampleClient.oAuth2Client
    };
    
    

    analyticsReporting/batchGet.js에서 추출 된 코드

    와이즈 비즈

    Service account - To use the service account based samples, create a new service account in the cloud developer console, and save the file as jwt.keys.json in the samples directory.

    samples/jwt.js에서 추출 된 코드

    'use strict'; const {google} = require('googleapis'); const path = require('path'); /** * The JWT authorization is ideal for performing server-to-server * communication without asking for user consent. * * Suggested reading for Admin SDK users using service accounts: * https://developers.google.com/admin-sdk/directory/v1/guides/delegation * * See the defaultauth.js sample for an alternate way of fetching compute credentials. */ async function runSample () { // Create a new JWT client using the key file downloaded from the Google Developer Console const client = await google.auth.getClient({ keyFile: path.join(__dirname, 'jwt.keys.json'), scopes: 'https://www.googleapis.com/auth/analytics.readonly' }); // Obtain a new drive client, making sure you pass along the auth client const analyticsreporting = google.analyticsreporting({ version: 'v4', auth: client }); // Make an authorized request to list Drive files. const res = = await analyticsreporting.reports.batchGet({ resource: { reportRequests: [{ viewId: '65704806', dateRanges: [ { startDate: '2018-03-17', endDate: '2018-03-24' }, { startDate: '14daysAgo', endDate: '7daysAgo' } ], metrics: [ { expression: 'ga:users' } ] }] } }); console.log(res.data); return res.data; } if (module === require.main) { runSample().catch(console.error); } // Exports for unit testing purposes module.exports = { runSample };

관련 자료

  • 이전 오이 자바 - json 플러그인 생성을 강제하는 방법
  • 다음 excel - VLOOKUP은 N/A를 반환하지만 수식을 평가 한 후 올바른 결과를 표시합니다