YouTube API v3-直接上传到自己的频道



由于YouTube v2 API越来越不推荐使用,我需要迁移到v3。

在v2中,我使用了同样不推荐使用的ClientLogin(http://bit.ly/v2_ClientLogin_authentification)身份验证方法进行身份验证,然后将用户视频上传到我的YouTube频道。

使用v3,我尝试使用服务帐户进行身份验证,使用此处使用的相同代码库

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

我从API端点得到了相同的错误消息:

调用POST时出错https://www.googleapis.com/youtube/v3/videos?part=status%2Csnippet:(401)未经授权的

我也通过谷歌的tokeninfo进行了检查(https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=[ACCESS_TOKEN])确定访问令牌有效:

{
"issued_to": "***.apps.googleusercontent.com",
"audience": "***.apps.googleusercontent.com",
"scope": "https://www.googleapis.com/auth/youtube",
"expires_in": 3592,
"access_type": "offline"
}

我发现的所有YouTube示例都是基于OAuth2和用户授权的。(就像这里的这个:http://bit.ly/yt-api-example-videoupload)。但这不是我想要的方式:用户不应该看到任何"请授权whatever.de上传YouTube视频">视频应该上传到我的YT频道,而不是他们的。

如果不可能使用API服务帐户,请给我一个如何使用OAuth2的提示?:-)

这是我当前的代码:

/** Config */ 
$private_key_password = 'notasecret';
$private_key_file = '***.p12';
$applicationName = '***';
$client_secret = '***'; // <--- WHERE IS THAT CLIENT_SECRET COMING FROM? Secret accounts do not have a client secret? 
$client_id = '***.apps.googleusercontent.com';
$service_mail = '***@developer.gserviceaccount.com';
$scope = 'https://www.googleapis.com/auth/youtube';
$url_youtube_token = 'https://accounts.google.com/o/oauth2/token';
$jwt = new Google_Auth_AssertionCredentials($service_mail, $scope, $private_key_file, $private_key_password, $url_youtube_token);
$jwt_assertion = $jwt->generateAssertion();
$data = array
(
'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
'assertion' => $jwt_assertion,
);
$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);
//var_dump($result); die();
try{
// Client init
$client = new Google_Client();
$client->setClientId($client_id);
//$client->setClientSecret($client_secret); // <-- See above
$client->setApplicationName($applicationName);
$client->setAccessToken($result);
if ($client->getAccessToken()) 
{
if($client->isAccessTokenExpired()) 
{
// @TODO Log error
echo 'Access Token Expired!!<br/>'; // Debug
}
$youtube = new Google_Service_Youtube($client);
$videoPath = "./test.mp4";
// Create a snipet with title, description, tags and category id
$snippet = new Google_Service_YouTube_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_Service_YouTube_VideoStatus();
$status->privacyStatus = "public";
// Create a YouTube video with snippet and status
$video = new Google_Service_YouTube_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
$insertRequest = $youtube->videos->insert("status,snippet", $video);
$media = new Google_Http_MediaFileUpload
(
$client,
$insertRequest,
'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_Service_Exception $e)
{
print "Caught Google service Exception ".$e->getCode(). " message is <br>".$e->getMessage(). " <br>";
//print "Stack trace is ".$e->getTraceAsString();
}
catch (Exception $e)
{
echo $e->getMessage();
}
?>

使用服务帐户无法访问YouTube API

问题5370:Youtube v3谷歌服务帐户访问

您将需要使用Oauth2。您只需要进行一次身份验证。使用脱机访问保存刷新令牌。然后您可以使用它来运行您的脚本。

$client->setAccessType('offline');   // Gets us our refreshtoken

最新更新