首页 文章

Google Analytics(分析) - invalid_grant:无效的JWT签名

提问于
浏览
1

我需要通过Google分析授权才能获取响应数据 .

var google = require('googleapis'), 
  q = require('q'), 
  SERVICE_ACCOUNT_EMAIL = '838823084353-cjjoiv9di67fuh7geqgggociibataf9v@developer.gserviceaccount.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:'838823084353-cjjoiv9di67fuh7geqgggociibataf9v @ developer .gserviceaccount.com',keyFile:'/ home / aaa / Desktop / ampretailer / server / google-services -private-key.pem',key:null,scopes:['https://www.googleapis.com/auth /analytics.readonly'],主题:未定义,gToken:[功能:GoogleToken]}错误是:错误:invalid_grant:无效的JWT签名 . {access_token:null,token_type:'Bearer',expiry_date:null}

1 回答

  • 1

    我建议您尝试使用Google Analytics v4而不是v3,您可以使用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撕掉

    服务帐户 - 要使用基于服务帐户的示例,请在 Cloud 开发人员控制台中创建新的服务帐户,并将文件另存为样本目录中的jwt.keys.json .

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

    代码从samples/jwt.js撕掉

相关问题