【问题标题】:PHP + Youtube API - how to allow user to upload videos to my own channel?PHP + Youtube API - 如何允许用户将视频上传到我自己的频道?
【发布时间】:2016-10-19 14:43:55
【问题描述】:

我正在尝试构建一个允许用户将视频上传到我的频道的网络应用程序。

所以我想我必须选择OAuth 2.0 for Server to Server Applications,正如它在那里所说的那样:

通常,应用程序在 应用程序使用 Google API 处理其自己的数据,而不是 用户的数据

所以我已经按照create a service account 的步骤进行操作。但在完成这些步骤并生成密钥和 id 后,我收到以下错误:

发生客户端错误:无法启动可恢复上传(HTTP 401:youtube.header,未经授权)

这是我的全部代码:

// Load 'Google/Client.php' and 'Google/Service/YouTube.php' with composer.
require_once __DIR__ . '/vendor/autoload.php';
session_start();

$client_email = 'xxx@developer.gserviceaccount.com';
$private_key = file_get_contents('xxx-74c6a50933e3.p12');
$scopes = array(
  'https://www.googleapis.com/auth/youtube.upload',
  'https://www.googleapis.com/auth/youtube',
  'https://www.googleapis.com/auth/youtubepartner'
);

$credentials = new Google_Auth_AssertionCredentials(
    $client_email,
    $scopes,
    $private_key
);

$client = new Google_Client();
$client->setAssertionCredentials($credentials);
if ($client->getAuth()->isAccessTokenExpired()) {
     $client->getAuth()->refreshTokenWithAssertion();
}

$htmlBody = '';

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

$htmlBody = '';

