Youtube video upload API issue - php

I just can't seem to get this API working. My eyes are missing the mistakes I'm making. The problem I have is that the page still Shows BLANK.
I need the form to upload the data onto Youtube which will later be displayed on my website.
Here is my code:
<?php
require_once 'library/Zend/Loader/AutoloaderFactory.php'; // the Zend dir must be in your include_path
Zend_Loader::loadClass('Zend_Gdata_YouTube');
$yt = new Zend_Gdata_YouTube();
Zend_Loader::loadClass('Zend_Gdata_AuthSub');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
// start a new session
session_start();
function getAuthSubRequestUrl()
{
$next = 'http://www.example.com/welcome.php';
$scope = 'http://gdata.youtube.com';
$secure = false;
$session = true;
return Zend_Gdata_AuthSub::getAuthSubTokenUri($next, $scope, $secure, $session);
}
function getAuthSubHttpClient()
{
if (!isset($_SESSION['sessionToken']) && !isset($_GET['token']) ){
echo 'Login!';
return;
} else if (!isset($_SESSION['sessionToken']) && isset($_GET['token'])) {
$_SESSION['sessionToken'] = Zend_Gdata_AuthSub::getAuthSubSessionToken($_GET['token']);
}
$httpClient = Zend_Gdata_AuthSub::getHttpClient($_SESSION['sessionToken']);
return $httpClient;
}
$yt = new Zend_Gdata_YouTube($httpClient, $applicationId, $clientId, $developerKey);
$authenticationURL= 'https://www.google.com/accounts/ClientLogin';
$httpClient =
Zend_Gdata_ClientLogin::getHttpClient(
$username = 'myuser#gmail.com',
$password = 'mypassword',
$service = 'youtube',
$client = null,
$source = 'MySource', // a short string identifying your application
$loginToken = null,
$loginCaptcha = null,
$authenticationURL);
$developerKey = 'ABC123 ... ';
$applicationId = 'Video uploader v1';
$clientId = 'My video upload client - v1';
$yt = new Zend_Gdata_YouTube($httpClient, $applicationId, $clientId, $developerKey);
// Assuming that $yt is a valid Zend_Gdata_YouTube object
$yt->setMajorProtocolVersion(2);
function getAndPrintVideoFeed($location = Zend_Gdata_YouTube::VIDEO_URI)
{
$yt = new Zend_Gdata_YouTube();
// set the version to 2 to receive a version 2 feed of entries
$yt->setMajorProtocolVersion(2);
$videoFeed = $yt->getVideoFeed($location);
printVideoFeed($videoFeed);
}
function printVideoFeed($videoFeed)
{
$count = 1;
foreach ($videoFeed as $videoEntry) {
echo "Entry # " . $count . "\n";
printVideoEntry($videoEntry);
echo "\n";
$count++;
}
}
// Note that this example creates an unversioned service object.
// You do not need to specify a version number to upload content
// since the upload behavior is the same for all API versions.
$yt = new Zend_Gdata_YouTube($httpClient);
// create a new VideoEntry object
$myVideoEntry = new Zend_Gdata_YouTube_VideoEntry();
$myVideoEntry->setVideoTitle('My Test Movie');
$myVideoEntry->setVideoDescription('My Test Movie');
// The category must be a valid YouTube category!
$myVideoEntry->setVideoCategory('Autos');
// Set keywords. Please note that this must be a comma-separated string
// and that individual keywords cannot contain whitespace
$myVideoEntry->SetVideoTags('cars, funny');
$tokenHandlerUrl = 'http://gdata.youtube.com/action/GetUploadToken';
$tokenArray = $yt->getFormUploadToken($myVideoEntry, $tokenHandlerUrl);
$tokenValue = $tokenArray['token'];
$postUrl = $tokenArray['url'];
// place to redirect user after upload
$nextUrl = 'http://www.example.com/youtube_uploads';
// build the form
$form = '<form action="'. $postUrl .'?nexturl='. $nextUrl .
'" method="post" enctype="multipart/form-data">'.
'<input name="file" type="file"/>'.
'<input name="token" type="hidden" value="'. $tokenValue .'"/>'.
'<input value="Upload Video File" type="submit" />'.
'</form>';
echo "aaaa".$form;
?>

