Youtube Api Get Video Url From Upload
Everybody knows about YouTube. YouTube is the number i video-sharing platform in the globe. The YouTube platform allows united states to host our videos. This saves united states a lot of server space and one can hands embed the video from YouTube on their website. Anyone can upload the video on YouTube. You just demand to create your YouTube business relationship and upload the video. Unproblematic and straightforward procedure. But what if someone needs to upload videos through the YouTube API on a YouTube channel? Is it possible? Aye, it is possible. In this article, we study how to use the YouTube API to upload a video using PHP.
Annals the Application and Create Credentials
To become started with the YouTube API, you need a Google Account. Once yous accept a Google account register your application and get the API keys.
Below are the steps to register an application and get your API keys.
- Go to the Google Developer Panel https://console.developers.google.com.
- Create a new projection. You can select existing projects as well.
- Type a proper name of your project. Google Console volition create a unique project ID.
- After creating a project, it will appear on acme of the left sidebar.
- Click on Library. You volition come across a list of Google APIs.
- Enable YouTube Data API.
- Click on the Credentials. Select Oauth Client id under Create credentials. Select the radio button for Web Application.
- Requite the Name. Under Authorized JavaScript origins enter your domain URL. In the Authorized redirect URIs give the link of the redirect URL. In my case I passed the URL
http://localhost/youtube/callback.php
. - Click on the Create button. You will get customer ID and client surreptitious in the popular-upwards. Copy these details. We will need it in a moment.
Setup a Basic Configuration
Uploading video using the YouTube API requires you lot to create an admission token. An access token is null simply an identifier of your YouTube account.
Only, the access token expires after some time passes. The expired access token throws the error of 'Unauthorized access'. The solution for this is to run the authorization procedure again or regenerate the access token in the background. In this article, I get for a second solution. We will regenerate the access token if it expires in the background without breaking the uploading procedure. By doing so, you lot don't need to do the authorization process again and again.
For this, you need to first authorize the business relationship to generate an access token. I am going to use the Hybridauth library for potency and to generate the admission token. Open your composer.json
file and add the below lines in it.
{ "require": { "google/apiclient": "^2.10", "hybridauth/hybridauth" : "~3.0" }, "scripts": { "pre-autoload-dump": "Google\\Task\\Composer::cleanup" }, "extra": { "google/apiclient-services": [ "YouTube" ] } }
Go on a notation YouTube is Google'south production and YouTube API is nothing but a Google API. That'south why we are using "google/apiclient" library. There are over 200 Google API services and we need just 'YouTube' service. And then I used Google\Task\Composer::cleanup
task to clean up and kept only the 'YouTube' service.
Next, run the control beneath for the installation of libraries.
composer install
Database Configuration
On each API telephone call, we need to transport an access token. And so it should be stored in the database. Create a table 'youtube_oauth' in your database using the beneath query.
CREATE TABLE `youtube_oauth` ( `id` int(11) NOT NULL AUTO_INCREMENT, `provider` varchar(255) NOT Aught, `provider_value` text Not NULL, PRIMARY Primal (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
We will need to interact with this 'youtube_oauth' tabular array for fetching and updating token details. That requires writing a database connection and a few queries. Create a file form-db.php
and add the following lawmaking to it.
grade-db.php
<?php course DB { private $dbHost = "DB_HOST"; individual $dbUsername = "DB_USERNAME"; individual $dbPassword = "DB_PASSWORD"; individual $dbName = "DB_NAME"; public function __construct(){ if(!isset($this->db)){ // Connect to the database $conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName); if($conn->connect_error){ die("Failed to connect with MySQL: " . $conn->connect_error); }else{ $this->db = $conn; } } } public function is_table_empty() { $result = $this->db->query("SELECT id FROM youtube_oauth WHERE provider = 'youtube'"); if($result->num_rows) { render false; } render true; } public role get_access_token() { $sql = $this->db->query("SELECT provider_value FROM youtube_oauth WHERE provider = 'youtube'"); $result = $sql->fetch_assoc(); return json_decode($consequence['provider_value']); } public function get_refersh_token() { $result = $this->get_access_token(); return $result->refresh_token; } public part update_access_token($token) { if($this->is_table_empty()) { $this->db->query("INSERT INTO youtube_oauth(provider, provider_value) VALUES('youtube', '$token')"); } else { $this->db->query("UPDATE youtube_oauth SET provider_value = '$token' WHERE provider = 'youtube'"); } } }
Pass your database credentials in the above file. Here I have defined unlike methods which will fetch, insert, update the tokens.
Generate Access Token for YouTube API
Yous have installed the libraries and created a tabular array for storing the token. At present let's write the code which will perform the authorization procedure, grab the access token, and store it in the 'youtube_oauth' table.
Create a config.php
file and write a configuration as per guidelines of the HybridAuth library.
config.php
<?php require_once 'vendor/autoload.php'; require_once 'class-db.php'; define('GOOGLE_CLIENT_ID', 'PASTE_CLIENT_ID_HERE'); define('GOOGLE_CLIENT_SECRET', 'PASTE_CLIENT_SECRET_HERE'); $config = [ 'callback' => 'YOUR_DOMAIN_URL/callback.php', 'keys' => [ 'id' => GOOGLE_CLIENT_ID, 'secret' => GOOGLE_CLIENT_SECRET ], 'scope' => 'https://www.googleapis.com/auth/youtube https://www.googleapis.com/auth/youtube.upload', 'authorize_url_parameters' => [ 'approval_prompt' => 'force', // to laissez passer only when you need to acquire a new refresh token. 'access_type' => 'offline' ] ]; $adapter = new Hybridauth\Provider\Google( $config );
Replace the placeholders with the bodily values of your Google credentials. Add the same callback URL which yous passed while creating the console awarding. When the user completes the authorization process they volition redirect to the callback.php
file.
In callback.php
file, we volition fetch the access token details and shop them in the database.
callback.php
<?php require_once 'config.php'; try { $adapter->authenticate(); $token = $adapter->getAccessToken(); $db = new DB(); $db->update_access_token(json_encode($token)); echo "Access token inserted successfully."; } grab( Exception $due east ){ repeat $eastward->getMessage() ; }
Head over to your browser and run YOUR_DOMAIN_URL/callback.php, you volition redirect to the Google account, complete the authorization procedure and you should see the success message. Check the database table 'youtube_oauth'. It should have your token details stored. And that means you are good to get alee to upload a video on your YouTube aqueduct.
Upload Video on YouTube Channel using YouTube API
You got the access token required for uploading the video on the YouTube channel. But every bit I mentioned before, the admission token will expire after some time and we will regenerate it in the groundwork without request for authority again.
We can practice it using 'refersh_token'. If you look at the 'provider_value' column in the tabular array you will see it also contains the entry of 'refresh_token'. Using this 'refresh_token' we telephone call the '/o/oauth2/token' endpoint and regenerate the access token in the groundwork.
Next, create the HTML course to browse the video and send it to the server for uploading. Let'southward create a simple HTML form as follows.
index.php
<form method="post" enctype="multipart/form-data"> <p><input blazon="text" name="title" placeholder="Enter Video Title" /></p> <p><textarea proper noun="summary" cols="30" rows="ten" placeholder="Video description"></textarea></p> <p><input type="file" name="file" /></p> <input type="submit" name="submit" value="Submit" /> </form>
The form has 3 fields – title, description, and file. On submission of this form, the beneath lawmaking will upload your video on the YouTube channel forth with the title and description.
alphabetize.php
<?php require_once 'config.php'; if (isset($_POST['submit'])) { $arr_data = array( 'title' => $_POST['title'], 'summary' => $_POST['summary'], 'video_path' => $_FILES['file']['tmp_name'], ); upload_video_on_youtube($arr_data); } role upload_video_on_youtube($arr_data) { $customer = new Google_Client(); $db = new DB(); $arr_token = (array) $db->get_access_token(); $accessToken = array( 'access_token' => $arr_token['access_token'], 'expires_in' => $arr_token['expires_in'], ); $client->setAccessToken($accessToken); $service = new Google_Service_YouTube($client); $video = new Google_Service_YouTube_Video(); $videoSnippet = new Google_Service_YouTube_VideoSnippet(); $videoSnippet->setDescription($arr_data['summary']); $videoSnippet->setTitle($arr_data['championship']); $video->setSnippet($videoSnippet); $videoStatus = new Google_Service_YouTube_VideoStatus(); $videoStatus->setPrivacyStatus('public'); $video->setStatus($videoStatus); try { $response = $service->videos->insert( 'snippet,status', $video, array( 'data' => file_get_contents($arr_data['video_path']), 'mimeType' => 'video/*', 'uploadType' => 'multipart' ) ); echo "Video uploaded successfully. Video ID is ". $response->id; } catch(Exception $e) { if( 401 == $e->getCode() ) { $refresh_token = $db->get_refersh_token(); $client = new GuzzleHttp\Client(['base_uri' => 'https://accounts.google.com']); $response = $customer->request('POST', '/o/oauth2/token', [ 'form_params' => [ "grant_type" => "refresh_token", "refresh_token" => $refresh_token, "client_id" => GOOGLE_CLIENT_ID, "client_secret" => GOOGLE_CLIENT_SECRET, ], ]); $data = (array) json_decode($response->getBody()); $data['refresh_token'] = $refresh_token; $db->update_access_token(json_encode($data)); upload_video_on_youtube($arr_data); } else { //repeat $e->getMessage(); //impress the fault just in case your video is not uploaded. } } } ?>
The higher up code takes a video file from the HTML grade and uploads it through API on your YouTube channel. If your admission token has expired and so it regenerates the token in the background and continues the process without breaking it.
Upload a Custom Thumbnail on YouTube Video
If you are edifice a custom application that manages YouTube videos then probably yous are looking to upload a thumbnail for a YouTube video. Uploading a custom thumbnail requires users to verify their phone number with their YouTube account. Visit the link https://world wide web.youtube.com/features and practise the phone number verification.
Once y'all verified the phone number, you tin can use our previous course and code with little modifications and prepare the custom thumbnail for the uploaded video. Commencement, add the form field which allows uploading images. The recommended YouTube thumbnail size is 1280x720
.
<p> <label>Paradigm</characterization> <input blazon="file" proper name="prototype" accept="image/*" /> </p>
On the form submit, we have built an array $arr_data
which contains all class information. Add the new pair for the image to the assortment $arr_data
every bit follows.
$arr_data = array( 'title' => $_POST['title'], 'summary' => $_POST['summary'], 'video_path' => $_FILES['file']['tmp_name'], 'image_path' => $_FILES['image']['tmp_name'], // hither nosotros are passing image );
Next, after uploading the video on YouTube, we have to accept the video id and assign a custom thumbnail to the video.
<?php ... ... echo "Video uploaded successfully. Video ID is ". $response->id; //upload thumbnail $videoId = $response->id; $chunkSizeBytes = one * 1024 * 1024; $client->setDefer(true); $setRequest = $service->thumbnails->set($videoId); $media = new Google_Http_MediaFileUpload( $customer, $setRequest, 'image/png', null, true, $chunkSizeBytes ); $imagePath = $arr_data['image_path']; $media->setFileSize(filesize($imagePath)); $status = simulated; $handle = fopen($imagePath, "rb"); while (!$condition && !feof($handle)) { $chunk = fread($handle, $chunkSizeBytes); $condition = $media->nextChunk($chunk); } fclose($handle); $client->setDefer(false); echo "Thumbnail URL: ". $condition['items'][0]['default']['url'];
Delete Video from YouTube Aqueduct using YouTube API
Yous may as well desire a lawmaking to delete videos using YouTube API. In lodge to delete a video, you lot require an additional scope https://www.googleapis.com/auth/youtube
which I accept already included in a config file. It means the admission token generated by following the above steps has the power to delete a video.
Below is the code which will delete a video from your YouTube aqueduct.
<?php require_once 'config.php'; delete_video('VIDEO_ID_HERE'); function delete_video($id) { $client = new Google_Client(); $db = new DB(); $arr_token = (assortment) $db->get_access_token(); $accessToken = array( 'access_token' => $arr_token['access_token'], 'expires_in' => $arr_token['expires_in'], ); try { $client->setAccessToken($accessToken); $service = new Google_Service_YouTube($client); $service->videos->delete($id); echo 'Video deleted successfully.'; } grab(Exception $due east) { if( 401 == $e->getCode() ) { $refresh_token = $db->get_refersh_token(); $client = new GuzzleHttp\Client(['base_uri' => 'https://accounts.google.com']); $response = $client->request('Postal service', '/o/oauth2/token', [ 'form_params' => [ "grant_type" => "refresh_token", "refresh_token" => $refresh_token, "client_id" => GOOGLE_CLIENT_ID, "client_secret" => GOOGLE_CLIENT_SECRET, ], ]); $data = (assortment) json_decode($response->getBody()); $data['refresh_token'] = $refresh_token; $db->update_access_token(json_encode($information)); delete_video($id); } else { //echo $due east->getMessage(); //print the error just in case your video is not uploaded. } } }
That's it! I hope you got to know about how to upload a video on the YouTube channel using the YouTube API. I would like to hear your thoughts or suggestions in the comment section below.
Related Articles
- How to Upload Video on YouTube in Laravel Application
- How to Become YouTube Video Tags using YouTube API
- YouTube API – How to Get List of YouTube Videos of Your Aqueduct
- How to Get YouTube Video List by Keywords using YouTube Search API
If you liked this article, then delight subscribe to our YouTube Channel for video tutorials.
Source: https://artisansweb.net/use-youtube-api-upload-video-youtube-channel/