PHP Youtube API v3-直接上传-未经授权的消息



我正在尝试使用API v3将视频直接上传到Youtube。

我正在使用服务帐户场景(https://developers.google.com/accounts/docs/OAuth2?hl=es&csw=1#场景),并且我解决了google api php客户端库中的一些问题(为了读取p12文件并避免isAccessTokenExpired总是返回false)。

<?php
/** Config */ 
$private_key_password = 'notasecret';
$private_key_file = 'xxxxxxxx-privatekey.p12';
$applicationName = 'xxxxx-youtube';
$client_secret = 'CLIENT_SECRET';
$client_id = 'xxxxxxxxxxxxx.apps.googleusercontent.com';
$service_mail = 'xxxxxxxxxxx@developer.gserviceaccount.com';
$public_key = 'xxxxxxxxxxx';
/** Constants */ 
$scope = 'https://www.googleapis.com/auth/youtube';
$url_youtube_token = 'https://accounts.google.com/o/oauth2/token';
/** Create and sign JWT */ 
$jwt = new Google_AssertionCredentials($service_mail, $scope, $private_key_file, $private_key_password, $url_youtube_token);
$jwt_assertion = $jwt->generateAssertion();
/** Use JWT to request token */
$data = array(
'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
'assertion' => $jwt_assertion,
);
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header'  => "Content-type: application/x-www-form-urlencodedrn",
'method'  => 'POST',
'content' => http_build_query($data),
),
);
$context = stream_context_create($options);
$result = file_get_contents($url_youtube_token, false, $context);

此时,我在json响应中得到了访问令牌,如下所示:

{
"access_token" : "1/8xbJqaOZXSUZbHLl5EOtu1pxz3fmmetKx9W8CV4t79M",
"token_type" : "Bearer",
"expires_in" : 3600
}

没有"created"、"refresh_token"one_answers"id_token"字段。因此,我修复了Google_OAuth2类中的setAccessToken方法,如果未设置,则将"已创建"字段设置为时间()。否则isAccessTokenExpired总是返回false。

现在,让我们上传文件。

try{
// Client init 
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setApplicationName($applicationName);
$client->setAccessToken($result);
if ($client->getAccessToken()) {
if($client->isAccessTokenExpired()) {
// @TODO Log error 
echo 'Access Token Expired!!<br/>'; // Debug
}
$youtube = new Google_YoutubeService($client);
$videoPath = "./test.mp4";
// Create a snipet with title, description, tags and category id
$snippet = new Google_VideoSnippet();
$snippet->setTitle("fmgonzalez test " . time());
$snippet->setDescription("fmgonzalez test " . time() );
$snippet->setTags(array("tag1", "tag2"));
// Numeric video category. See
// https://developers.google.com/youtube/v3/docs/videoCategories/list
$snippet->setCategoryId("22");
// Create a video status with privacy status. Options are "public", "private" and "unlisted".
$status = new Google_VideoStatus();
$status->privacyStatus = "public";
// Create a YouTube video with snippet and status
$video = new Google_Video();
$video->setSnippet($snippet);
$video->setStatus($status);
// Size of each chunk of data in bytes. Setting it higher leads faster upload (less chunks,
// for reliable connections). Setting it lower leads better recovery (fine-grained chunks)
$chunkSizeBytes = 1 * 1024 * 1024;
// Create a MediaFileUpload with resumable uploads
$media = new Google_MediaFileUpload('video/*', null, true, $chunkSizeBytes);
$media->setFileSize(filesize($videoPath));
// Create a video insert request
$insertResponse = $youtube->videos->insert("status,snippet", $video,
array('mediaUpload' => $media));
$uploadStatus = false;
// Read file and upload chunk by chunk
$handle = fopen($videoPath, "rb");
$cont = 1;
while (!$uploadStatus && !feof($handle)) {
$chunk = fread($handle, $chunkSizeBytes);
$uploadStatus = $media->nextChunk($insertResponse, $chunk);
echo 'Chunk ' . $cont . ' uploaded <br/>';
$cont++;
}
fclose($handle);
echo '<br/>OK<br/>';
}else{
// @TODO Log error 
echo 'Problems creating the client';
}
} catch(Google_ServiceException $e) {
print "Caught Google service Exception ".$e->getCode(). " message is ".$e->getMessage(). " <br>";
print "Stack trace is ".$e->getTraceAsString();
}catch (Exception $e) {
echo $e->getMessage();
}

但我收到"无法启动可恢复上传">消息。

调试,Google_MediaFileUpload中的方法getResumeUri我得到了这个响应体:

"error": {
"errors": [
{
"domain": "youtube.header",
"reason": "youtubeSignupRequired",
"message": "Unauthorized",
"locationType": "header",
"location": "Authorization"
}
],
"code": 401,
"message": "Unauthorized"
}

我找到了其他场景的例子,但没有找到这个。

我应该怎么做才能最终上传视频文件?有关于这种情况的例子吗?

提前谢谢。

这看起来可能很琐碎,但你是否在要上传视频的帐户中至少创建了一个频道。我在acceess_token中使用了与你几乎相同的解决方法,然后遇到了同样的问题,直到我进入Youtube帐户上传部分,看到在上传视频之前创建至少一个频道的消息。希望能有所帮助。

您得到的错误响应是经过设计的。谷歌不允许Youtube API通过服务帐户访问。

https://developers.google.com/youtube/v3/guides/moving_to_oauth#service-帐户无法使用youtube api

服务帐户不适用于YouTube数据API调用,因为服务帐户需要关联的YouTube频道,而您不能将新渠道或现有渠道与服务帐户关联如果您使用服务帐户调用YouTube数据API,API服务器返回错误类型设置为未经授权,原因设置为youtubeSignupRequired

最新更新