Google Analytics Reporting API v4缺少必需的身份验证凭据

时间:2017-03-28 23:13:49

标签: google-analytics google-api google-oauth google-analytics-api

我是使用此API的新手,我正在努力使用Google Analytics Reporting API v4检索我的数据。我只是试图检索网站的分析,以便我可以构建一个仪表板。我在这里关注这个例子:Hello Analytics Reporting API v4; JavaScript quick start for web applications

我可以提出请求,但是,我不断收到400 error可能是这样的:400: Invalid Credentials

`Invalid JSON payload received. Unknown name "express" at 'report_requests[0].metrics[0]': Cannot find field.
handleError @ Test.js:64
h.o0 @ cb=gapi.loaded_0:53
xs @ cb=gapi.loaded_0:56
Wq @ cb=gapi.loaded_0:56
_.C.uea @ cb=gapi.loaded_0:55
Ap @ cb=gapi.loaded_0:49`

我不知道我做错了什么,我希望有人能指出我正确的方向。

这是一个反应应用程序。我在组件安装后发出请求。

import React, { Component } from 'react';
import GoogleLogin from 'react-google-login';
import $ from 'jquery';

const VIEW_ID = '17414592';
const CLIENT_ID = "936270024581-stgn130l17v21s6vjch9p751hiqbovac.apps.googleusercontent.com";
const DISC_DOCS = 'https://analyticsreporting.googleapis.com/$discovery/rest?version=v4';

export default class Test extends Component {
  constructor(props) {
    super(props)

    this.printResults = this.printResults.bind(this);
    this.handleRequest = this.handleRequest.bind(this);
    this.handleError = this.handleError.bind(this);
  }

  //when component mounts, create a google sign in button.
  componentDidMount() {
    //load gapi
    $.getScript("https://apis.google.com/js/client:platform.js")
    .done(() => {
      window.gapi.signin2.render('my-signin2', {
        'scope': 'profile email',
        'width': 240,
        'height': 50,
        'longtitle': true,
        'theme': 'dark',
        'onsuccess': this.handleRequest,
        'onfailure': this.handleError
      });
    })
  }

  //on success, make a request to get google analytics data
  handleRequest() {
    window.gapi.client.request({
      path: '/v4/reports:batchGet',
      root: 'https://analyticsreporting.googleapis.com',
      method: 'POST',
      body: {
        reportRequests: [
          {
            viewId: VIEW_ID,
            dateRanges: [{
              startDate: '7daysAgo',
              endDate: 'today'
            }],
            metrics: [{ express: 'ga:sessions' }]
          }
        ]
      }
    }).then(this.printResults, this.handleError)
  }

  //log the data
  printResults(response) {
    console.log(response)
  }

  //or the error if there is one
  handleError(reason) {
    console.error(reason)
    console.error(reason.result.error.message);
  }

  //render it all
  render() {
    return (
      <div>
      <div id="my-signin2"></div>
      </div>
    )
  }
}

我做错了什么?如何使用Google Analytics Reporting APIv4正确执行batchRequest以检索7天内的所有数据?我觉得好像我正在使用所有必需的字段,但是,我不知道我错过了什么。你能指出我正确的方向吗?

2 个答案:

答案 0 :(得分:2)

我回答了我自己的问题,以防其他人需要帮助,使用谷歌分析报告api v4 with react。这是我需要做的,以构建一个gapi按钮,然后发出一个基本的请求。我创造的错误来自一个错字。而不是metrics:[{expression: 'ga:sessions'}]我正在使用metrics:[{express: 'ga:sessions'}]

这是一个创建简单请求的组件。请注意,您必须将VIEW_ID更改为您的值。

import React, { Component } from 'react';
import $ from 'jquery';

const VIEW_ID = '17414592';

export default class Test extends Component {
  constructor(props) {
    super(props)

    this.printResults = this.printResults.bind(this);
    this.handleRequest = this.handleRequest.bind(this);
    this.handleError = this.handleError.bind(this);
  }

  //when component mounts, create a google sign in button.
  componentDidMount() {
    //load gapi
    $.getScript("https://apis.google.com/js/client:platform.js")
    .done(() => {
      window.gapi.signin2.render('my-signin2', {
        'scope': 'profile email',
        'width': 240,
        'height': 50,
        'longtitle': true,
        'theme': 'dark',
        'onsuccess': this.handleRequest,
        'onfailure': this.handleError
      });
    })
  }

  //on success, make a request to get google analytics data
  handleRequest() {
    window.gapi.client.request({
      path: '/v4/reports:batchGet',
      root: 'https://analyticsreporting.googleapis.com',
      method: 'POST',
      body: {
        reportRequests: [
          {
            viewId: VIEW_ID,
            dateRanges: [{
              startDate: '7daysAgo',
              endDate: 'today'
            }],
            metrics: [{ expression: 'ga:sessions' }]
          }
        ]
      }
    }).then(this.printResults, this.handleError)
  }

  //log the data
  printResults(response) {
    console.log(response)
  }

  //or the error if there is one
  handleError(reason) {
    console.error(reason)
    console.error(reason.result.error.message);
  }

  //render it all
  render() {
    return (
      <div>
      <div id="my-signin2"></div>
      </div>
    )
  }
}

答案 1 :(得分:1)

  

401:凭据无效授权标头无效。 访问权限   您正在使用的令牌已过期或无效。

这基本上意味着您需要再次登录。

  

点击登录按钮,然后授权访问Google Analytics。

请记住,访问令牌仅在一小时内有效,您必须在到期时再次签名。