首页 文章

Google AnalyticsAPI:自动登录用户和获取数据,显示错误“OAuth客户端无效” .

提问于
浏览
0

我想使用oAuth访问谷歌分析数据,这样我就不必一次又一次地登录 .

为此我下载google analytic Php library ,使用 composer 安装它,把 code 提供 google ,我的代码如下 -

require_once 'vendor/autoload.php';

    $analytics = initializeAnalytics();
    $profile = getFirstProfileId($analytics);
    $results = getResults($analytics, $profile);
    printResults($results);

    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 = 'myproject.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_Analytics($client);

      return $analytics;
    }

    function getFirstProfileId($analytics) {
        // Get the user's first view (profile) ID.
        // Get the list of accounts for the authorized user.
        $accounts = $analytics->management_accounts->listManagementAccounts();


      if (count($accounts->getItems()) > 0) {
        $items = $accounts->getItems();
        $firstAccountId = $items[0]->getId();

        // Get the list of properties for the authorized user.
        $properties = $analytics->management_webproperties
            ->listManagementWebproperties($firstAccountId);

        if (count($properties->getItems()) > 0) {
          $items = $properties->getItems();
          $firstPropertyId = $items[0]->getId();

          // Get the list of views (profiles) for the authorized user.
          $profiles = $analytics->management_profiles
              ->listManagementProfiles($firstAccountId, $firstPropertyId);

          if (count($profiles->getItems()) > 0) {
            $items = $profiles->getItems();

            // Return the first view (profile) ID.
            return $items[0]->getId();

          } else {
            throw new Exception('No views (profiles) found for this user.');
          }
        } else {
          throw new Exception('No properties found for this user.');
        }
      } else {
        throw new Exception('No accounts found for this user.');
      }
    }

    function getResults($analytics, $profileId) {
      // Calls the Core Reporting API and queries for the number of sessions
      // for the last seven days.
       return $analytics->data_ga->get(
           'ga:' . $profileId,
           '7daysAgo',
           'today',
           'ga:sessions');
    }

    function printResults($results) {
      // Parses the response from the Core Reporting API and prints
      // the profile name and total sessions.
      if (count($results->getRows()) > 0) {

        // Get the profile name.
        $profileName = $results->getProfileInfo()->getProfileName();

        // Get the entry for the first entry in the first row.
        $rows = $results->getRows();
        $sessions = $rows[0][0];

        // Print the results.
        print "First view (profile) found: $profileName\n";
        print "Total sessions: $sessions\n";
      } else {
        print "No results found.\n";
      }
    }

当我以前运行此代码时,它提供以下错误 -

