PHP API Youtube上传,例外:无法启动可恢复上传,必须将上传发送到上传URL

时间:2015-06-30 10:09:06

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

我正在尝试构建一个用于将视频上传到YouTube的服务器应用程序。在我的服务器应用程序中,用户可以将视频直接上传到我的YouTube频道,以便将其公开。

enter image description here

  1. 我的应用程序的客户端部分获取视频并将其上传到我的服务器。
  2. 我的服务器然后使用YouTube API将视频上传到我的YouTube频道。
  3. 为了完成这项工作,我创建了一个虚拟Web应用程序,它可以捕获生成的刷新令牌,并将其存储在key.txt文件中

    {"access_token":"MYTOKEN","token_type":"Bearer","expires_in":3600,"created":1435654774}
    

    如果upload_video.php已过期,"key.txt"脚本将自动更新access_token文件。这是upload_video.php的代码:

    $key = file_get_contents('key.txt');
    
    $application_name = 'YouTube_Upload'; 
    $client_secret    = 'MY_CLIENT_SECRET';
    $client_id        = 'MY_CLIENT_ID';
    $scope            = array('https://www.googleapis.com/auth/youtube.upload', 'https://www.googleapis.com/auth/youtube', 'https://www.googleapis.com/auth/youtubepartner');
    
    $videoPath        = "Test.f4v";
    $videoTitle       = "A tutorial video";
    $videoDescription = "A video tutorial on how to upload to YouTube";
    $videoCategory    = "22";
    $videoTags        = array("youtube", "tutorial");
    
    try{
        // Client init
        $client = new Google_Client();
        $client->setApplicationName($application_name);
        $client->setClientId($client_id);
        $client->setAccessType('offline');
        $client->setAccessToken($key);
        $client->setScopes($scope);
        $client->setClientSecret($client_secret);
    
        if ($client->getAccessToken()) {
    
            /**
             * Check to see if 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('key.txt', $client->getAccessToken());
            }
    
            $youtube = new Google_Service_YouTube($client);
    
            // Create a snipet with title, description, tags and category id
            $snippet = new Google_Service_YouTube_VideoSnippet();
            $snippet->setTitle($videoTitle);
            $snippet->setDescription($videoDescription);
            $snippet->setCategoryId($videoCategory);
            $snippet->setTags($videoTags);
    
            // Create a video status with privacy status. Options are "public", "private" and "unlisted".
            $status = new Google_Service_YouTube_VideoStatus();
            $status->setPrivacyStatus('unlisted');
    
            // 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;
    
            // 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);
    
            /**
             * Video has successfully been upload
             */
            if ($status->status['uploadStatus'] == 'uploaded') {
                // Actions to perform for a successful upload
                // ......
            }
    
            // If want to make other calls after the file upload, set setDefer back to false
            $client->setDefer(true);
    
        } else{
            // @TODO Log error
            echo 'Problems creating the client';
        }
    
    } catch(Google_Service_Exception $e) {
        print "Google_Service_Exception ".$e->getCode(). " message is ".$e->getMessage();
        print "Stack trace is ".$e->getTraceAsString();
    }catch (Exception $e) {
        print "Exception ".$e->getCode(). " message is ".$e->getMessage();
        print "Stack trace is ".$e->getTraceAsString();
    }
    

    当脚本运行时,会引发此异常:

    Exception 0 message is Failed to start the resume-able upload (HTTP 400: global, Uploads must be sent to the upload URL. Re-send this request to https://www.googleapis.com/upload/youtube/v3/videos?part=status,snippet&uploadType=resumable)Stack trace is 
    #0 D:\xampp\htdocs\youtube\src\Google\Http\MediaFileUpload.php(136): Google_Http_MediaFileUpload->getResumeUri()
    #1 D:\xampp\htdocs\youtube\resumable_upload.php(100): Google_Http_MediaFileUpload->nextChunk('\x00\x00\x00\x1Cftypf4v \x00\x00\x00...')
    #2 {main}
    
    getResumeUri()的{​​{1}}(第281行)

    异常加注,我有来自Google的var转储

    Google_Http_MediaFileUpload

    有什么问题? 感谢您的帮助,对不起的英语感到抱歉。

4 个答案:

答案 0 :(得分:4)

这似乎是Google API的PHP客户端库的一个问题。转到GOOGLE_LIB_PATH / Http / MediaFileUpload.php并替换此行:

$this->request->setBaseComponent($base . '/upload'); 

有了这个:

$this->request->setBaseComponent($base . 'upload'); 

再试一次并分享结果。我遇到了与Google Pubsub API类似的问题,其中库设置的API路径不正确。

答案 1 :(得分:1)

我希望你需要Resumable Uploads(https://developers.google.com/youtube/v3/guides/using_resumable_upload_protocol

然后使用this而不做任何修改。

同时检查https://support.google.com/youtube/troubleshooter/2888402?hl=en

是否支持视频格式

答案 2 :(得分:1)

有一种google方法来获取刷新令牌,因此不使用json_decode:

$newToken = json_decode($client->getAccessToken());
$client->refreshToken($newToken->refresh_token);

你可以这样做:

$client->refreshToken( $client->getRefreshToken() );

答案 3 :(得分:-1)

这是我到目前为止测试过的并且工作正常。

$key = trim(file_get_contents('key.txt'));
$scope = 'https://www.googleapis.com/auth/youtube';