2

使用YouTube API將視頻上傳到單個頻道非常簡單。 這是我如何使用PHP客戶端庫目前做,,使用YouTube API將視頻上傳到多個頻道

<?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 

腳本運行的第一次,促使我與一個窗口來驗證請求,令牌被授予並在60分鐘內到期。

我想使用相同的腳本將視頻上傳到我擁有的不同頻道。例如,如果我有3個不同的頻道,我可以登錄到不同的瀏覽器來驗證應用程序。 我目前有超過10個YouTube頻道,每隔幾個小時後我想上傳內容。

有沒有一種方法可以從中央服務管理所有這些通道,以避免每次添加新通道時進行身份驗證。或者有沒有一種方法可以使用我的YouTube用戶登錄信息來驗證YouTube的API? 任何建議將不勝感激。謝謝。

回答

0

YouTube API與其他Google API略有不同。通常,認證是基於用戶帳戶的。因此,如果我通過身份驗證來訪問我的Google日曆,則可以訪問我所有的Google日曆。

YouTube API是基於用戶頻道的。您將不得不爲每個頻道驗證一次應用程序。然後確保你有一個刷新令牌。將刷新令牌存儲在與通道名稱關聯的位置。然後,您的自動腳本將能夠使用刷新令牌請求新的訪問令牌,並在需要時訪問您的帳戶。
這個問題適用於Analytics API,但代碼應該適用於YouTube,只需稍作修改即可指向YouTube API。 How to refresh token with Google API client?

+0

嗨@DaImTo,感謝您的反饋,但看起來您所暗示的是我目前使用的,我有令牌刷新邏輯,並且每小時相應地刷新令牌。問題是我無法使用1瀏覽器來驗證2個不同的頻道。每個瀏覽器一個驗證週期,如果我驗證了另一個帳戶,第一個驗證將被撤銷。即我需要100個瀏覽器來認證100個不同的YouTube用戶。任何額外的建議將不勝感激。謝謝.. – electronicsalim

相關問題