Allow users to upload videos to my channel using youtube API v3 - php

Using Google API v3 php library . I want the user to upload videos on my youtube channel. But oAuth require user google login and the video uploaded to the logged in user youtube channel.
Before using the V3 api we used the V2 to upload the video and it works well.
global $youtube_api_key, $youtube_username, $youtube_password;
if(is_file('../uploader/ClassYouTubeAPI.php')){ include_once ('../uploader/ClassYouTubeAPI.php'); }
else{ include_once('ClassYouTubeAPI.php'); }
$obj = new ClassYouTubeAPI($youtube_api_key);
$result = $obj->clientLoginAuth($youtube_username, $youtube_password);
$result = $obj->uploadVideo($uploaded_file_name, $file_path, $title, $description, $privacy);
var_dump($result);
if (is_array($result) and count($result) and ! isset($result["is_error"])) {
$youtube_file = str_replace($uploaded_file_name, $result["videoId"] . '.youtube', $file_path);
$resource = fopen($youtube_file, 'w');
fwrite($resource, "");
fclose($resource);
#unlink($file_path);
return $result["videoId"];
} else {
#unlink($file_path);
return false;
}
Is there any way to use the V3 without 'User Google Account' and upload the video to my channel?

There is only one solution, described here.
In short, you must create a "web application" account (not a "service account") in Google console and do authentication from your server on behalf of your YouTube account.

Related

How to get live video id from from youtube channel html

How to get live video id from YouTube channel using simple HTML dom parser or any other method rather than YouTube api?
https://www.youtube.com/embed/live_stream?channel=UC8Z-VjXBtDJTvq6aqkIskPg&autoplay=1
Because YouTube api does not work to get live video id.
Finaly i fund answer
function getvideourl($chid)
{
$videoId = null;
// Fetch the livestream page
if($data = file_get_contents('https://www.youtube.com/embed/live_stream?
channel='.$chid))
{
// Find the video ID in there
if(preg_match('/\'VIDEO_ID\': \"(.*?)\"/', $data, $matches))
$videoId = $matches[1];
else
$videoId ="";
}
else
throw new Exception('Couldn\'t fetch data');
$video_url = "https://www.youtube.com/embed/".$videoId;
return $video_url;
}

How can i upload video on specific channel using YouTube API in PHP?

I want to make functionality for users to upload video on my channel without authentication (if needed). IS it possible ?
Please help me .
Thanks
OM
Yes Omprakash,it is possible
You will need Google APIs Client Library for PHP.
You will also need to create a project on
https://console.developers.google.com/ and get credentials(i.e
client secret & client id).
Finally,you will need to generate access token for specific channel.
Please take a look at this link
(https://youtube-eng.googleblog.com/2013/06/google-page-identities-and-youtube-api_24.html)
to generate access token.
Once you have all these things ready with you,you can use ready made
example code available in Google APIs Client Library for PHP to upload
video on YouTube.
Note: This is not in detail process.It is not possible to explain all of the process in detail on stack-overflow. But, once you get close to solution,you can re-post or put comment for further assistance.
This is example code to upload video on YouTube. Hope, it will help you
/*include google libraries */
require_once '../api/src/Google/autoload.php';
require_once '../api/src/Google/Client.php';
require_once '../api/src/Google/Service/YouTube.php';
$application_name = 'Your application/project name created on google developer console';
$client_secret = 'Your client secret';
$client_id = 'Your client id';
$scope = array('https://www.googleapis.com/auth/youtube.upload', 'https://www.googleapis.com/auth/youtube', 'https://www.googleapis.com/auth/youtubepartner');
try{
$key = file_get_contents('the_key.txt'); //it stores access token obtained in step 3
$videoPath = 'video path on your server goes here';
$videoTitle = 'video title';
$videoDescription = 'video description';
$videoCategory = "22"; //please take a look at youtube video categories for videoCategory.Not so important for our example
$videoTags = array('tag1', 'tag2','tag3');
// 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('public');
// 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; //you got here youtube video id
} else {
// handle failere here
}
// 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) {
echo "\r\n Caught Google service Exception ".$e->getCode(). " message is ".$e->getMessage();
echo "\r\n Stack trace is ".$e->getTraceAsString();
} catch (Exception $e) {
echo "\r\n Caught Google service Exception ".$e->getCode(). " message is ".$e->getMessage();
echo "\r\n Stack trace is ".$e->getTraceAsString();
}

Laravel webapp login from iOS with Facebook SDK

i have a webapp working with Laravel.
i have some users registered in my webapp.
users who dont want to create a account can use Facebook/Google+ login.
to make Facebook/Google+ connection, i used a oAuth2 connexion with :
oauth-4-laravel
on the iOS application, users can login using username and password but they can login too with Facebook/Google+ using FB/G+ SDK.
my questions is, how to login on my webapp users from iOS who are connected by Facebook/Google+.
artdarek/oauth-4-laravel require a "code" given by the social network, and i dont know how to get it on iOS.
here the code for users who want to connect to the webapp by web browser :
public function loginWithFacebook() {
// get data from input
$code = Input::get( 'code' );
// get fb service
$fb = OAuth::consumer( 'Facebook' );
// check if code is valid
// if code is provided get user data and sign in
if ( !empty( $code ) ) {
// This was a callback request from facebook, get the token
$token = $fb->requestAccessToken( $code );
// Send a request with it
$result = json_decode( $fb->request( '/me' ), true );
// $message = 'Your unique facebook user id is: ' . $result['id'] . ' and your name is ' . $result['name'];
//echo $message. "<br/>";
//Var_dump
//display whole array().
// dd($result);
if (User::where('fb_id','=', $result['id'])->count() == 0) {
$user = new User;
$user->firstname = $result['first_name'];
$user->lastname = $result['last_name'];
$user->username = $result['email'];
$user->email = $result['email'];
$user->fb_id = $result['id'];
$user->yearofbirth = substr($result['birthday'],6,9);
$user->fk_role=3;
if ($result['gender'] == 'male') {
$user->sex = 1;
}
else{
$user->sex = 0;
}
$user->save();
}
else{
$user = User::where('fb_id','=', $result['id'])->first();
}
Auth::login($user);
Userslog::log('desktop_facebook_login');
return Redirect::to('/')->with('message', 'Logged in with Facebook');
}
// if not ask for permission first
else {
// get fb authorization
$url = $fb->getAuthorizationUri();
// return to facebook login url
return Redirect::to( (string)$url );
}
}
i finally find a solution in the issues of oauth-4-laravel on github,
i just have to use iOS AccessToken and connect the user to the webapp using this token.
here the code laravel code to use the Token ;)
use OAuth\OAuth2\Token\StdOAuth2Token;
$token_interface = new StdOAuth2Token(Input::get( 'token' ));
$network = OAuth::consumer( 'Facebook' );
$network->getStorage()->storeAccessToken('Facebook', $token_interface);
$result = json_decode( $network->request( '/me' ), true );
$fb_id = $result['id'];
To Resume,
the best way is ; to login with Facebook/Google+ on iOS,
when login finish with success, get the AccessToken and send to the webapp.And then the webapp use you token to login again the user to Facebook/Google+ and finally , the user is verified and you can login it to laravel webapp.
have a nice day.
I'm quite in the same situation here.
With the solution you provide, how are you preventing other applications to send their own AccessToken and access your Laravel application?
I assume you send the token via a POST request from you iOS app to a certain endpoint of your Laravel app, therefore any developper knowing this endpoint could pretend to be logged on your mobile application, no?

