UserがWeb上から動画をアップロードさせる仕組みを作りたいです。
https://developers.google.com/youtube/v3/code_samples/php?hl=ja#resumable_uploads
公式のサンプルコードだとOAuth認証しないと、アップロードできません。Userがgoogleアカウントを持っていなくてもアップロードできるように認証を挟まずにアップロードさせたいのです。
可能なのでしょうか?
GoogleDevelopperConsole->OAuth->サービスアカウント からサービスアカウント取って、試してみましたが、
An client error occurred: Failed to start the resumable upload (HTTP 401: youtube.header, Unauthorized)
と返ってきます。考えられる原因は何でしょうか?
(一応、コード載せますm(_ _)m)Cakephpでの記述です。
public function resumable_upload(){
App::import('Vendor', 'google-api-php-client-master/src/Google/Client');
App::import('Vendor', 'google-api-php-client-master/src/Google/Service/YouTube');
$htmlBody ='';
// サービスアカウント名(メールアドレス) $service_account_name ='service_accont_name'; // P12キーファイルのパス $key_file_location = 'path/to/key'; session_start(); if ( !strlen($service_account_name) || !strlen($key_file_location)) { echo missingServiceAccountDetailsWarning(); } $client = new Google_Client(); $client->setScopes('https://www.googleapis.com/auth/youtube'); //tokenをセット if (isset($_SESSION['service_token'])) { $client->setAccessToken($_SESSION['service_token']); } //Credentials(証明書)用の設定 $key = file_get_contents($key_file_location); $cred = new Google_Auth_AssertionCredentials( $service_account_name, array('https://www.googleapis.com/auth/youtube.upload'),//$scope $key ); $client->setAssertionCredentials($cred); //トークンのリフレッシュ if($client->getAuth()->isAccessTokenExpired()) { $client->getAuth()->refreshTokenWithAssertion($cred); } $_SESSION['service_token'] = $client->getAccessToken(); //apiを操作用?インスタンスを生成 $youtube = new Google_Service_YouTube($client); if (isset($_SESSION['token'])) { $client->setAccessToken($_SESSION['token']); }
);
// Check to ensure that the access token was successfully acquired. if ($client->getAccessToken()) { echo 'getAccessToken true <br>'; try{ // REPLACE this value with the path to the file you are uploading. $videoPath = 'videopath'; // Create a snippet with title, description, tags and category ID // Create an asset resource and set its snippet metadata and type. // This example sets the video's title, description, keyword tags, and // video category. $snippet = new Google_Service_YouTube_VideoSnippet(); $snippet->setTitle("Test title"); $snippet->setDescription("Test description"); $snippet->setTags(array("tag1", "tag2")); // Numeric video category. See // https://developers.google.com/youtube/v3/docs/videoCategories/list $snippet->setCategoryId("22"); // Set the video's status to "public". Valid statuses are "public", // "private" and "unlisted". $status = new Google_Service_YouTube_VideoStatus(); $status->privacyStatus = "public"; // Associate the snippet and status objects with a new video resource. $video = new Google_Service_YouTube_Video(); $video->setSnippet($snippet); $video->setStatus($status); // Specify the size of each chunk of data, in bytes. Set a higher value for // reliable connection as fewer chunks lead to faster uploads. Set a lower // value for better recovery on less reliable connections. $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"); debug($handle); while (!$status && !feof($handle)) { $chunk = fread($handle, $chunkSizeBytes); $status = $media->nextChunk($chunk); } fclose($handle); // If you want to make other calls after the file upload, set setDefer back to false $client->setDefer(false); //text 成形 $htmlBody .= "<h3>Video Uploaded</h3><ul>"; $htmlBody .= sprintf('<li>%s (%s)</li>', $status['snippet']['title'], $status['id']); } catch (Google_ServiceException $e) { $htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage())); } catch (Google_Exception $e) { $htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage())); echo $htmlBody; ・・・☆ここで401エラーが吐かれます↓
An client error occurred: Failed to start the resumable upload (HTTP 401: youtube.header, Unauthorized)
}
$_SESSION['token'] = $client->getAccessToken(); } else { // If the user hasn't authorized the app, initiate the OAuth flow $state = mt_rand(); $client->setState($state); $_SESSION['state'] = $state; $authUrl = $client->createAuthUrl(); } $this->autoRender = false; }

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2015/02/03 07:10
2015/02/03 07:22