youtube api错误登录需要php

时间:2016-10-05 21:41:25

标签: php laravel youtube youtube-api

我正在尝试获取YouTube视频的标题,但我收到了此错误

  

REST.php第118行中的Google_Service_Exception:需要登录

这是我的代码

function getCaptions($app, $developKey, $OAUTH2_CLIENT_ID, $OAUTH2_CLIENT_SECRET){

    $client = new Google_Client();
    $client->setApplicationName($app);
    $client->setDeveloperKey($developKey);
    $client->setClientId($OAUTH2_CLIENT_ID);
    $client->setClientSecret($OAUTH2_CLIENT_SECRET);
    $client->setScopes('https://www.googleapis.com/auth/youtube.force-ssl');
    $client->setScopes('https://www.googleapis.com/auth/youtube');

    $redirect = filter_var('https://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],
        FILTER_SANITIZE_URL);
    $client->setRedirectUri($redirect);

    // Define an object that will be used to make all API requests.
    $youtube = new Google_Service_YouTube($client);

    $captions = $youtube->captions->listCaptions('snippet',$video);

    if (empty($captions)) {
        $htmlBody .= "<h3>Can't get video caption tracks.</h3>";
    } else {
        $firstCaptionId = $captions[0]['id'];
        $this->downloadCaption($youtube, $firstCaptionId, $htmlBody);
    }

    return response()->json($searchResponse->items[0]->snippet);
}  

function downloadCaption(Google_Service_YouTube $youtube, $captionId, &$htmlBody) {
    // Call the YouTube Data API's captions.download method to download an existing caption.
    $captionResouce = $youtube->captions->download($captionId, array(
        'tfmt' => "srt",
        'alt' => "media"
));

$htmlBody .= "<h2>Downloaded caption track</h2><ul>";
$htmlBody .= sprintf('<li>%s</li>',
  $captionResouce);
$htmlBody .= '</ul>';
}

我知道我需要一个代码来进行身份验证($client->authentication($code);),但我不知道在哪里可以获得该代码。

1 个答案:

答案 0 :(得分:0)

确保您有oauth部分$client->setAuthConfig($oauth_credentials);

$client = new Google_Client();
$client->setAuthConfig($oauth_credentials);
$client->setRedirectUri($redirect_uri);
$client->addScope("https://www.googleapis.com/auth/drive");
$service = new Google_Service_Drive($client);

这是谷歌在ObservableList中提供的方式。您将看到setAuthConfig始终包含在php示例中。