Youtube – Upload videos with partner API in PHP

Librairy et Access

Downloads and documentation

Get the Client Id et Client secret

  1. Go on https://code.google.com/apis/console/
  2. In the tab APIs &auth
  3. Click on Credentials
    • get Client Id
    • get Client secret

Authorization

Make sure the account is authorized on the CMS https://cms.youtube.com/edit_cms_accounts

 Data Sample

$videoTitle = "video title";
$videoText = "video text";
$videoKeywords = array("tag1", "tag2", "tag3");
$contentOwnerId = XXXXXXXX;
$channelCode = XXXXXXXX;
$videoPath = "/pathtovideo/video.ext";

OAuth2

 

Upload a video

Create a snippet with title, description, tags and category ID

// Create a snippet with title, description, tags and category ID
 $snippet = new Google_Service_YouTube_VideoSnippet();
 $snippet->setTitle($videoTitle);
 $snippet->setDescription($videoText);
 $snippet->setTags($videoKeywords);
 
 // 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 = $videoPrivacy;
 
 // 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.
 $this->_client->setDefer(true);
 
 // Create a request for the API's videos.insert method to create and upload the video.
 $insertRequest = $this->_youtube->videos->insert("status,snippet", $video,
 array('onBehalfOfContentOwner' => $contentOwnerId,
 'onBehalfOfContentOwnerChannel' => $channelCode));
 
 // Create a MediaFileUpload object for resumable uploads.
 $media = new Google_Http_MediaFileUpload($this->_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");
 $totalUploaded = 0;
 Factory_System_Message::msg('start uploading file, waiting...');
 while (!$status && !feof($handle)) {
 $chunk = fread($handle, $chunkSizeBytes);
 $status = $media->nextChunk($chunk);
 // Size
 $totalUploaded += $chunkSizeBytes;
 }
 fclose($handle);
 Factory_System_Message::msg("uploaded ".($totalUploaded/1024)." KB");
 
 // Set defer back to false to be able to make other calls after the file upload.
 $this->_client->setDefer(false);
 
 $videoId = $status['id'];

Create an asset resource and set its metadata and type:

 // Create an asset resource and set its metadata and type. Assets support
 // many metadata fields, but this sample only sets a title and description.
 Factory_System_Message::msg("create youtube partner asset");
 $asset = new Google_Service_YouTubePartner_Asset();
 $metadata = new Google_Service_YouTubePartner_Metadata();
 $metadata->setTitle($this->getYoutubeTitle());
 $metadata->setDescription($this->getYoutubeText());
 $asset->setMetadata($metadata);
 $asset->setType("web");
 
 // Insert the asset resource. Extract its unique asset ID from the API
 // response.
 $assetInsertResponse = $this->_youtubePartner->assets->insert($asset,
 array('onBehalfOfContentOwner' => $contentOwnerId));
 $assetId = $assetInsertResponse['id'];
 
 // Create a territory owner with owner, ratio, type and territories
 // Set the asset's ownership data. This example identifies the content
 // owner associated with the authenticated user's account as the asset's
 // owner. It indicates that the content owner owns 100% of the asset
 // worldwide.
 $owners = new Google_Service_YouTubePartner_TerritoryOwners();
 $owners->setOwner($contentOwnerId);
 $owners->setRatio(100);
 $owners->setType("exclude");
 $owners->setTerritories(array());
 
 // Create ownership with a territory owner
 $ownership = new Google_Service_YouTubePartner_RightsOwnership();
 $ownership->setGeneral(array($owners));
 
 // Update the asset's ownership with the rights data defined above.
 $ownershipUpdateResponse = $this->_youtubePartner->ownership->update($assetId, $ownership,
 array('onBehalfOfContentOwner' => $contentOwnerId));
 
 // Define a monetization policy for the asset.
 Factory_System_Message::msg('define youtube policy');
 $policy = new Google_Service_YouTubePartner_Policy();
 $policyRule = new Google_Service_YouTubePartner_PolicyRule();
 $policyRule->setAction("monetize");
 $policy->setRules(array($policyRule));

Define a monetization policy for the asset:

// Create a claim resource. Identify the video being claimed, the asset
 // that represents the claimed content, the type of content being claimed,
 // and the policy that you want to apply to the claimed video.
 $claim = new Google_Service_YouTubePartner_Claim();
 $claim->setAssetId($assetId);
 $claim->setVideoId($videoId);
 $claim->setPolicy($policy);
 $claim->setContentType("audiovisual");
 
 // Insert the created claim.
 $claimInsertResponse = $this->_youtubePartner->claims->insert($claim,
 array('onBehalfOfContentOwner' => $contentOwnerId));
 
 # Enable ads for the video. This example enables the TrueView ad format.
 $option = new Google_Service_YouTubePartner_VideoAdvertisingOption();
 //$option->setAdFormats(array("overlay", "trueview_instream", "standard_instream"));
 $option->setAdFormats(array("trueview_instream", "standard_instream"));
 $setAdvertisingResponse = $this->_youtubePartner->videoAdvertisingOptions->update(
 $videoId, $option, array('onBehalfOfContentOwner' => $contentOwnerId));

Raphaël has written 45 articles

3 thoughts on “Youtube – Upload videos with partner API in PHP

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>