首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PHP YouTube thumbnails.set失败

PHP YouTube thumbnails.set失败
EN

Stack Overflow用户
提问于 2014-03-04 11:38:02
回答 1查看 2.6K关注 0票数 3

我试图用YouTube库使用YouTube API更新一个视频缩略图。我们使用的是1.0.3-beta版本。

我复制/粘贴了示例,并将我们的client_idclient_secret更改为client_idclient_secret的值,这是因为我仍然可以使用这些值来上传视频,我只是不能设置缩略图(在我刚刚使用相同凭证上传的视频上)。

这是我得到的错误:

代码语言:javascript
复制
An client error occurred: Error calling PUT https://www.googleapis.com/upload/youtube/v3/thumbnails/set?videoId=wL3Rt0sokdI&uploadType=resumable&upload_id=AEnB2UqFI4w1qO1gjoFS-fOlc61OthOht0ngdFAcdG9Nnufds61IyMIUUxf1rAvmoDl77LeEQZb1-HMyqtc9Op3Jg4hRfcyuOQ: (403) Forbidden

编辑-更多信息:这是我打印出整个异常时获得的信息片段:

代码语言:javascript
复制
{
    ["errors":protected]=> array(1) 
    {
        [0]=> array(5) { 
            ["domain"]=> string(17) "youtube.thumbnail" 
            ["reason"]=> string(9) "forbidden" 
            ["message"]=> string(9) "Forbidden" 
            ["locationType"]=> string(6) "header" 
            ["location"]=> string(13) "Authorization" 
    } 
}

下面是我使用的脚本(它与示例代码相同,但我把它放在这里,以防上面的示例URL下降):

代码语言:javascript
复制
/**
 * This sample uploads and sets a custom thumbnail for a video.
 *
 * 1. It uploads an image using the "Google_MediaFileUpload" class.
 * 2. It sets the uploaded image as a custom thumbnail to the video by
 *    calling the API's "youtube.thumbnails.set" method
 *
 * @author Ibrahim Ulukaya
*/


// Call set_include_path() as needed to point to your client library.
set_include_path('/path/to/google-api-php-client/src/');
require_once('Google/Client.php');
require_once('Google/Service/YouTube.php');
session_start();

/*
 * You can acquire an OAuth 2.0 client ID and client secret from the
 * Google Developers Console <https://cloud.google.com/console>
 * For more information about using OAuth 2.0 to access Google APIs, please see:
 * <https://developers.google.com/youtube/v3/guides/authentication>
 * Please ensure that you have enabled the YouTube Data API for your project.
 */
$OAUTH2_CLIENT_ID = 'OURCLIENTIDWASHERE';
$OAUTH2_CLIENT_SECRET = 'OURCLIENTSECRETWASHERE';

$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setScopes('https://www.googleapis.com/auth/youtube');
$redirect = filter_var('http://' . $_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);

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);
}

if (isset($_SESSION['token'])) {
  $client->setAccessToken($_SESSION['token']);
}

// Check to ensure that the access token was successfully acquired.
if ($client->getAccessToken()) {
  try{

    // REPLACE this value with the video ID of the video being updated.
    $videoId = "wL3Rt0sokdI";

    // REPLACE this value with the path to the image file you are uploading.
    $imagePath =     "/path/to/image.jpg";

    // Specify the size of each chunk of data, in bytes. Set a higher value for
    // reliable connection as fewer chunks lead to faster uploads. Set a lower
    // value for better recovery on less reliable connections.
    $chunkSizeBytes = 1 * 1024 * 1024;

    // Setting the defer flag to true tells the client to return a request which can be     called
    // with ->execute(); instead of making the API call immediately.
    $client->setDefer(true);

    // Create a request for the API's thumbnails.set method to upload the image and     associate
    // it with the appropriate video.
    $setRequest = $youtube->thumbnails->set($videoId);

    // Create a MediaFileUpload object for resumable uploads.
    $media = new Google_Http_MediaFileUpload(
        $client,
        $setRequest,
        'image/jpeg',
        null,
        true,
        $chunkSizeBytes
);
$media->setFileSize(filesize($imagePath));


// Read the media file and upload it chunk by chunk.
$status = false;
$handle = fopen($imagePath, "rb");
while (!$status && !feof($handle)) {
  $chunk = fread($handle, $chunkSizeBytes);
  $status = $media->nextChunk($chunk);
}

fclose($handle);

// If you want to make other calls after the file upload, set setDefer back to false
$client->setDefer(false);


$thumbnailUrl = $status['items'][0]['default']['url'];
$htmlBody .= "<h3>Thumbnail Uploaded</h3><ul>";
$htmlBody .= sprintf('<li>%s (%s)</li>',
    $videoId,
    $thumbnailUrl);
$htmlBody .= sprintf('<img src="%s">', $thumbnailUrl);
$htmlBody .= '</ul>';


} catch (Google_ServiceException $e) {
  $htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>',
      htmlspecialchars($e->getMessage()));
} catch (Google_Exception $e) {
  $htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>',
      htmlspecialchars($e->getMessage()));
}

$_SESSION['token'] = $client->getAccessToken();
} 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;
}
?>

<!doctype html>
<html>
<head>
<title>Claim Uploaded</title>
</head>
<body>
  <?=$htmlBody?>
</body>
</html>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-03-04 14:25:34

我终于想出了答案。YouTube帐户没有上传自定义缩略图的权限(尽管可以从YouTube后端“选择”缩略图)。

您可以在以下网址上找到在帐户上启用的功能列表:http://www.youtube.com/features

在我的例子中,我需要未启用的自定义缩略图权限:

显然,只要您的帐户处于良好状态,验证您的YouTube帐户就会授予此权限。

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22170881

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档