【问题标题】:Google analytics how to give access token谷歌分析如何提供访问令牌
【发布时间】:2017-09-15 18:55:24
【问题描述】:

我正在尝试从谷歌分析 API 获取实时用户

我正在关注这个:https://developers.google.com/analytics/devguides/reporting/core/v4/basics

我发布的数据如下:

$url = 'https://analyticsreporting.googleapis.com/v4/reports:batchGet';

//Initiate cURL.
$ch = curl_init($url);

$jsonDataEncoded = '{
  "reportRequests":
  [
    {
      "viewId": "109200098",
      "dateRanges": [{"startDate": "2014-11-01", "endDate": "2014-11-30"}],
      "metrics": [{"expression": "ga:users"}]
    }
  ]
}'
;

//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);

//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);

//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 

//Execute the request
$result = curl_exec($ch);

print_r($result);

{ "error": { "code": 401, "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.", "status": "UNAUTHENTICATED" } }

我知道我应该为此获得一些 OAuth,但我不知道如何做到这一点。 你能帮我解决这个问题吗? 谢谢!

index.php 和 oauth2callback.php

和这里一样:https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/web-php

现在我想使用 https://developers.google.com/analytics/devguides/reporting/realtime/v3/reference/data/realtime/get#auth 来获取 rt:activeUsers

我正在编辑 index.php :

    if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
      // Set the access token on the client.
      $client->setAccessToken($_SESSION['access_token']);

      // Create an authorized analytics service object.
      $analytics = new Google_Service_AnalyticsReporting($client);

      // Call the Analytics Reporting API V4.
      $response = getReport($analytics);

      $optParams = array(
    'dimensions' => 'rt:medium');

try {
  $results = $analytics->data_realtime->get(
      'ga:56789',
      'rt:activeUsers',
      $optParams);
  // Success. 
} catch (apiServiceException $e) {
  // Handle API service exceptions.
  $error = $e->getMessage();
}

      // Print the response.
      printResults($response);

    } else {
      $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php';
      header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
    }

出现错误:未定义属性:Google_Service_AnalyticsReporting::$data_realtime

【问题讨论】:

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


    【解决方案1】:

    我可以使用更新的 index.php 来做到这一点

    <?php
    
    // Load the Google API PHP Client Library.
    require_once __DIR__ . '/vendor/autoload.php';
    
    session_start();
    
    $client = new Google_Client();
    $client->setAuthConfig(__DIR__ . '/client_secret.json');
    $client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
    $service = new Google_Service_Analytics($client);
    
    // If the user has already authorized this app then get an access token
    // else redirect to ask the user to authorize access to Google Analytics.
    if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
      // Set the access token on the client.
      $client->setAccessToken($_SESSION['access_token']);
    
      // Create an authorized analytics service object.
      $analytics = new Google_Service_AnalyticsReporting($client);
    
      // Call the Analytics Reporting API V4.
      $response = getReport($analytics);
    
      // Print the response.
      printResults($response);
    
    
    
        $result = $service->data_realtime->get(
            'ga:<VIEWID CHANGE>',
            'rt:activeVisitors'
        );
        echo "<pre>";
        print_r($result->totalsForAllResults['rt:activeVisitors']);
        echo "</pre>";
    
    } else {
      $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php';
      header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
    }
    
    
    /**
     * Queries the Analytics Reporting API V4.
     *
     * @param service An authorized Analytics Reporting API V4 service object.
     * @return The Analytics Reporting API V4 response.
     */
    function getReport($analytics) {
    
      // Replace with your view ID, for example XXXX.
      $VIEW_ID = "<VIEW ID>";
    
      // Create the DateRange object.
      $dateRange = new Google_Service_AnalyticsReporting_DateRange();
      $dateRange->setStartDate("7daysAgo");
      $dateRange->setEndDate("today");
    
      // Create the Metrics object.
      $sessions = new Google_Service_AnalyticsReporting_Metric();
      $sessions->setExpression("ga:sessions");
      $sessions->setAlias("sessions");
    
      // Create the ReportRequest object.
      $request = new Google_Service_AnalyticsReporting_ReportRequest();
      $request->setViewId($VIEW_ID);
      $request->setDateRanges($dateRange);
      $request->setMetrics(array($sessions));
    
      $body = new Google_Service_AnalyticsReporting_GetReportsRequest();
      $body->setReportRequests( array( $request) );
      return $analytics->reports->batchGet( $body );
    }
    
    
    /**
     * Parses and prints the Analytics Reporting API V4 response.
     *
     * @param An Analytics Reporting API V4 response.
     */
    function printResults($reports) {
      for ( $reportIndex = 0; $reportIndex < count( $reports ); $reportIndex++ ) {
        $report = $reports[ $reportIndex ];
        $header = $report->getColumnHeader();
        $dimensionHeaders = $header->getDimensions();
        $metricHeaders = $header->getMetricHeader()->getMetricHeaderEntries();
        $rows = $report->getData()->getRows();
    
        for ( $rowIndex = 0; $rowIndex < count($rows); $rowIndex++) {
          $row = $rows[ $rowIndex ];
          $dimensions = $row->getDimensions();
          $metrics = $row->getMetrics();
          for ($i = 0; $i < count($dimensionHeaders) && $i < count($dimensions); $i++) {
            print($dimensionHeaders[$i] . ": " . $dimensions[$i] . "\n");
          }
    
          for ($j = 0; $j < count($metrics); $j++) {
            $values = $metrics[$j]->getValues();
            for ($k = 0; $k < count($values); $k++) {
              $entry = $metricHeaders[$k];
              print($entry->getName() . ": " . $values[$k] . "\n");
            }
          }
        }
      }
    }
    

    【讨论】:

      【解决方案2】:

      首先,如果您想访问实时数据,那么您使用了错误的 api。你应该使用realtime api

      使用 curl 进行身份验证有点复杂。您需要先获取刷新令牌。获得后,您可以在需要时使用以下内容获取访问令牌。

      curl \ –request POST \ –data ‘client_id=[Application Client Id]&client_secret=[Application Client Secret]&refresh_token=[Refresh token granted by second step]&grant_type=refresh_token’ \ https://accounts.google.com/o/oauth2/token
      

      您需要做的就是将 &access_token=token 添加到您对 api 发出的任何请求中。

      我的完整教程可以在这里找到Google auth curl

      更新

      请记住,实时 API 与报告 API 不同。如果您仍在引用报告 api,那么它就无法工作。您现在应该发送 HTTP GET 而不是 HTTP Post,并且终点是

      https://www.googleapis.com/analytics/v3/data/realtime  
      

      查看文档realtime.get 调用的格式也不同

      按照这些思路应该不会很难

      https://www.googleapis.com/analytics/v3/data/realtime?id=XXX&metrics=XXX&accesstoken=XXX  
      

      正如我所说,它是一个 HTTP GET,因此您可以在将其添加到 Curl 脚本之前将其转储到浏览器中进行测试。

      【讨论】:

      猜你喜欢
      • 2019-07-07
      • 2016-05-09
      • 2016-06-16
      • 2015-09-28
      • 2017-04-23
      • 2016-11-28
      • 1970-01-01
      • 2014-10-17
      • 2017-11-13
      相关资源
      最近更新 更多