获取数据Google Analytics(分析)

时间:2019-01-23 12:35:37

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

用于获取Google Analytics(分析)数据的库。当要使用库获取数据时,在登录其给定数据后重定向gmail登录名,但是它将在服务器上的cron作业中设置。无法手动登录。因此,如何在不使用Gmail登录的情况下获取Google Analytics(分析)数据,或者有没有办法使用用户名和密码自动登录并获取数据。.使用库

define('CLIENT_ID', 'xxxxxxljg7pukglq.apps.googleusercontent.com');

/* Google App Client Secret */
define('CLIENT_SECRET', 'xxxxxxxxxxx');

/* Google App Redirect Url */
define('CLIENT_REDIRECT_URL', 'http://localhost:8080/ga1/oauth2callback.php');

已经具有用于手动登录的凭据和库

1 个答案:

答案 0 :(得分:0)

您的Google Analytics(分析)帐户

假设您将仅访问自己的数据。然后,您应该考虑使用服务帐户。服务帐户是虚拟用户,您可以随后将其授予Google Analytics(分析)帐户权限。然后,您无需执行常规登录即可访问您的数据

Hello analytics php service account

<?php

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

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


/**
 * Initializes an Analytics Reporting API V4 service object.
 *
 * @return An authorized Analytics Reporting API V4 service object.
 */
function initializeAnalytics()
{

  // 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__ . '/service-account-credentials.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;
}


/**
 * 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 = "<REPLACE_WITH_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");
        }
      }
    }
  }
}

不是您的Analytics(分析)帐户

如果您不访问自己的数据,则必须坚持使用Oauth2并对用户进行一次身份验证,然后请求脱机访问以保存刷新令牌,并稍后使用该令牌来请求新的访问令牌。无法在第一时间请求用户许可。