// Check to ensure that the access token was successfully acquired.
if ($client->getAccessToken()) {
  try{
    // REPLACE this value with the path to the file you are uploading.
    $videoPath = "/home/xxx/Desktop/Vids/small.mp4";

    // Create a snippet with title, description, tags and category ID
    // Create an asset resource and set its snippet metadata and type.
    // This example sets the video's title, description, keyword tags, and
    // video category.
    $snippet = new Google_Service_YouTube_VideoSnippet();
    $snippet->setTitle("Test title");
    $snippet->setDescription("Test description");
    $snippet->setTags(array("tag1", "tag2"));

    // Numeric video category. See
    // https://developers.google.com/youtube/v3/docs/videoCategories/list
    $snippet->setCategoryId("22");

    // Set the video's status to "public". Valid statuses are "public",
    // "private" and "unlisted".
    $status = new Google_Service_YouTube_VideoStatus();
    $status->privacyStatus = "public";

    // Associate the snippet and status objects with a new video resource.
    $video = new Google_Service_YouTube_Video();
    $video->setSnippet($snippet);
    $video->setStatus($status);

    // 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 videos.insert method to create and upload the video.
    $insertRequest = $youtube->videos->insert("status,snippet", $video);

    // Create a MediaFileUpload object for resumable uploads.
    $media = new Google_Http_MediaFileUpload(
        $client,
        $insertRequest,
        'video/*',
        null,
        true,
        $chunkSizeBytes
    );
    $media->setFileSize(filesize($videoPath));


    // Read the media file and upload it chunk by chunk.
    $status = false;
    $handle = fopen($videoPath, "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);


    $htmlBody .= "<h3>Video Uploaded</h3><ul>";
    $htmlBody .= sprintf('<li>%s (%s)</li>',
        $status['snippet']['title'],
        $status['id']);

    $htmlBody .= '</ul>';

  } catch (Google_Service_Exception $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>Video Uploaded</title>
</head>
<body>
  <?=$htmlBody?>
</body>
</html>

任何想法我错过了什么?

【问题讨论】:

  • 会不会像 youtube 频道设置的问题一样简单?可能是允许从服务帐户上传视频的设置?
  • @TMartin Possibly a setting to allow videos to be uploaded from a service account? - 我怎样才能从我的频道中允许它?
  • 我做了一些研究,但不确定您的尝试是否可行。你在其他地方看到过成功吗?看到这个:developers.google.com/youtube/v3/guides/…
  • 是的,我在多年前和另一个开发者一起用 python 开发了一个 web 应用程序。该网络应用允许用户上传到所有者频道。
  • 您仍然可以访问该应用程序的源代码吗?查看工作版本可能会帮助您绕过您遇到的任何限制问题。我没有大量使用 youtube API 的经验,所以我的知识仅限于我到目前为止告诉你的内容。祝你好运!

标签: php api youtube google-api youtube-api


【解决方案1】:

我知道这听起来很奇怪,但前几天我也遇到了同样的问题。我在尝试不同的东西...尝试更改 YouTube 类别 ID...

尝试将其更改为 1,我花了数小时排除故障,最终发现很多类别在 YouTube PHP SDK 中不起作用。

如果可行,可能需要对 YouTube 进行 API 调用并获取所有类别 ID 的列表,然后逐个尝试它们,直到找到可行的方法...有关如何执行此操作的文档在这里: https://developers.google.com/youtube/v3/docs/videoCategories/list

这是假设您拥有正确的所有 OAuth 令牌。

【讨论】:

  • 如何正确获取我的 OAuth 令牌?每次我尝试从网络浏览器上传时,它都会要求我进行身份验证!
  • 当您使用 OAuth 进行身份验证时,它应该发回您的初始令牌和刷新令牌。每次 OAuth 令牌过期并访问 Google Auth 服务器以获取新的 OAuth 令牌时,您都需要使用刷新令牌。查看此处链接的 OAuth 文档:link
  • 问题是我不希望用户在他们想从我的网站/webapp 上传时进行身份验证。我只想在不知道这个该死的 OAuth 的情况下无缝上传。
  • 您需要使用 OAuth 进行身份验证,然后保存刷新令牌。当用户上传视频时,使用刷新令牌进行身份验证。
  • 一个问题 - 我如何获得刷新令牌?
【解决方案2】:

我想我从这个article找到了答案。

步骤:

第 1 步。 创建一个 token.php(确保将其设置为 777)。将来自 Google 的代码示例 - https://developers.google.com/youtube/v3/code_samples/php#upload_a_video - 稍作修改如下:

变化:

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

收件人:

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

  // @ref: http://www.whitewareweb.com/php-youtube-video-upload-google-api-oauth-2-0-v3/
  echo "Access Token: " . $_SESSION['token'];
}

第 2 步。 在浏览器上运行 token.php。授予访问权限。然后你会得到下面的 json 输出:

{
  "access_token": "xxxxt7YvjObwYx3DG4NRmfjiQ",
  "token_type": "Bearer",
  "expires_in": 3600,
  "refresh_token": "xxxxq5hzQTUapZ7zyRIHP7X_G8",
  "created": 1466238624
}

另存为 token.txt

第 3 步。 使用来自 Google 的相同示例代码创建 upload.php - 进行以下修改:

一个。 在您的upload.php 开头包含token.txt 文件:

$key = file_get_contents('token.txt');

然后将$key 传递给new Google_Client()

$OAUTH2_CLIENT_ID = 'xxxx.googleusercontent.com';
$OAUTH2_CLIENT_SECRET = 'xxxx';

// Client init
$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->setAccessToken($key);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);

二。将这段代码添加到try catch部分之前 $youtube = new Google_Service_YouTube($client);:

    /**
     * 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()) {
        $newToken = json_decode($client->getAccessToken());
        $client->refreshToken($newToken->refresh_token);
        file_put_contents('token.txt', $client->getAccessToken());
    }

第 4 步。运行upload.php就可以了。

您可以从那篇文章中获取整个代码。

【讨论】:

    猜你喜欢
    • 2017-07-05
    • 2014-11-22
    • 2012-01-08
    • 1970-01-01
    • 1970-01-01
    • 2013-07-02
    • 2013-02-03
    • 1970-01-01
    • 2014-12-01
    相关资源
    最近更新 更多