Why isn't my Google OAuth 2.0 Working?

I've been working on a small script to grab YouTube channel data and my Google OAuth 2.0 isn't working.
$validate = "https://accounts.google.com/o/oauth2/auth?client_id=242340718758-65veqhhdjfl21qc2klkfhbcb19rre8li.apps.googleusercontent.com&redirect_uri=http://conor1998.web44.net/php/oauth.php&scope=https://www.googleapis.com/auth/yt-analytics.readonly&response_type=code&access_type=offline";
echo "<a href='$validate'>Login with Google for advanced analytics</a>";
if(isset($_GET['code'])) {
// try to get an access token
$code = $_GET['code'];
$url = 'https://accounts.google.com/o/oauth2/token?code='.$code.'&client_id=242340718758-65veqhhdjfl21qc2klkfhbcb19rre8li.apps.googleusercontent.com&client_secret={secret}&redirect_uri=http://conor1998.web44.net/php/oauth.php&grant_type=authorization_code';
$url = urlencode($url);
header('Location: $url');
}
$response = file_get_contents($url);
$response = json_decode($response);
$channel_data = file_get_contents('https://www.googleapis.com/youtube/analytics/v1/reports?ids=channel==mine&start-date=2014-08-01&end-date=2014-09-01&metrics=views&key=AIzaSyDTxvTLWXStUrhzgCDptVUG4dGBCpyL9MY?alt=json');
$channel_data = json_decode($channel_data, true);
echo "<br />";
var_dump($channel_data);
echo "<br />";
I have no idea why it doesn't work. I feel it's mainly due to my goal of trying to get the authentication token for the user so i can grab their YouTube data. Any help would be appreciated
The code you receive from the auth website is not the access token! You have to exchange it for refresh and access tokens (see #4).
You have to perform a POST request to https://accounts.google.com/o/oauth2/token in order to get your tokens. It is not working via GET (as you can see when clicking the link).

Uploading video to an owned youtube channel

I am trying to upload video using my developer key to a youtube channel that is owned by my google account.
$authenticationURL= 'https://www.google.com/accounts/ClientLogin';
$httpClient =
Zend_Gdata_ClientLogin::getHttpClient(
$username = 'username',
$password = 'pass',
$service = 'youtube',
$client = null,
$source = 'mysource', // a short string identifying your application
$loginToken = null,
$loginCaptcha = null,
$authenticationURL);
$developerKey = 'key';
$applicationId = 'Video Upload';
$clientId = 'Video Uploader v1';
However when i try to upload to that channel it gives me "write-access" error even though this channel is owned by me.
I can manage this youtube channel easily using "switch account" of youtube. but when it comes to upload using the API i get write-access error.
I use upload url like this
http://uploads.gdata.youtube.com/feeds/api/users/CHANNELUSERNAME/uploads
Any idea how to fix this ?
This blog will give you the right information on how to manage multiple channels via API.

Categories