致命错误:未捕获Google_Service_Exception:{“error”:“invalid_client”,“error_description”:“OAuth客户端无效 . ”在第118行的D:\ wamp64 \ www \ store2 \ pdf \ printpdf \ vendor \ google \ apiclient \ src \ Google \ Http \ REST.php中

基本上,如果任何人可以为我提供从谷歌分析访问数据的一步一步的过程,因为我整天推出我的头,但没有一个帖子可以提供我的步骤,我发现一些旧的,而不是为我工作

1 回答

  • 0

    这是我使用的代码

    Serviceaccount.php

    // Load the Google API PHP Client Library.
    require_once __DIR__ . '/vendor/autoload.php';
    
    // 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.
    putenv('GOOGLE_APPLICATION_CREDENTIALS='.__DIR__.'/service-account.json');
    $service = getAuthenticateServiceAccount();
    
    
    /**
     * Authenticating to Google using a Service account
     * Documentation: https://developers.google.com/api-client-library/php/auth/service-accounts
     * Initializes an Analyticsreporting.v4 service object.
     *
     * @return An authorized Analyticsreporting.v4 service object.
     */
    function getAuthenticateServiceAccount() {
        try {   
    
            // Create and configure a new client object.        
            $client = new Google_Client();
            $client->useApplicationDefaultCredentials();
            $client->addScope(Google_Service_Analytics::ANALYTICS);
            return new Google_Service_AnalyticsReporting($client);
        } catch (Exception $e) {
            print "An error occurred: " . $e->getMessage();
        }
    }
    ?>
    

    Reporting.php

    // Load the Google API PHP Client Library.
    require_once __DIR__ . '/vendor/autoload.php';
    require_once __DIR__ . '/ServiceAccount.php';
    
    // Create the DateRange object.
    $dateRange = new Google_Service_AnalyticsReporting_DateRange();
    $dateRange->setStartDate("2016-01-01");
    $dateRange->setEndDate("2017-06-30");
    
    // Create the Metrics object.
    $sessions = new Google_Service_AnalyticsReporting_Metric();
    $sessions->setExpression("ga:sessions");
    $sessions->setAlias("ga:sessions");
    
    $users = new Google_Service_AnalyticsReporting_Metric();
    $users->setExpression("ga:users");
    $users->setAlias("ga:users");
    
    
    
    //Create the Dimensions object.
    $date = new Google_Service_AnalyticsReporting_Dimension();
    $date->setName("ga:date");
    $pagePath = new Google_Service_AnalyticsReporting_Dimension();
    $pagePath->setName("ga:pagePath");
    
    // Create the ReportRequest object.
    $request = new Google_Service_AnalyticsReporting_ReportRequest();
    $request->setViewId("81692014");
    $request->setPageSize("10000");
    $request->setDateRanges($dateRange);
    $request->setDimensions(array($date,$pagePath));
    $request->setMetrics(array($sessions,$users));
    
    $body = new Google_Service_AnalyticsReporting_GetReportsRequest();
    $body->setReportRequests( array( $request) );
    $data =  $service->reports->batchGet( $body );
    
    
    showData($data->reports[0]);
    $cnt = 0; 
    while ($data->reports[0]->nextPageToken > 0 && $cnt < 1) {
        // There are more rows for this report.
        $body->reportRequests[0]->setPageToken($data->reports[0]->nextPageToken);
        $data =  $service->reports->batchGet( $body );
        showData($data->reports[0]);
        $cnt++;
        }
    
    
    
    function showData($data)  {
        ?> <pre><table><?php
    
        ?><tr><?php // Header start row
        for($i = 0; $i < sizeof($data->columnHeader->dimensions);$i++)  {
            ?> <td> <?php print_r($data->columnHeader->dimensions[$i]); ?> </td> <?php
        }
        for($i = 0; $i < sizeof($data->columnHeader->metricHeader->metricHeaderEntries);$i++)   {
            ?> <td> <?php print_r($data->columnHeader->metricHeader->metricHeaderEntries[$i]->name); ?> </td> <?php
        }
        ?><tr><?php  // Header row end
    
        // Display data
        for($i = 0; $i < sizeof($data->data->rows);$i++)    {
    
            ?><tr><?php // Data row start
            // Dimensions
            for($d = 0; $d < sizeof($data->columnHeader->dimensions);$d++)  {
                ?> <td> <?php print_r($data->data->rows[$i]->dimensions[$d]); ?> </td> <?php
            }
            // Metrics
            for($m = 0; $m < sizeof($data->columnHeader->metricHeader->metricHeaderEntries);$m++)   {
                ?> <td> <?php print_r($data->data->rows[$i]->metrics[0]->values[$m]); ?> </td> <?php
            }
            ?><tr><?php  // Header row end
        }
        ?></table></pre><?php
    }
    
    
    function showText($data)
    {
     ?> <pre> <?php print_r($data); ?> </pre> <?php
    }
    /**
    * Returns the Analytics data. 
    * Documentation https://developers.google.com/analyticsreporting/v4/reference/reports/batchGet
    * Generation Note: This does not always build corectly.  Google needs to standardise things I need to figuer out which ones are wrong.
    * @service Authenticated Analyticsreporting service.</param>  
    * @body A valid Analyticsreporting v4 body.</param>
    * @return GetReportsResponseResponse</returns>
    */
    function BatchGet($service, $body)
    {
        try
        {
            // Initial validation.
            if ($service == null)
                throw new Exception("service");
            if ($body == null)
                throw new Exception("body");
    
            // Make the request.
            return $service->reports->batchGet($body);
        }
        catch (Exception $ex)
        {
            throw new Exception("Request Reports.BatchGet failed.", $ex->getMessage());
        }
    }
    ?>
    

    Update

    请务必确保您已在帐户一级将服务帐户评估授予您的Google Analytics帐户 .

    enter image description here

    注意代码是从我的github项目中删除的

相关问题