15

我在尝试执行 youtube 分析 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'并且我从这里获得了 access_token

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

4

1 回答 1

2

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

尝试 :

  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);
    }
于 2017-05-26T11:42:11.227 回答