0

Google API PHP 클라이언트와 OAuth를 함께 사용하여 Analytics 및 Search Console 데이터에 액세스 할 수있게하려고합니다. 나는 example here from Google을 따라 왔습니다. Google에 로그인하여 액세스를 승인하면 사이트로 리디렉션 될 때 'Request has invalid authentication credentials'라는 401 오류가 발생합니다.Google API PHP - OAuth 문제 - "요청에 잘못된 인증 자격증 명이 있습니다."

N.B. 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)); 
} 

사람이 잘못 될 수 있는지 알고 있나요?

답변

0

코드에서 직접 시도하는 대신 REST 클라이언트를 사용하여 요청 및 응답을 보내고받습니다. 성공적으로 완료되면 코드에서 해당 매개 변수를 사용하십시오.

관련 문제