使用Google Analytics Reporting API V4时出错 - php

我正在尝试使用Google Analytics Reporting API V4,并且按此链接中所述进行了所有操作:reporting api v4

现在我收到此错误:

Fatal error: Uncaught exception 'Google_Service_Exception' with message '{ "error": "invalid_grant", "error_description": "Invalid JWT Signature." } ' in C:\xampp\htdocs\gaapi\vendor\google\apiclient\src\Google\Http\REST.php:118 Stack trace: #0 C:\xampp\htdocs\gaapi\vendor\google\apiclient\src\Google\Http\REST.php(94): Google_Http_REST::decodeHttpResponse(Object(GuzzleHttp\Psr7\Response), Object(GuzzleHttp\Psr7\Request), 'Google_Service_...') #1 [internal function]: Google_Http_REST::doExecute(Object(GuzzleHttp\Client), Object(GuzzleHttp\Psr7\Request), 'Google_Service_...') #2 C:\xampp\htdocs\gaapi\vendor\google\apiclient\src\Google\Task\Runner.php(181): call_user_func_array(Array, Array) #3 C:\xampp\htdocs\gaapi\vendor\google\apiclient\src\Google\Http\REST.php(58): Google_Task_Runner->run() #4 C:\xampp\htdocs\gaapi\vendor\google\apiclient\src\Google\Client.php(779): Google_Http_REST::execute(Object(GuzzleHttp\Client), Object(GuzzleHttp\Psr7\Request), 'Google_Service_...', Array) #5 C:\xampp\htdocs\gaapi\vendor\google\a in C:\xampp\htdocs\gaapi\vendor\google\apiclient\src\Google\Http\REST.php on line 118

这是rest.php,我从以下位置得到此错误:

   <?php
/*
 * Copyright 2010 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

use Google\Auth\HttpHandler\HttpHandlerFactory;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7\Response;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;

/**
 * This class implements the RESTful transport of apiServiceRequest()'s
 */
class Google_Http_REST
{
  /**
   * Executes a Psr\Http\Message\RequestInterface and (if applicable) automatically retries
   * when errors occur.
   *
   * @param Google_Client $client
   * @param Psr\Http\Message\RequestInterface $req
   * @return array decoded result
   * @throws Google_Service_Exception on server side error (ie: not authenticated,
   *  invalid or malformed post body, invalid url)
   */
  public static function execute(
      ClientInterface $client,
      RequestInterface $request,
      $expectedClass = null,
      $config = array(),
      $retryMap = null
  ) {
    $runner = new Google_Task_Runner(
        $config,
        sprintf('%s %s', $request->getMethod(), (string) $request->getUri()),
        array(get_class(), 'doExecute'),
        array($client, $request, $expectedClass)
    );

    if (!is_null($retryMap)) {
      $runner->setRetryMap($retryMap);
    }

    return $runner->run();
  }

  /**
   * Executes a Psr\Http\Message\RequestInterface
   *
   * @param Google_Client $client
   * @param Psr\Http\Message\RequestInterface $request
   * @return array decoded result
   * @throws Google_Service_Exception on server side error (ie: not authenticated,
   *  invalid or malformed post body, invalid url)
   */
  public static function doExecute(ClientInterface $client, RequestInterface $request, $expectedClass = null)
  {
    try {
      $httpHandler = HttpHandlerFactory::build($client);
      $response = $httpHandler($request);
    } catch (RequestException $e) {
      // if Guzzle throws an exception, catch it and handle the response
      if (!$e->hasResponse()) {
        throw $e;
      }

      $response = $e->getResponse();
      // specific checking for Guzzle 5: convert to PSR7 response
      if ($response instanceof \GuzzleHttp\Message\ResponseInterface) {
        $response = new Response(
            $response->getStatusCode(),
            $response->getHeaders() ?: [],
            $response->getBody(),
            $response->getProtocolVersion(),
            $response->getReasonPhrase()
        );
      }
    }

    return self::decodeHttpResponse($response, $request, $expectedClass);
  }

  /**
   * Decode an HTTP Response.
   * @static
   * @throws Google_Service_Exception
   * @param Psr\Http\Message\RequestInterface $response The http response to be decoded.
   * @param Psr\Http\Message\ResponseInterface $response
   * @return mixed|null
   */
  public static function decodeHttpResponse(
      ResponseInterface $response,
      RequestInterface $request = null,
      $expectedClass = null
  ) {
    $code = $response->getStatusCode();

    // retry strategy
    if ((intVal($code)) >= 400) {
      // if we errored out, it should be safe to grab the response body
      $body = (string) $response->getBody();

      // Check if we received errors, and add those to the Exception for convenience
      throw new Google_Service_Exception($body, $code, null, self::getResponseErrors($body));
    }

    // Ensure we only pull the entire body into memory if the request is not
    // of media type
    $body = self::decodeBody($response, $request);

    if ($expectedClass = self::determineExpectedClass($expectedClass, $request)) {
      $json = json_decode($body, true);

      return new $expectedClass($json);
    }

    return $response;
  }

