我想用PHP和YouTube Data Api v3上传视频文件。 PHP文件应
- 自动登录YouTube数据API
- 上传视频文件
使用户不必手动登录。
目标是允许用户无需先登录Google即可通过应用或网站将视频上传到YouTube。
这是我正在使用的代码:
<?php
if (!file_exists(__DIR__ . '/youtubeapi/vendor/autoload.php')) {
throw new Exception(sprintf('Please run "composer require google/apiclient:~2.0" in "%s"',__DIR__));
}
require_once __DIR__ . '/youtubeapi/vendor/autoload.php';
putenv('GOOGLE_APPLICATION_CREDENTIALS=service_credentials.json');
$client = new Google_Client();
$client->setScopes([
'https://www.googleapis.com/auth/youtube','https://www.googleapis.com/auth/youtube.force-ssl','https://www.googleapis.com/auth/youtube.upload','https://www.googleapis.com/auth/youtubepartner-channel-audit','https://www.googleapis.com/auth/youtubepartner'
]);
$client->useApplicationDefaultCredentials();
// Define service object for making API requests.
$service = new Google_Service_YouTube($client);
// Define the $video object,which will be uploaded as the request body.
$video = new Google_Service_YouTube_Video($client);
// Add 'snippet' object to the $video object.
$videosnippet = new Google_Service_YouTube_Videosnippet($client);
$videosnippet->setCategoryId('22');
$videosnippet->setDescription('Description of uploaded video.');
$videosnippet->setTitle('Test video upload.');
$video->setsnippet($videosnippet);
// Add 'status' object to the $video object.
$videoStatus = new Google_Service_YouTube_VideoStatus($client);
$videoStatus->setPrivacyStatus('private');
$video->setStatus($videoStatus);
// TODO: For this request to work,you must replace "YOUR_FILE"
// with a pointer to the actual file you are uploading.
// The maximum file size for this operation is 128GB.
$response = $service->videos->insert(
'snippet,status',$video,array(
'data' => file_get_contents("big_buck_bunny.mp4"),'mimeType' => 'video/*','uploadType' => 'multipart'
)
);
print_r($response);
?>
这是我得到的错误:
> Fatal error: Uncaught Google_Service_Exception: { "error": { "errors":
> [ { "domain": "youtube.header","reason": "youtubeSignupRequired",> "message": "Unauthorized","locationType": "header","location":
> "Authorization" } ],"code": 401,"message": "Unauthorized" } } in
> /homepages/37/d797893845/htdocs/development/sitesmedia/youtube/youtubeapi/src/Google/Http/REST.php:118
> Stack trace: #0
> /homepages/37/d797893845/htdocs/development/sitesmedia/youtube/youtubeapi/src/Google/Http/REST.php(94):
> Google_Http_REST::decodeHttpResponse(Object(GuzzleHttp\Psr7\Response),> Object(GuzzleHttp\Psr7\Request),'Google_Service_...') #1
> /homepages/37/d797893845/htdocs/development/sitesmedia/youtube/youtubeapi/src/Google/Task/Runner.php(176):
> Google_Http_REST::doExecute(Object(GuzzleHttp\Client),'Google_Service_...') #2
> /homepages/37/d797893845/htdocs/development/sitesmedia/youtube/youtubeapi/src/Google/Http/REST.php(58):
> Google_Task_Runner->run() #3 /homepages/37/d797893845/ in
> /homepages/37/d797893845/htdocs/development/sitesmedia/youtube/youtubeapi/src/Google/Http/REST.php
> on line 118