无法通过Google PHP API在特定的YouTube帐户上传视频

时间:2015-10-01 13:04:36

标签: php api youtube youtube-api youtube-data-api

我们正尝试使用PHP YouTube API在YouTube频道上传视频。视频已在所有YouTube帐户和频道上成功上传,但一个帐户https://www.youtube.com/user/OLXInTv/除外。

在搜索时,我们发现很少提及服务帐户的链接不适用于YouTube API。 https://developers.google.com/youtube/v3/guides/moving_to_oauth#service-accounts-do-not-work-with-the-youtube-api

请帮忙。

我们用于YouTube视频上传的代码是

<?php
session_start();
require_once '../../pdo/olxdb.php';
date_default_timezone_set("Asia/Kolkata");
$videoData = $invokeThis->selectOlxUtubeModeratedVideo();

require_once '../api/src/Google/autoload.php';
require_once '../api/src/Google/Client.php';
require_once '../api/src/Google/Service/YouTube.php';
$fileR = 'logs/youtubelog.txt';
$application_name = 'ABC'; 
$client_secret = 'ABC';
$client_id = 'ABC';
$scope = array('https://www.googleapis.com/auth/youtube.upload', 'https://www.googleapis.com/auth/youtube', 'https://www.googleapis.com/auth/youtubepartner');

foreach ($videoData as $video) { 
    try{ 
        $key = file_get_contents('the_key.txt');
        $videoPath = '../../converted/final/ready/madeit/'.$video['video'];
        $videoTitle = 'Buy '.$video['color'].' '.$video['category'].' at Rs.'.$video['price'];
        $videoDescription = 'Hi, I am willing to sell my '.$video["color"].' '.$video["category"].' at INR.'.$video["price"].'. If interested, kindly visit http://makeyourad.olx.in/ and go to video gallery to look for my product using my name '.$video["name"].'. Look to hear from you…';
        $videoCategory = "22";
        $videoTags = array($video['id'],$video['color'], $video['category'], $video['price'], 'Buy', 'Sell');
        $videoid = $video['id'];  

        // 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 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('the_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('private');

            // 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, now lets perform some cleanup functions for this video
             */
            if ($status->status['uploadStatus'] == 'uploaded') {
                $youtube_id = $status->id;
                $invokeThis->updateOlxYoutubeVideo($videoid,$youtube_id);
            }

            // If you 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) {
        $invokeThis->updateOlxYoutubeVideoRead($videoid);
        $line1 = "\r\n Caught Google service Exception ".$e->getCode(). " message is ".$e->getMessage();
        $line2 = "\r\n Stack trace is ".$e->getTraceAsString();
        $dateStart = date("Y:m:d h:i:s");
        $fileContents = "\r\n ".$dateStart.' Video Id:='.$videoid.$line1.$line2;
        file_put_contents($fileR, $fileContents, FILE_APPEND);
    } catch (Exception $e) {
        $invokeThis->updateOlxYoutubeVideoRead($videoid);
        $line1 =  "\r\n Caught Google service Exception ".$e->getCode(). " message is ".$e->getMessage();
        $line2 =  "\r\n Stack trace is ".$e->getTraceAsString(); 
        $dateStart = date("Y:m:d h:i:s");
        $fileContents = "\r\n ".$dateStart.' Video Id:='.$videoid.$line1.$line2;
        file_put_contents($fileR, $fileContents, FILE_APPEND);
    }

}

?>

1 个答案:

答案 0 :(得分:0)

最后,我们找到了解决方案。没有必要更改代码。 切换频道后应生成访问令牌,如下所述。

  1. 登录YouTube帐户并切换到您希望上传视频的频道。
  2. 现在是时候登录并通过api生成访问令牌。
  3. 此处还会要求您指定频道。
  4. 指定频道后,您将获得访问令牌。
  5. 那就是它。

    在我们的案例中,由于订单未在指南的任何地方指定,因此我们遵循了错误的订单。

    希望这也能帮助别人。

    Google支持提供了此参考链接http://youtube-eng.blogspot.in/2013/06/google-page-identities-and-youtube-api_24.html

    感谢Google

相关问题