2016-08-29 8 views
0

각 채널의 분석 보고서에서 분마다 모든 데이터를 다운로드하고 싶지만 403 오류가 발생합니다. 어떤 종류의 권한이 필요합니까? Analytics Reporting API에 대한 액세스 권한을 얻으려면 어떻게해야합니까? 그것은 나를 위해 API를 사용할 수 없다고 말합니다.Youtube SDK - Analytics에서 Analytics의 액세스 및 데이터 덤프를 PHP로보고하는 방법?

또한 정규 서버 (하루에 적어도 10 번)에서 데이터를 가져 오는 서버 2 서버 인증은 작동합니까?

$client = new Google_Client(); 
$client->setClientId($OAUTH2_CLIENT_ID); 
$client->setClientSecret($OAUTH2_CLIENT_SECRET); 

/* 
* This OAuth 2.0 access scope allows for read access to the YouTube Analytics monetary reports for 
* authenticated user's account. Any request that retrieves earnings or ad performance metrics must 
* use this scope. 
*/ 
$client->setScopes(array('https://www.googleapis.com/auth/youtube.readonly', 'https://www.googleapis.com/auth/yt-analytics.readonly')); 
$redirect = filter_var('https://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'], 
    FILTER_SANITIZE_URL); 
$redirect = str_replace('.php', '', $redirect); 
$client->setRedirectUri($redirect); 

if (isset($_GET['code'])) { 
    if (strval($_SESSION['state']) !== strval($_GET['state'])) { 
     die('The session state did not match.'); 
    } 

    $client->authenticate($_GET['code']); 
    $_SESSION['token'] = $client->getAccessToken(); 
    header('Location: ' . $redirect); 
} 
try { 
    if (isset($_SESSION['token'])) { 
     $client->setAccessToken($_SESSION['token']); 
    } 
    if ($client->getAccessToken()) { 
     $youtube = new Google_Service_YouTube($client); 
     //die("<pre>" . var_export($youtube->channels->listChannels('id', array('forUsername' => 'kingbach')),1)); 
     $analytics = new Google_Service_YouTubeAnalytics($client); 

     $id = 'channel==<CHANNEL_ID>'; 
     $start_date = '2016-09-17'; 
     $end_date = '2016-09-24'; 
     $optparams = array(
      'onBehalfOfContentOwner' => '<USERNAME>' 
     ); 

     $metrics = array(
      'views', 
      'estimatedMinutesWatched', 
      'averageViewDuration', 
      'comments', 
      //'favoritesAdded', 
      //'favoritesRemoved', 
      'likes', 
      'dislikes', 
      'shares', 
      'subscribersGained', 
      'subscribersLost' 
     ); 

     $api_response = $metrics; 

     foreach ($metrics as $metric) { 
      $api = $analytics->reports->query($id, $start_date, $end_date, $metric, $optparams); 
      if (isset($api['rows'])) { 
       $api_response[$metric] = $api['rows'][0][0]; 
      } 
     } 

    } else { 
     // If the user hasn't authorized the app, initiate the OAuth flow 
     $state = mt_rand(); 
     $client->setState($state); 
     $_SESSION['state'] = $state; 

     $authUrl = $client->createAuthUrl(); 
     $htmlBody = <<<END 
    <h3>Authorization Required</h3> 
    <p>You need to <a href="$authUrl">authorize access</a> before proceeding.<p> 
END; 
    } 

} catch (\Exception $e) { 
    die("<pre>" . $e->getMessage() . "</pre>"); 
} 

답변