获取'禁止错误'在尝试执行youtube分析API时

时间:2016-09-15 07:27:12

标签: php youtube-analytics-api

尝试执行youtube analytics API时收到错误消息。

  

发生服务错误:调用GET时出错   https://www.googleapis.com/youtube/analytics/v1/reports?ids=channel%3D%3DUCaayLD9i5x4MmIoVZxXSv_g&start-date=2016-08-01&end-date=2016-08-07&metrics=views&dimensions=7DayTotals:   (403)禁止

这是我的代码:

require_once __DIR__.'\google-api-php-client-1-master\src\Google\autoload.php';
require_once __DIR__.'\google-api-php-client-1-master\src\Google\Client.php';
require_once __DIR__.'\google-api-php-client-1-master\src\Google\Service\YouTube.php';
session_start();
$key = file_get_contents('mykey.json');
$OAUTH2_CLIENT_ID = 'xx-xx-xx';
$OAUTH2_CLIENT_SECRET = 'xxx';
$scope = array("https://www.googleapis.com/auth/youtube.force-ssl", "https://www.googleapis.com/auth/youtubepartner-channel-audit", "https://www.googleapis.com/auth/youtube", "https://www.googleapis.com/auth/youtube.readonly", "https://www.googleapis.com/auth/yt-analytics.readonly", "https://www.googleapis.com/auth/yt-analytics-monetary.readonly","https://www.googleapis.com/auth/youtubepartner");

    $client = new Google_Client();
    $client->setClientId($OAUTH2_CLIENT_ID);
    $client->setClientSecret($OAUTH2_CLIENT_SECRET);
    $client->setAccessType('offline');
    $client->setAccessToken($key);
    $client->setScopes($scope);
      if ($client->getAccessToken()) {        
    //Check to see if our access token has expired. If so, get a new one and save it to file for future use.
        if($client->isAccessTokenExpired()) {
            //refresh your access token if it's expired
            $newToken = json_decode($client->getAccessToken());
            $client->refreshToken($newToken->refresh_token);
            file_put_contents('mykey.json', $client->getAccessToken());
        }

        $analytics = new Google_Service_YouTubeAnalytics($client);
            $channel_url = 'UCaayLD9i5x4MmIoVZxXSv_g';
            $ids = 'channel==' . $channel_url . '';
            $end_date = '2016-08-07';
            $start_date = '2016-08-01';
            $optparams = array(
            'dimensions' => '7DayTotals',
            );
            $metric = 'views';
            $api = $analytics->reports->query($ids, $start_date, $end_date, $metric, $optparams);
            echo '<pre>';print_r($api);die;
  }

我已启用'youtube analytic API',我从here获取了access_token

我的代码有什么问题,或者我们是否需要做更多的事情来摆脱这个?

1 个答案:

答案 0 :(得分:1)

查看您的代码,似乎您在将其保存到文件时生成新的访问令牌(使第一个令牌无效)。

尝试:

  if($client->isAccessTokenExpired()) {
        //refresh your access token if it's expired
        $newToken = json_decode($client->getAccessToken());
        $client->refreshToken($newToken->refresh_token);
        file_put_contents('mykey.json', $newToken);
    }