【问题标题】:Google API PHP - OAuth Issue - "Request had invalid authentication credentials"Google API PHP - OAuth 问题 - “请求具有无效的身份验证凭据”
【发布时间】:2016-10-15 17:31:31
【问题描述】:

我正在尝试让 Google 的 API PHP 客户端与 OAuth 一起使用,以便我可以访问 Analytics 和 Search Console 数据。我一直在关注example here from Google。我被发送到 Google 以登录并授权访问,然后当我被重定向回该站点时,我收到 401 错误“请求具有无效的身份验证凭据”。

注意我正在使用Google API PHP Client

我一直在寻找几个小时,但无法让它正常工作。这是我的代码。

在 index.php 中:

<?php
require_once '../../vendor/autoload.php';

session_start();

$client = new Google_Client();
$client->setAuthConfig('../../public/client_secrets.json');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
$client->setApplicationName("Tool");
$client->setAccessType("offline");


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

  var_dump($_SESSION);

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

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

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


function getReport($analytics) {

  // Replace with your view ID. E.g., XXXX.
  $VIEW_ID = "XXXXXXXX";

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

这是在 oauth2callback.php 中:

<?php
require_once '../../vendor/autoload.php';

// Start a session to persist credentials.
session_start();

// Create the client object and set the authorization configuration
// from the client_secrets.json you downloaded from the Developers Console.
$client = new Google_Client();
$client->setAuthConfig('../../public/client_secrets.json');
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
$client->setApplicationName("Tool");
$client->setAccessType("offline");

// Handle authorization flow from the server.
if (! isset($_GET['code'])) {
  $auth_url = $client->createAuthUrl();
  header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
  $client->authenticate($_GET['code']);
  $_SESSION['access_token'] = $client->getAccessToken();
  $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/tests/simple-file-upload.php';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

有谁知道哪里出了问题?

【问题讨论】:

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


    【解决方案1】:

    不要直接从代码中尝试,而是使用 REST 客户端来发送和接收请求和响应。成功后,在代码中使用这些参数。

    【讨论】:

      猜你喜欢
      • 2020-11-09
      • 1970-01-01
      • 2019-11-11
      • 2021-03-02
      • 2019-04-06
      • 1970-01-01
      • 1970-01-01
      • 2020-09-11
      • 2019-06-23
      相关资源
      最近更新 更多