2014-02-12 62 views
4

我試圖用API v3直接上傳視頻到Youtube。PHP Youtube API v3 - 直接上傳 - 未經授權的信息

我使用服務帳戶方案(https://developers.google.com/accounts/docs/OAuth2?hl=es&csw=1#scenarios),我解決了谷歌的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 = '[email protected]'; 
$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-urlencoded\r\n", 
     '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 
} 

無 「創造」, 「refresh_token」 和 「id_token」 領域。所以我修復了setAccessToken方法Google_OAuth2類如果未設置,則將「created」字段設置爲time()。否則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" 
} 

我發現的例子。

我該怎麼做才能最終上傳視頻文件?關於這種情況的任何例子?

在此先感謝。

+0

我獨立地到了你所在的位置,必須添加相同的標記字段以避免即時令牌過期,並且與實際上傳具有相同的確切問題(未經授權)。你是否設法最終解決這個問題?如果是這樣如何? – Claud

回答

3

它可能看起來微不足道,但是您是否在要上傳視頻的帳戶中創建了至少一個頻道。我使用了幾乎與acceess_token相同的解決方法,然後遇到同樣的問題,直到我進入我的Youtube帳戶上傳部分,並在上傳視頻之前看到該消息創建至少一個頻道。希望能幫助到你。

2

你得到的錯誤響應是設計。 Google不允許通過服務帳戶訪問Youtube API。

https://developers.google.com/youtube/v3/guides/moving_to_oauth#service-accounts-do-not-work-with-the-youtube-api

服務帳戶沒有爲YouTube數據API的工作電話因爲 服務帳戶要求相關的YouTube頻道,您可以用服務帳戶不 聯想新的或現有的渠道。 如果使用 服務帳戶調用YouTube數據API,該API服務器返回 設置爲未經授權錯誤類型和原因設置爲 錯誤youtubeSignupRequired