【问题标题】:Google's JS tutorial for Analytics Reporting API v4 fails due to outdated oauth library由于 oauth 库过时,Google 的 Analytics Reporting API v4 JS 教程失败
【发布时间】:2022-12-10 04:42:57
【问题描述】:

我已经为我的(通用)分析项目设置了 API 访问,它通过 Request Composer 从谷歌的“演示和工具”运行良好。所以我从这里选择了简单的教程 HTML 文件:

https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/web-js

但是一旦页面加载,控制台就会出现错误:您创建了一个新的客户端应用程序,该应用程序使用库进行用户身份验证或授权,但很快就会被弃用……等等。

但是图书馆似乎还没有被弃用(这似乎是在 2023 年 3 月)。

无论如何,我试图与时俱进并按照此处的指南使用新库:

https://developers.google.com/identity/gsi/web/guides/migration#popup-mode_1

这无处可去(403 错误和其他问题,因为它似乎不适合 API 访问)。不过,最终,我找到了一个指南,展示了如何使用 GIS 访问 API:

https://developers.google.com/identity/oauth2/web/guides/migration-to-gis

使用它,我设法拼凑出一个有效的查询。我会把它作为答案发布。这是为了帮助受过时教程影响的其他人。

【问题讨论】:

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


    【解决方案1】:

    按照本教程指示的方式启用 Analytics API:https://www.jcchouinard.com/google-api/

    您需要为内部 Web 应用程序创建凭据,并将“授权的 JavaScript 来源”设置为 http://localhost:8080

    将其另存为 .html 并在 localhost:8080 上提供。它应该要求您登录,您应该在登录提示中看到您的 Web 应用程序的名称。一旦你按下“查询报告”,你应该会得到一个很好的 JSON。

    <!DOCTYPE html>
    <html>
      <head>
      <script src="https://apis.google.com/js/client:platform.js"></script>
        <script src="https://accounts.google.com/gsi/client" onload="initClient()" async defer></script>
      </head>
      <body>
        <script>
          var client;
          var access_token;
    
          function initClient() {
            client = google.accounts.oauth2.initTokenClient({
              client_id: 'YOUR-CLIENT-ID',
              scope: 'https://www.googleapis.com/auth/analytics.readonly',
              callback: (tokenResponse) => {
                access_token = tokenResponse.access_token;
              },
            });
          }
          function getToken() {
            client.requestAccessToken();
          }
          function revokeToken() {
            google.accounts.oauth2.revoke(access_token, () => {console.log('access token revoked')});
          }
          function loadCalendar() {
            var xhr = new XMLHttpRequest();
            xhr.open('GET', 'https://www.googleapis.com/calendar/v3/calendars/primary/events');
            xhr.setRequestHeader('Authorization', 'Bearer ' + access_token);
            xhr.send();
          }
        </script>
        
    
    <script>
      // Replace with your view ID.
      var VIEW_ID = 'YOUR-VIEW-ID';
    
      // Query the API and print the results to the page.
      function queryReports() {
        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(displayResults, console.error.bind(console));
      }
    
      function displayResults(response) {
        var formattedJson = JSON.stringify(response.result, null, 2);
        document.getElementById('query-output').value = formattedJson;
      }
    </script>
        
        <h1>Google Identity Services Authorization Token model</h1>
        <button onclick="getToken();">Get access token</button><br><br>
        <button onclick="queryReports();">Query Reports</button><br><br>
        <button onclick="revokeToken();">Revoke token</button>
        
        <!-- The API response will be printed here. -->
    <textarea cols="80" rows="20" id="query-output"></textarea>
        
      </body>
    </html>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-12
      • 1970-01-01
      • 2016-11-22
      • 2016-08-19
      • 1970-01-01
      • 1970-01-01
      • 2018-09-14
      • 1970-01-01
      相关资源
      最近更新 更多