banner



How To Publish Video On Youtube From Another Channel

Everybody knows about YouTube. YouTube is the number one video-sharing platform in the earth. The YouTube platform allows us to host our videos. This saves us a lot of server infinite and one can easily embed the video from YouTube on their website. Anyone tin can upload the video on YouTube. You just demand to create your YouTube account and upload the video. Unproblematic and straightforward procedure. Merely what if someone needs to upload videos through the YouTube API on a YouTube channel? Is it possible? Yes, it is possible. In this article, we written report how to employ the YouTube API to upload a video using PHP.

Register the Application and Create Credentials

To get started with the YouTube API, you need a Google Account. Once yous accept a Google business relationship register your application and get the API keys.

Beneath are the steps to annals an application and get your API keys.

  • Go to the Google Programmer Console https://console.developers.google.com.
  • Create a new projection. You tin select existing projects also.
  • Type a name of your project. Google Panel will create a unique project ID.
  • After creating a project, information technology will appear on summit of the left sidebar.
  • Click on Library. You will see a listing of Google APIs.
  • Enable YouTube Data API.
  • Click on the Credentials. Select Oauth Client id under Create credentials. Select the radio button for Web Awarding.
  • Requite the Proper noun. 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 push button. You volition become client ID and client secret in the pop-up. Copy these details. We will need it in a moment.
Google Credentials

Setup a Bones Configuration

Uploading video using the YouTube API requires you to create an access token. An admission token is nothing just an identifier of your YouTube account.

But, 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 authorisation procedure again or regenerate the access token in the groundwork. In this article, I get for a 2d solution. We will regenerate the access token if information technology expires in the groundwork without breaking the uploading process. Past doing so, y'all don't demand to practise the authorization process once again and again.

For this, y'all demand to beginning qualify the business relationship to generate an access token. I am going to use the Hybridauth library for potency and to generate the access 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\\Chore\\Composer::cleanup"     },     "actress": {         "google/apiclient-services": [             "YouTube"         ]     } }          

Keep a note YouTube is Google's product and YouTube API is nothing only a Google API. That'southward why we are using "google/apiclient" library. In that location are over 200 Google API services and nosotros need merely 'YouTube' service. So I used Google\Chore\Composer::cleanup chore to clean up and kept only the 'YouTube' service.

Adjacent, run the command below for the installation of libraries.

composer install

Database Configuration

On each API call, we need to send an access token. And so information technology should be stored in the database. Create a tabular array 'youtube_oauth' in your database using the beneath query.

CREATE Tabular array `youtube_oauth` (  `id` int(eleven) Not Nil AUTO_INCREMENT,  `provider` varchar(255) Non NULL,  `provider_value` text NOT Zippo,  Master KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;          

Nosotros will need to interact with this 'youtube_oauth' table for fetching and updating token details. That requires writing a database connection and a few queries. Create a file class-db.php and add the following lawmaking to it.

course-db.php

<?php course DB {     individual $dbHost     = "DB_HOST";     private $dbUsername = "DB_USERNAME";     private $dbPassword = "DB_PASSWORD";     private $dbName     = "DB_NAME";       public part __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) {             return false;         }           render true;     }       public office get_access_token() {         $sql = $this->db->query("SELECT provider_value FROM youtube_oauth WHERE provider = 'youtube'");         $consequence = $sql->fetch_assoc();         return json_decode($result['provider_value']);     }       public function get_refersh_token() {         $effect = $this->get_access_token();         return $result->refresh_token;     }       public function 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 Fix provider_value = '$token' WHERE provider = 'youtube'");         }     } }          

Pass your database credentials in the above file. Hither I accept defined unlike methods which will fetch, insert, update the tokens.

Generate Access Token for YouTube API

Y'all take installed the libraries and created a table for storing the token. At present allow's write the lawmaking which volition perform the authorization process, 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' => 'forcefulness', // to laissez passer only when you need to larn a new refresh token.             'access_type' => 'offline'     ] ];   $adapter = new Hybridauth\Provider\Google( $config );          

Supersede the placeholders with the actual values of your Google credentials. Add the aforementioned callback URL which you lot passed while creating the console awarding. When the user completes the authorization process they will 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';   endeavor {     $adapter->authenticate();     $token = $adapter->getAccessToken();     $db = new DB();     $db->update_access_token(json_encode($token));     repeat "Access token inserted successfully."; } catch( Exception $e ){     echo $e->getMessage() ; }          

Head over to your browser and run YOUR_DOMAIN_URL/callback.php, you volition redirect to the Google account, complete the authorization process and you should see the success message. Bank check the database table 'youtube_oauth'. It should accept your token details stored. And that means you are proficient to go alee to upload a video on your YouTube channel.

Upload Video on YouTube Aqueduct using YouTube API

You got the access token required for uploading the video on the YouTube channel. But as I mentioned before, the access token volition elapse later on some time and we will regenerate information technology in the background without asking for authorization again.

Nosotros can practice it using 'refersh_token'. If you lot look at the 'provider_value' column in the tabular array you will see it likewise contains the entry of 'refresh_token'. Using this 'refresh_token' we call the '/o/oauth2/token' endpoint and regenerate the access token in the background.