  private static function decodeBody(ResponseInterface $response, RequestInterface $request = null)
  {
    if (self::isAltMedia($request)) {
      // don't decode the body, it's probably a really long string
      return '';
    }

    return (string) $response->getBody();
  }

  private static function determineExpectedClass($expectedClass, RequestInterface $request = null)
  {
    // "false" is used to explicitly prevent an expected class from being returned
    if (false === $expectedClass) {
      return null;
    }

    // if we don't have a request, we just use what's passed in
    if (is_null($request)) {
      return $expectedClass;
    }

    // return what we have in the request header if one was not supplied
    return $expectedClass ?: $request->getHeaderLine('X-Php-Expected-Class');
  }

  private static function getResponseErrors($body)
  {
    $json = json_decode($body, true);

    if (isset($json['error']['errors'])) {
      return $json['error']['errors'];
    }

    return null;
  }

  private static function isAltMedia(RequestInterface $request = null)
  {
    if ($request && $qs = $request->getUri()->getQuery()) {
      parse_str($qs, $query);
      if (isset($query['alt']) && $query['alt'] == 'media') {
        return true;
      }
    }

    return false;
  }
}

这是调用API的php文件:

   <?php

// Load the Google API PHP Client Library.
require_once __DIR__ . '/vendor/autoload.php';

$analytics = initializeAnalytics();
$response = getReport($analytics);
printResults($response);

function initializeAnalytics()
{
  // Creates and returns the Analytics Reporting service object.

  // Use the developers console and download your service account
  // credentials in JSON format. Place them in this directory or
  // change the key file location if necessary.
  $KEY_FILE_LOCATION = __DIR__ . '/DMCwizard-90f81ab1b049.json';

  // Create and configure a new client object.
  $client = new Google_Client();
  $client->setApplicationName("Hello Analytics Reporting");
  $client->setAuthConfig($KEY_FILE_LOCATION);
  $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
  $analytics = new Google_Service_AnalyticsReporting($client);

  return $analytics;
}

function getReport(&$analytics) {

  // Replace with your view ID, for example XXXX.
  $VIEW_ID = "123747116";

  // 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 );
}

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( $metricHeaders ) && $j < count( $metrics ); $j++) {
        $entry = $metricHeaders[$j];
        $values = $metrics[$j];
        print("Metric type: " . $entry->getType() . "\n" );
        for ( $valueIndex = 0; $valueIndex < count( $values->getValues() ); $valueIndex++ ) {
          $value = $values->getValues()[ $valueIndex ];
          print($entry->getName() . ": " . $value . "\n");
        }
      }
    }
  }

}

如果您需要我为您上传其他文件,请告诉我。

参考方案

我应该只将导致异常的部分代码放入try catch块中。而且工作正常。因此,如果您想使用GA report API版本4,则只需添加此try catch,其他所有事情都必须与document完全一样,然后就可以完成。

Google Analytics PHP API:找不到目标 - php

在我公司,我们决定使用Google Analytics(分析)来获取有关访问者,进入渠道等的一些有趣指标...当访问者提交联系表单时,我创建了一个“触发”的目标,一切工作正常,我什至创建了一个细分来预览使用该表单的人与其他人之间的区别。使用PHP API,我有自己的仪表板表,其中逐个列出了每个会话的一些详细信息,其中包括:每个访问的URL约会时间如果来自Ad…

Google Analytics API-不完整的报告批次 - php

因此,我们有一个有效的API,可以在特定日期范围内获取报告。最近,我们尝试获取行数达到40,000个结果的报告。我们从API得到响应,并且能够提取前1000行。现在的问题是分页。查询设置为每批检索1,000行,因此总共40批(基于40,000行)。根据analytics api pagination,从api响应中检索nextPageToken并将其设置为下…

Google Analytics(分析)报告中的分页 - php

在这里,我正在获取下一个和上一个URL,但是当尝试使用该URL访问下一页时,由于网址= https://www.googleapis.com/analytics/v3/data/ga?ids=ga:85914642&dimensions=ga:pagePath,ga:date&metrics=ga:pageviews,ga:uniquePag…

我们如何使用API​​访问特定的Google Analytics(分析)帐户数据? - php

我们正在开发一个Web应用程序,允许客户创建和显示产品。我们想在管理面板中为客户提供Google Analytics(分析)帐户中有关其产品的指标。不幸的是,GA API文档并未说明如何执行此操作。所有示例均基于OAuth 2.0身份验证,以便获得对用户GA数据(而非网站帐户)的访问权限。有没有一种方法可以访问我们有权访问的帐户的Google Analyti…

使用php将交易推送到Google Analytics(分析) - php

我需要将离线交易推送到Google Analytics(分析)。我正在考虑创建一个php脚本来查询电子商务数据库,以查看从后端创建的最近一小时内进行的交易。确定了这些交易(以及订单项/ SKU)。如何使用PHP将数据推送到Google Analytics(分析)? 参考方案 您需要通过measurement protocol。没有客户端库可以帮助您在PHP中…