Here is my code with Zend
//include Zend Gdata Libs
require_once("Zend/Gdata/ClientLogin.php");
require_once("Zend/Gdata/HttpClient.php");
require_once("Zend/Gdata/YouTube.php");
require_once("Zend/Gdata/App/HttpException.php");
require_once('Zend/Uri/Http.php');
//yt account info
$yt_user = 'myuser#gmail.com'; //youtube username or gmail account
$yt_pw = 'mypassword'; //account password
$yt_source = 'title of my video'; //name of application (can be anything)
//yt dev key get here : https://code.google.com/apis/youtube/dashboard/
$yt_api_key = ''ABC123 ... ''; //your youtube developer key
//login in to YT
$authenticationURL= 'https://www.google.com/youtube/accounts/ClientLogin';
$httpClient = Zend_Gdata_ClientLogin::getHttpClient(
$username = $yt_user,
$password = $yt_pw,
$service = 'youtube',
$client = null,
$source = $yt_source, // a short string identifying your application
$loginToken = null,
$loginCaptcha = null,
$authenticationURL);
// Note that this example creates an unversioned service object.
// You do not need to specify a version number to upload content
// since the upload behavior is the same for all API versions.
//$yt = new Zend_Gdata_YouTube($httpClient);
$yt = new Zend_Gdata_YouTube($httpClient, $yt_source, NULL, $yt_api_key);
I can Upload my file and after a while I'm redirected to "$nextUrl".
My issue is that I get this page : http://www.example.com/youtube_uploads?statu=400&error=failed
And I don't no why.
Any Idea, please ?

Related

How to integrate Google Plus OAuth API with Codeigniter?

I'm trying to build a simple project in which the google plus profile data will be saved or will get updated into the database. I'm unable to figure the way out of invalid character URI problem. I'm getting invalid character URI as response from google.
How can I solve this problem of invalid URI?
I have attached the image of the error at the end of this post.
Login Controller class code is:
public function index() {
// Include the google api php libraries
include_once APPPATH."libraries/google-api-php-client/Google_Client.php";
include_once APPPATH."libraries/google-api-php-client/contrib/Google_Oauth2Service.php";
// Google Project API Credentials
$clientId = 'My Client ID';
$clientSecret = 'My Secret here';
$redirectUrl = 'https://example.com/index.php?login/index/';
// Google Client Configuration
$gClient = new Google_Client();
$gClient->setApplicationName('Login to Application');
$gClient->setClientId($clientId);
$gClient->setClientSecret($clientSecret);
$gClient->setRedirectUri($redirectUrl);
$google_oauthV2 = new Google_Oauth2Service($gClient);
if (isset($_REQUEST['code'])) {
$gClient->authenticate();
$this->session->set_userdata('token', $gClient->getAccessToken());
redirect($redirectUrl);
}
$token = $this->session->userdata('token');
if (!empty($token)) {
$gClient->setAccessToken($token);
}
if ($gClient->getAccessToken()) {
$userProfile = $google_oauthV2->userinfo->get();
// Preparing data for database insertion
$userData['oauth_provider'] = 'google';
$userData['oauth_uid'] = $userProfile['id'];
$userData['first_name'] = $userProfile['given_name'];
$userData['last_name'] = $userProfile['family_name'];
$userData['email'] = $userProfile['email'];
$userData['gender'] = $userProfile['gender'];
$userData['locale'] = $userProfile['locale'];
$userData['profile_url'] = $userProfile['link'];
$userData['picture_url'] = $userProfile['picture'];
// Insert or update user data
$userID = $this->user->checkUser($userData);
if(!empty($userID)){
$data['userData'] = $userData;
$this->session->set_userdata('userData',$userData);
} else {
$data['userData'] = array();
}
} else {
$data['authUrl'] = $gClient->createAuthUrl();
}
$this->load->view('backend/login',$data);
}
The image of the error :
I am unable to tackle the problem. Please suggest me how can I avoid this.