Side by side, create the HTML form to browse the video and send information technology to the server for uploading. Permit's create a simple HTML class as follows.

alphabetize.php

<course method="post" enctype="multipart/class-data">     <p><input type="text" proper noun="title" placeholder="Enter Video Title" /></p>     <p><textarea proper noun="summary" cols="thirty" rows="ten" placeholder="Video clarification"></textarea></p>     <p><input type="file" name="file" /></p>     <input type="submit" name="submit" value="Submit" /> </course>          

The form has 3 fields – title, description, and file. On submission of this form, the below lawmaking volition upload your video on the YouTube channel along with the title and description.

index.php

<?php require_once 'config.php';   if (isset($_POST['submit'])) {     $arr_data = array(         'title' => $_POST['championship'],         'summary' => $_POST['summary'],         'video_path' => $_FILES['file']['tmp_name'],     );     upload_video_on_youtube($arr_data); }   office upload_video_on_youtube($arr_data) {       $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'],     );       $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['title']);     $video->setSnippet($videoSnippet);       $videoStatus = new Google_Service_YouTube_VideoStatus();     $videoStatus->setPrivacyStatus('public');     $video->setStatus($videoStatus);       try {         $response = $service->videos->insert(             'snippet,condition',             $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 = $client->request('Mail', '/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 $east->getMessage(); //print the fault just in instance your video is not uploaded.         }     } } ?>          

The above code takes a video file from the HTML form and uploads it through API on your YouTube channel. If your access token has expired then it regenerates the token in the background and continues the process without breaking it.

Upload a Custom Thumbnail on YouTube Video

If you are building a custom awarding that manages YouTube videos then probably you are looking to upload a thumbnail for a YouTube video. Uploading a custom thumbnail requires users to verify their phone number with their YouTube business relationship. Visit the link https://www.youtube.com/features and practice the phone number verification.

Once yous verified the phone number, you tin can utilise our previous form and lawmaking with fiddling modifications and gear up 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>Prototype</label>     <input type="file" name="image" have="image/*" /> </p>          

On the course submit, nosotros have congenital an array $arr_data which contains all form data. Add the new pair for the epitome to the array $arr_data as follows.

$arr_data = array(     'title' => $_POST['title'],     'summary' => $_POST['summary'],     'video_path' => $_FILES['file']['tmp_name'],     'image_path' => $_FILES['image']['tmp_name'], // here nosotros are passing image );          

Next, after uploading the video on YouTube, we have to take 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 = 1 * 1024 * 1024;   $customer->setDefer(truthful);   $setRequest = $service->thumbnails->gear up($videoId);   $media = new Google_Http_MediaFileUpload(     $client,     $setRequest,     'image/png',     goose egg,     true,     $chunkSizeBytes ); $imagePath = $arr_data['image_path']; $media->setFileSize(filesize($imagePath));   $status = imitation; $handle = fopen($imagePath, "rb");   while (!$status && !feof($handle)) {     $chunk  = fread($handle, $chunkSizeBytes);     $status = $media->nextChunk($chunk); }   fclose($handle);   $client->setDefer(false); echo "Thumbnail URL: ". $status['items'][0]['default']['url'];          

Delete Video from YouTube Channel using YouTube API

You may also want a code to delete videos using YouTube API. In gild to delete a video, you require an additional scope https://www.googleapis.com/auth/youtube which I have already included in a config file. It means the admission token generated past following the above steps has the power to delete a video.

Beneath is the code which will delete a video from your YouTube channel.

<?php require_once 'config.php';   delete_video('VIDEO_ID_HERE');   function delete_video($id) {           $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'],     );           effort {         $client->setAccessToken($accessToken);         $service = new Google_Service_YouTube($client);         $service->videos->delete($id);     repeat 'Video deleted successfully.';     } catch(Exception $e) {         if( 401 == $e->getCode() ) {             $refresh_token = $db->get_refersh_token();               $client = new GuzzleHttp\Client(['base_uri' => 'https://accounts.google.com']);               $response = $client->request('Mail', '/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());             $information['refresh_token'] = $refresh_token;               $db->update_access_token(json_encode($data));               delete_video($id);         } else {             //echo $e->getMessage(); //print the error just in case your video is not uploaded.         }     } }          

That's it! I hope y'all got to know well-nigh how to upload a video on the YouTube aqueduct using the YouTube API. I would similar to hear your thoughts or suggestions in the annotate section below.

Related Articles

  • How to Upload Video on YouTube in Laravel Application
  • How to Get YouTube Video Tags using YouTube API
  • YouTube API – How to Go List of YouTube Videos of Your Aqueduct
  • How to Get YouTube Video Listing by Keywords using YouTube Search API

If you lot liked this article, then please subscribe to our YouTube Channel for video tutorials.

Source: https://artisansweb.net/use-youtube-api-upload-video-youtube-channel/

Posted by: mercerposelver.blogspot.com

0 Response to "How To Publish Video On Youtube From Another Channel"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel