2

Using the YouTube API to upload videos to a single channel is straightforward. This is how I currently do it using the PHP Client Library:

<?php

/**
 * This sample adds new tags to a YouTube video by:
 *
 * 1. Retrieving the video resource by calling the "youtube.videos.list" method
 *    and setting the "id" parameter
 * 2. Appending new tags to the video resource's snippet.tags[] list
 * 3. Updating the video resource by calling the youtube.videos.update method.
 *
 * @author Ibrahim Ulukaya
*/

/**
 * Library Requirements
 *
 * 1. Install composer (https://getcomposer.org)
 * 2. On the command line, change to this directory (api-samples/php)
 * 3. Require the google/apiclient library
 *    $ composer require google/apiclient:~2.0
 */
if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
  throw new \Exception('please run "composer require google/apiclient:~2.0" in "' . __DIR__ .'"');
}

require_once __DIR__ . '/vendor/autoload.php';
session_start();

/*
 * You can acquire an OAuth 2.0 client ID and client secret from the
 * {{ Google Cloud Console }} <{{ https://cloud.google.com/console }}>
 * For more information about using OAuth 2.0 to access Google APIs, please see:
 * <https://developers.google.com/youtube/v3/guides/authentication>
 * Please ensure that you have enabled the YouTube Data API for your project.
 */
$OAUTH2_CLIENT_ID = 'REPLACE_ME';
$OAUTH2_CLIENT_SECRET = 'REPLACE_ME';

$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setScopes('https://www.googleapis.com/auth/youtube');
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],
    FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);

// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);

// Check if an auth token exists for the required scopes
$tokenSessionKey = 'token-' . $client->prepareScopes();
if (isset($_GET['code'])) {
  if (strval($_SESSION['state']) !== strval($_GET['state'])) {
    die('The session state did not match.');
  }

  $client->authenticate($_GET['code']);
  $_SESSION[$tokenSessionKey] = $client->getAccessToken();
  header('Location: ' . $redirect);
}

if (isset($_SESSION[$tokenSessionKey])) {
  $client->setAccessToken($_SESSION[$tokenSessionKey]);
}

// Check to ensure that the access token was successfully acquired.
if ($client->getAccessToken()) {
  $htmlBody = '';
  try{

    // REPLACE this value with the video ID of the video being updated.
    $videoId = "VIDEO_ID";

    // Call the API's videos.list method to retrieve the video resource.
    $listResponse = $youtube->videos->listVideos("snippet",
        array('id' => $videoId));

    // If $listResponse is empty, the specified video was not found.
    if (empty($listResponse)) {
      $htmlBody .= sprintf('<h3>Can\'t find a video with video id: %s</h3>', $videoId);
    } else {
      // Since the request specified a video ID, the response only
      // contains one video resource.
      $video = $listResponse[0];
      $videoSnippet = $video['snippet'];
      $tags = $videoSnippet['tags'];

      // Preserve any tags already associated with the video. If the video does
      // not have any tags, create a new list. Replace the values "tag1" and
      // "tag2" with the new tags you want to associate with the video.
      if (is_null($tags)) {
        $tags = array("tag1", "tag2");
      } else {
        array_push($tags, "tag1", "tag2");
      }

      // Set the tags array for the video snippet
      $videoSnippet['tags'] = $tags;

      // Update the video resource by calling the videos.update() method.
      $updateResponse = $youtube->videos->update("snippet", $video);

      $responseTags = $updateResponse['snippet']['tags'];

      $htmlBody .= "<h3>Video Updated</h3><ul>";
      $htmlBody .= sprintf('<li>Tags "%s" and "%s" added for video %s (%s) </li>',
          array_pop($responseTags), array_pop($responseTags),
          $videoId, $video['snippet']['title']);

      $htmlBody .= '</ul>';
    }
  } catch (Google_Service_Exception $e) {
    $htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>',
        htmlspecialchars($e->getMessage()));
  } catch (Google_Exception $e) {
    $htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>',
        htmlspecialchars($e->getMessage()));
  }

    $_SESSION[$tokenSessionKey] = $client->getAccessToken();
} elseif ($OAUTH2_CLIENT_ID == 'REPLACE_ME') {
  $htmlBody = <<<END
  <h3>Client Credentials Required</h3>
  <p>
    You need to set <code>\$OAUTH2_CLIENT_ID</code> and
    <code>\$OAUTH2_CLIENT_ID</code> before proceeding.
  <p>
END;
} else {
  // If the user hasn't authorized the app, initiate the OAuth flow
  $state = mt_rand();
  $client->setState($state);
  $_SESSION['state'] = $state;

  $authUrl = $client->createAuthUrl();
  $htmlBody = <<<END
<h3>Authorization Required</h3>
<p>You need to <a href="$authUrl">authorize access</a> before proceeding.<p>
END;
}
?>

<!doctype html>
<html>
<head>
<title>Video Updated</title>
</head>
<body>
  <?=$htmlBody?>
</body>
</html>
update_video.php

The very first time the script runs, I am prompted with a window to authenticate the request, a token is granted and expires in 60 minutes.

I want to use the same script to upload videos to different channels which I own. For example if I have 3 different channels I can sign in to different browsers to authenticate the application. I currently have more than 10 YouTube channels that I want to upload content to after every few hours.

Is there a way I can manage all these channels from a central service so as to avoid authenticating each time I add a new channel. Or is there a way to authenticate the YouTube API using my YouTube login details?

halfer
  • 18,701
  • 13
  • 79
  • 158
salimsaid
  • 1,886
  • 2
  • 11
  • 17

1 Answers1

0

The YouTube API is slightly different then other Google APIs. Normally authentication is user account based. So if I authenticate you to access my Google calendar you have access to all my Google calendars.

The YouTube API is how ever User channel based. Your going to have to authenticate your application once for each channel. Then make sure you have a refresh token. Store the refresh token someplace associated with the name of the channel. Then you your automated script will be able to use the refresh token to request a new access token and gain access to your account when ever it needs.
This question is for the Analytics api but the code should work for YouTube as well with a few minor alterations to point to the YouTube API instead. How to refresh token with Google API client?

Community
  • 1
  • 1
DaImTo
  • 72,534
  • 21
  • 122
  • 346
  • Hey @DaImTo , thanks for your feedback however it appears what you are suggesting is what i currently use, i have token refresh logic in place & it refreshes token accordingly each hour. The problems is that i can not use 1 browser to authenticate 2 different channels. One authentication cycle per browser, if i authenticate a different account the first authentication gets revoked. i.e. i need 100 browsers to authenticate 100 different youtube channel users. Any additional suggestions would be greatly appreciated. Thanks.. – salimsaid Dec 07 '16 at 20:38