Authentication error with Youtube upload API

I'm doing an application that uploads videos from a web form into my youtube account. I want to use the server authentication.
I have configured my app in the Google Cloud Console and I have downloaded the private key into my server.
This is the code:
const SERVICE_ACCOUNT_EMAIL = 'MY_ACCOUNT_EMAIL';
const CLIENT_ID = 'MY_CLIENT_ID';
const KEY_FILE = './MY_PRIVATE_KEY.p12';
if ( !isset($_FILES['video']) ) {
echo '<form method="post" enctype="multipart/form-data">';
echo '<input type="file" name="video">';
echo '<input type="submit" value="Submit">';
echo '</form>';
}
else {
require_once 'Google/Client.php';
require_once 'Google/Service/YouTube.php';
$client = new Google_Client();
$client->setApplicationName('My Application Name');
$client->setClientId(CLIENT_ID);
$oauthClient = new Google_Auth_OAuth2($client);
// Set your cached access token. Remember to replace $_SESSION with a
// real database or memcached.
session_start();
if (isset($_SESSION['token'])) {
$oauthClient->setAccessToken($_SESSION['token']);
} else {
$key = file_get_contents(KEY_FILE);
$oauthClient->refreshTokenWithAssertion(new Google_Auth_AssertionCredentials(SERVICE_ACCOUNT_EMAIL, array('https://www.googleapis.com/auth/youtube'), $key));
}
if ($oauthClient->getAccessToken()) {
echo '<p>Uploading ...</p>';
$youtube = new Google_Service_YouTube($client);
$videoPath = $_FILES['video']['tmp_name'];
// Create a snippet with title, description, tags and category ID
$snippet = new Google_Service_YouTube_VideoSnippet();
$snippet->setTitle("Test video ".date('H:i'));
$snippet->setDescription("Test description ".date('H:i'));
$snippet->setTags(array("test", "oauth"));
// Set the video's status to "public".
$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);
// Create a request for the API's videos.insert method to create and upload the video.
$insertRequest = $youtube->videos->insert("status,snippet", $video, array("data"=>file_get_contents($videoPath), "uploadType" => "media", "mimeType" => "video/mp4"));
echo '<h3>Upload complete</h3>';
echo '<p>Link to the video</p>';
}
else {
$authUrl = $client->createAuthUrl();
print "<a href='$authUrl'>Authorize this application</a>";
}
}
It doesn't work. I have a Fatal Error:
Error calling POST https://www.googleapis.com/upload/youtube/v3/videos?part=status%2Csnippet&uploadType=multipart: (401) Login Required
What am I doing wrong?
You shouldn't use that OAuth2 class, just call the setAssertionCredentials method of the Google_Client passing a Google_Auth_AssertionCredentials instance.
Take a look at this example (it's using the old PHP lib version, but the authentication process is the same).

Set authenticated user's about me/description/summary

I am using the "youtube api" for PHP library, ie zend.
My goal is to set the description, ie what you see when you open the channel of a user in the textbox at the right.
What I did.
function anmelden_yt($name,$passwort)
{
$yt_source = 'sou'; //name of application (can be anything)
$yt_api_key = 'ak';
$yt = null;
$authenticationURL= 'https://www.google.com/youtube/accounts/ClientLogin';
$httpClient = Zend_Gdata_ClientLogin::getHttpClient(
$username = $name,
$password = $passwort,
$service = 'youtube',
$client = null,
$source = $yt_source, // a short string identifying your application
$loginToken = null,
$loginCaptcha = null,
$authenticationURL);
return new Zend_Gdata_YouTube($httpClient, $yt_source, NULL, $yt_api_key);
}
$yt = anmelden_yt('name','pw');
$yt->setMajorProtocolVersion(2);
$userProfileEntry = $yt->getUserProfile('name');
$userProfileEntry->setAboutMe('test');
$userProfileEntry->setContent('test');
$userProfileEntry->setSummary('test');
Nothing changed.
Those fields are no longer exposed via the API. They also don't correspond to the channel description display that you're referring to. There currently isn't a way to set that channel description via the API.

CodeIgniter: Upload Video to YouTube

I'm using CodeIgniter + Zend libraries. I want to let users upload videos to my site, which I will then upload to my YouTube channel. This is my first exposure to the YouTube API. Can someone point me in the right direction?
Am I right to be looking at this: http://code.google.com/apis/youtube/2.0/developers_guide_protocol.html#Direct_uploading? Does anyone have a snippet of code that shows how uploading is done via PHP?
Try this its working
class Addvideo extends Controller {
function Addvideo()
{
parent::Controller();
$this->load->library("zend");
$this->zend->load("Zend/Gdata/AuthSub");
$this->zend->load("Zend/Gdata/ClientLogin");
$authenticationURL= 'https://www.google.com/youtube/accounts/ClientLogin';
/************Authentication**************/
$this->zend->load("Zend/Gdata/YouTube");
$this->zend->load("Zend/Gdata/HttpClient");
$this->zend->load("Zend/Gdata/App/MediaFileSource");
$this->zend->load("Zend/Gdata/App/HttpException");
$this->zend->load("Zend/Uri/Http");
$youtube = new Zend_Gdata_YouTube();
$myVideoEntry = new Zend_Gdata_YouTube_VideoEntry();
$Gdata_AuthSub=new Zend_Gdata_AuthSub();
$this->load->helper("text");
}
function index(){
$data['result']='videos';
$this->load->view('videos/newform', $data);
}
function indexed(){
$title = 'GruppoDSE Video';
$description = 'Description';
$youtube = new Zend_Gdata_YouTube();
$authenticationURL= 'https://www.google.com/youtube/accounts/ClientLogin';
$httpClient = Zend_Gdata_ClientLogin::getHttpClient(
$username = $this->config->item('username'),
$password = $this->config->item('password'),
$service = 'youtube',
$client = null,
$source = 'Arts Connector', // a short string identifying your application
$loginToken = null,
$loginCaptcha = null,
$authenticationURL);
$developerKey = $this->config->item('developer_key');
$applicationId = 'Arts Connector';
$clientId = 'My video upload client - v1';
$yt = new Zend_Gdata_YouTube($httpClient, $applicationId, $clientId, $developerKey);
// create a new VideoEntry object
$myVideoEntry = new Zend_Gdata_YouTube_VideoEntry();
$myVideoEntry->setVideoTitle($title);
$myVideoEntry->setVideoDescription($description);
// The category must be a valid YouTube category!
$myVideoEntry->setVideoCategory('Autos');
// Set keywords. Please note that this must be a comma-separated string
// and that individual keywords cannot contain whitespace
$myVideoEntry->SetVideoTags('cars, funny');
$tokenHandlerUrl = 'http://gdata.youtube.com/action/GetUploadToken';
$tokenArray = $yt->getFormUploadToken($myVideoEntry, $tokenHandlerUrl);
$data['tokenValue'] = $tokenArray['token'];
$data['postUrl'] = $tokenArray['url'];
// place to redirect user after upload
$data['nextUrl'] = 'http://www.avantajsoftwares.com/gruppo/uploadVideo';
$res="Il file video aggiungere con successo, il risultato atteso verrĂ  visualizzato dopo alcune volte";
$this->session->set_userdata('greenFlag',$res);
// build the form
$this->load->view('videos/form', $data);
}
function AddVideoAjax(){
$title=$_POST['title'];
$description=$_POST['description'];
$youtube = new Zend_Gdata_YouTube();
$authenticationURL= 'https://www.google.com/youtube/accounts/ClientLogin';
$httpClient = Zend_Gdata_ClientLogin::getHttpClient(
$username = $this->config->item('username'),
$password = $this->config->item('password'),
$service = 'youtube',
$client = null,
$source = 'Arts Connector', // a short string identifying your application
$loginToken = null,
$loginCaptcha = null,
$authenticationURL);
$developerKey = $this->config->item('developer_key');
$applicationId = 'Arts Connector';
$clientId = 'My video upload client - v1';
try {
$yt = new Zend_Gdata_YouTube($httpClient, $applicationId, $clientId, $developerKey);
// create a new VideoEntry object
$myVideoEntry = new Zend_Gdata_YouTube_VideoEntry();
$myVideoEntry->setVideoTitle($title);
$myVideoEntry->setVideoDescription($description);
// The category must be a valid YouTube category!
$myVideoEntry->setVideoCategory('Education');
// Set keywords. Please note that this must be a comma-separated string
// and that individual keywords cannot contain whitespace
$myVideoEntry->SetVideoTags('Seminar, Events');
$tokenHandlerUrl = 'http://gdata.youtube.com/action/GetUploadToken';
$tokenArray = $yt->getFormUploadToken($myVideoEntry, $tokenHandlerUrl);
$tokenValue = $tokenArray['token'];
$postUrl = $tokenArray['url'];
// place to redirect user after upload
$nextUrl = 'http://www.avantajsoftwares.com/gruppo/Addvideo';
$res="Il file video aggiungere con successo, il risultato atteso verrĂ  visualizzato dopo alcune volte";
$this->session->set_userdata('greenFlag',$res);
// build the form
echo $form = '<form action="'. $postUrl .'?nexturl='. $nextUrl .
'" method="post" enctype="multipart/form-data" onsubmit="return valid()">'.
'<div style="float:left;"><input name="file" type="file" id="file"/></div><div class="preloader"></div>'.
'<input name="token" type="hidden" value="'. $tokenValue .'"/>'.
'<div style="clear:both"></div>'.
'<div class="login-footer" id="prog_bar style="cursor:pointer"><input value="Carica video" type="submit" id="validate" class="button" onclick="progress_bar()"/></div>'.
'</form>';
} catch (Zend_Gdata_App_Exception $e) {
echo $return="<div class='login-footer' style='width:130px;'><a style='height:16px; padding-top:7px;' class='button' href=".site_url()."Addvideo>Riprova di nuovo</a></div>";
}
// Assuming that $videoEntry is the object that was returned during the upload
//$state = $myVideoEntry->getVideoState();
}
function getAuthSubRequestUrl()
{
$gdata_AuthSub = new Zend_Gdata_AuthSub();
$next = 'http://www.avantajsoftwares.com/gruppo/videos';
$scope = 'http://gdata.youtube.com';
$secure = false;
$session = true;
return $data=$gdata_AuthSub->getAuthSubTokenUri($next, $scope, $secure, $session);
}
function getAuthSubHttpClient()
{
echo $_SESSION['sessionToken'];
if (!isset($_SESSION['sessionToken']) && !isset($_GET['token']) ){
echo 'Login!';
return;
} else if (!isset($_SESSION['sessionToken']) && isset($_GET['token'])) {
$_SESSION['sessionToken'] = Zend_Gdata_AuthSub::getAuthSubSessionToken($_GET['token']);
}
$httpClient = Zend_Gdata_AuthSub::getHttpClient($_SESSION['sessionToken']);
return $httpClient;
}
/*************************** Class end ***********************************/
}
I don't recommend using Zend with CI due to it's size and complexity. I developed a library specifically for CodeIgniter https://github.com/jimdoescode/CodeIgniter-YouTube-API-Library
The library provides several different options for uploading to YouTube. You can do a direct upload where you upload a video stored on your server to youtube. There is also an option to use a form to upload a video from the client to youtube. Check it out and let me know if you have any questions.
The docs have this, as well as other methods, covered for Zend Gdata: Uploading Videos

Zend framework, YouTube API, default title (Browserbased upload)

I got this code for uploading videos to my youtubeaccount from my website:
<?php
session_start();
set_time_limit(0);
ini_set('memory_limit', '150M');
ini_set('upload_max_filesize', '30M');
ini_set('default_socket_timeout', '6000');
ini_set('max_input_time', '6000');
ini_set('post_max_size', '100M');
ini_set('max_execution_time', '6000');
$clientLibraryPath = 'library';
$oldPath = set_include_path(get_include_path() . PATH_SEPARATOR . $clientLibraryPath);
//include Zend Gdata Libs
require_once("Zend/Gdata/ClientLogin.php");
require_once("Zend/Gdata/HttpClient.php");
require_once("Zend/Gdata/YouTube.php");
require_once("Zend/Gdata/App/MediaFileSource.php");
require_once("Zend/Gdata/App/HttpException.php");
require_once('Zend/Uri/Http.php');
//yt account info
$yt_user = 'xx'; //youtube username or gmail account
$yt_pw = 'xx'; //account password
$yt_source = 'xx'; //name of application (can be anything)
//yt dev key
$yt_api_key = 'xx'; //your youtube developer key
//login in to YT
$authenticationURL= 'https://www.google.com/youtube/accounts/ClientLogin';
$httpClient = Zend_Gdata_ClientLogin::getHttpClient(
$username = $yt_user,
$password = $yt_pw,
$service = 'youtube',
$client = null,
$source = $yt_source, // a short string identifying your application
$loginToken = null,
$loginCaptcha = null,
$authenticationURL);
$yt = new Zend_Gdata_YouTube($httpClient, $yt_source, NULL, $yt_api_key);
$myVideoEntry = new Zend_Gdata_YouTube_VideoEntry();
$myVideoEntry->setVideoTitle('The Movie');
$myVideoEntry->setVideoDescription('My Test Movie');
$myVideoEntry->setVideoCategory('Autos');
$myVideoEntry->SetVideoTags('cars, funny');
$tokenHandlerUrl = 'http://gdata.youtube.com/action/GetUploadToken';
$tokenArray = $yt->getFormUploadToken($myVideoEntry, $tokenHandlerUrl);
$tokenValue = $tokenArray['token'];
$postUrl = $tokenArray['url'];
// place to redirect user after upload
$nextUrl = 'http://sabinequardon.dk';
// build the form
$form = '<form id="youtube_upload" action="'. $postUrl .'?nexturl='. $nextUrl .
'" method="post" enctype="multipart/form-data" target="uploader">'.
'<input id="title" name="video_title" type="text"/>'.
'<input id="file_upload" name="file_upload" type="file"/>'.
'<input name="token" type="hidden" value="'. $tokenValue .'"/>'.
'<input value="Upload Video File" type="submit" id="submit" />'.
'</form>
';
echo $form;
?>
I'm not really good at PHP, and it's the first time I'm trying to use the YouTube API. Been reading everything I could, just didn't seem to help much.
I know it's something that I get the metadata first before uploading the video?
I need the user to write their own title, so all the video's aren't named the same thing.
Is there a way to do this?
I've tried looking everywhere, just can't seem to find the right answer.
Just annoying if all the videos the users are uploading are called the same.
Thank you.
This line sets the video title:
$myVideoEntry->setVideoTitle('The Movie');
As you already have an input for the title in the form, you can simply use it:
$video_title = $_POST['video_title'];
$myVideoEntry->setVideoTitle($video_title);
Or simply:
$myVideoEntry->setVideoTitle($_POST['video_title']);

Categories