Javascript 将视频添加到用户';YouTube上最喜爱/喜欢的播放列表
其目的是使用YouTube API创建一个Favorite/Like按钮。当用户单击该按钮时,视频将保存到用户喜爱/喜欢的播放列表中 就像你在自己的网站上实现类似Facebook的按钮一样 这基本上是我在上一篇文章中提出的一个极好的解决方案的后续问题,我们的目的是在“以后观看”播放列表中添加一个视频 此特定功能的工作代码为:Javascript 将视频添加到用户';YouTube上最喜爱/喜欢的播放列表,javascript,php,video,youtube,youtube-api,Javascript,Php,Video,Youtube,Youtube Api,其目的是使用YouTube API创建一个Favorite/Like按钮。当用户单击该按钮时,视频将保存到用户喜爱/喜欢的播放列表中 就像你在自己的网站上实现类似Facebook的按钮一样 这基本上是我在上一篇文章中提出的一个极好的解决方案的后续问题,我们的目的是在“以后观看”播放列表中添加一个视频 此特定功能的工作代码为: <!-- button 1 --> <button type="submit" data-youtube-video-id="EH3gqI2NAiE" v
<!-- button 1 -->
<button type="submit" data-youtube-video-id="EH3gqI2NAiE" value="Watch Later" class="ma_youtube_watch_later" name="send">
<div class="ma_youtube_watch_later_text">Watch Later</div>
</button>
<!-- button 2 -->
<button type="submit" data-youtube-video-id="0EMmKIIF-zE" value="Watch Later" class="ma_youtube_watch_later" name="send">
<div class="ma_youtube_watch_later_text">Watch Later</div>
</button>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
// By Bertrand Martel: https://stackoverflow.com/a/42561941/1649673
var OAUTH2_CLIENT_ID = '28993181493-c9o6hdll3di0ssvebfd4atf13edqfu9g.apps.googleusercontent.com';
var OAUTH2_SCOPES = [
'https://www.googleapis.com/auth/youtube'
];
var init = false;
var youtube_video_id = '';
var button = null;
googleApiClientReady = function() {
gapi.auth.init(function() {
window.setTimeout(checkAuth, 1);
});
}
function checkAuth() {
gapi.auth.authorize({
client_id: OAUTH2_CLIENT_ID,
scope: OAUTH2_SCOPES,
immediate: true
}, handleAuthResult);
}
// Handle the result of a gapi.auth.authorize() call.
function handleAuthResult(authResult) {
jQuery('.ma_youtube_watch_later').off('click');
jQuery('.ma_youtube_watch_later').click(function(e) {
button = this;
var youtube_video_id = jQuery(this).attr("data-youtube-video-id");
// Add a video ID specified in the form to the playlist.
function addVideoToPlaylist() {
//addToPlaylist(jQuery('#video-id').val());
addToPlaylist(youtube_video_id);
}
if (authResult && !authResult.error) {
addVideoToPlaylist();
} else {
init = true;
gapi.auth.authorize({
client_id: OAUTH2_CLIENT_ID,
scope: OAUTH2_SCOPES,
immediate: false
}, handleAuthResult);
}
return false;
});
if (authResult && !authResult.error) {
// Authorization was successful. Hide authorization prompts and show
// content that should be visible after authorization succeeds.
jQuery('.pre-auth').hide();
jQuery('.post-auth').show();
loadAPIClientInterfaces();
jQuery('#add_to_wl').click(function(e) {
button = this;
addVideoToPlaylist(self);
});
}
}
function loadAPIClientInterfaces() {
gapi.client.load('youtube', 'v3', function() {
if (init) {
init = false;
addVideoToPlaylist();
}
});
}
// Add a video to a playlist. The "startPos" and "endPos" values let you
// start and stop the video at specific times when the video is played as
// part of the playlist. However, these values are not set in this example.
function addToPlaylist(id, startPos, endPos) {
var details = {
videoId: id,
kind: 'youtube#video'
}
if (startPos != undefined) {
details['startAt'] = startPos;
}
if (endPos != undefined) {
details['endAt'] = endPos;
}
var request = gapi.client.youtube.playlistItems.insert({
part: 'snippet',
resource: {
snippet: {
playlistId: "WL",
resourceId: details
}
}
});
request.execute(function(response) {
console.log(response);
if (!response.code) {
//jQuery('#status').html('<pre>Succesfully added the video : ' + JSON.stringify(response.result) + '</pre>');
// change button text
$(button).text('Video added');
} else if (response.code == 409) {
//jQuery('#status').html('<p>Conflict : this video is already on your Watch Later playlist</p>');
// change button text
$(button).text('Already added');
} else if (response.code == 404) {
//jQuery('#status').html('<p>Not Found : this video hasnt been found</p>');
// change button text
$(button).text('Video not found');
} else {
//jQuery('#status').html('<p>Error : code ' + response.code + '</p>');
// change button text
$(button).text('Error: Try again');
}
});
}
</script>
<script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>
晚点看
晚点看
//伯特兰·马特尔:https://stackoverflow.com/a/42561941/1649673
var OAUTH2_CLIENT_ID='28993181493-c9o6hdll3di0ssvebfd4atf13edqfu9g.apps.googleusercontent.com';
变量OAUTH2_作用域=[
'https://www.googleapis.com/auth/youtube'
];
var init=false;
var youtube_video_id='';
var按钮=null;
googleapiclientraday=函数(){
gapi.auth.init(函数(){
setTimeout(checkAuth,1);
});
}
函数checkAuth(){
gapi.auth.authorize({
客户端id:OAUTH2\u客户端id,
作用域:OAUTH2_作用域,
立即:对
},handleAuthResult);
}
//处理gapi.auth.authorize()调用的结果。
函数handleAuthResult(authResult){
jQuery('.ma_youtube_watch_later')。关闭('click');
jQuery('.ma_youtube_watch_later')。单击(函数(e){
按钮=这个;
var youtube_video_id=jQuery(this).attr(“数据youtube视频id”);
//将表单中指定的视频ID添加到播放列表中。
函数addVideoToPlaylist(){
//addToPlaylist(jQuery('#video id').val());
addToPlaylist(youtube\u video\u id);
}
if(authResult&!authResult.error){
addVideoToPlaylist();
}否则{
init=真;
gapi.auth.authorize({
客户端id:OAUTH2\u客户端id,
作用域:OAUTH2_作用域,
即时:假
},handleAuthResult);
}
返回false;
});
if(authResult&!authResult.error){
//授权成功。隐藏授权提示并显示
//授权成功后应可见的内容。
jQuery('.pre auth').hide();
jQuery('.post auth').show();
loadAPIClientInterfaces();
jQuery(“#将_添加到_wl”)。单击(函数(e){
按钮=这个;
添加视频播放列表(self);
});
}
}
函数loadAPIClientInterfaces(){
load('youtube','v3',function(){
if(init){
init=false;
addVideoToPlaylist();
}
});
}
//将视频添加到播放列表中。“startPos”和“endPos”值允许您
//在播放视频时的特定时间启动和停止视频
//播放列表的一部分。但是,本例中未设置这些值。
函数addToPlaylist(id、startPos、endPos){
变量详细信息={
视频id:id,
种类:“youtube#视频”
}
if(startPos!=未定义){
详细信息['startAt']=startPos;
}
如果(endPos!=未定义){
详细信息['endAt']=endPos;
}
var request=gapi.client.youtube.playlitems.insert({
部分:'代码片段',
资源:{
片段:{
播放ID:“WL”,
resourceId:详细信息
}
}
});
请求.执行(函数(响应){
控制台日志(响应);
如果(!response.code){
//jQuery('#status').html('成功添加视频:'+JSON.stringify(response.result)+'');
//更改按钮文本
$(按钮)。文本(“添加视频”);
}else if(response.code==409){
//jQuery(“#status”).html(“冲突:此视频已在您稍后观看的播放列表中””;
//更改按钮文本
$(按钮).text('已添加');
}else if(response.code==404){
//jQuery(“#status”).html(“未找到:未找到此视频””;
//更改按钮文本
$(按钮)。文本(“未找到视频”);
}否则{
//jQuery('#status').html('错误:code'+response.code+'');
//更改按钮文本
$(按钮).text('错误:重试');
}
});
}
我们有很多关于API文档的信息。我们也有一些有关的文档
如何使用PHP或/和javascript实现这一点 您可以通过具有以下参数的频道列表端点找到喜欢的播放列表ID(&F): 您将在
relatedPlaylists
中获得播放列表,包括likes
,收藏夹
,上传
,稍后观看
和观看历史
<!doctype html>
<html>
<head>
<title>Add to multiple playlists</title>
</head>
<body>
<input type="submit" data-youtube-video-id="EH3gqI2NAiE" data-type="WL" value="Add to Watch Later playlist" class="yt_add_to_playlist" />
<input type="submit" data-youtube-video-id="0EMmKIIF-z" data-type="likes" value="Add to Like playlist" class="yt_add_to_playlist" />
<input type="submit" data-youtube-video-id="T4ZE2KtoFzs" data-type="favorites" value="Add to Favorite playlist" class="yt_add_to_playlist" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
var OAUTH2_CLIENT_ID = '28993181493-c9o6hdll3di0ssvebfd4atf13edqfu9g.apps.googleusercontent.com';
var OAUTH2_SCOPES = [
'https://www.googleapis.com/auth/youtube'
];
var init = false;
var button = null;
googleApiClientReady = function() {
gapi.auth.init(function() {
window.setTimeout(checkAuth, 1);
});
}
function checkAuth() {
gapi.auth.authorize({
client_id: OAUTH2_CLIENT_ID,
scope: OAUTH2_SCOPES,
immediate: true
}, handleAuthResult);
}
// Handle the result of a gapi.auth.authorize() call.
function handleAuthResult(authResult) {
jQuery('.yt_add_to_playlist').off('click');
jQuery('.yt_add_to_playlist').click(function(e) {
button = this;
if (authResult && !authResult.error) {
addToPlaylist($(this).attr("data-youtube-video-id"), $(this).attr("data-type"));
} else {
init = true;
gapi.auth.authorize({
client_id: OAUTH2_CLIENT_ID,
scope: OAUTH2_SCOPES,
immediate: false
}, handleAuthResult);
}
return false;
});
if (authResult && !authResult.error) {
// Authorization was successful. Hide authorization prompts and show
// content that should be visible after authorization succeeds.
jQuery('.pre-auth').hide();
jQuery('.post-auth').show();
loadAPIClientInterfaces();
jQuery('#add_to_wl').click(function(e) {
button = this;
addToPlaylist($(this).attr("data-youtube-video-id"), $(this).attr("data-type"));
});
}
}
function loadAPIClientInterfaces() {
gapi.client.load('youtube', 'v3', function() {
if (init) {
init = false;
addToPlaylist($(button).attr("data-youtube-video-id"), $(button).attr("data-type"));
}
});
}
function addToPlaylist(videoId, playlistType) {
console.log("add to playlist type : " + playlistType);
if (playlistType != "WL" && playlistType != "HL") {
var request = gapi.client.youtube.channels.list({
mine: true,
part: 'contentDetails'
});
request.execute(function(response) {
var playlistId = response.result.items[0].contentDetails.relatedPlaylists[playlistType];
if (typeof playlistId != 'undefined') {
console.log("found playlist id : " + playlistId);
insertToPlaylist(videoId, playlistId);
} else {
console.log("playlist not found");
}
});
} else {
insertToPlaylist(videoId, playlistType);
}
}
function insertToPlaylist(videoId, playlistId) {
var details = {
videoId: videoId,
kind: 'youtube#video'
};
var request = gapi.client.youtube.playlistItems.insert({
part: 'snippet',
resource: {
snippet: {
playlistId: playlistId,
resourceId: details
}
}
});
request.execute(function(response) {
console.log(response);
if (!response.code) {
$(button).val('Video added');
} else if (response.code == 409) {
$(button).val('Already added');
} else if (response.code == 404) {
$(button).val('Video not found');
} else {
$(button).val('Error: Try again');
}
});
}
</script>
<script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>
</body>
</html>
对于WatchLater和WatchHistory,所有用户的播放ID都相同(分别为WL和HL)
您可以使用gapi.client.youtube.channels.list
调用Javascript中的频道列表端点,方法与调用播放列表插入API相同
然后,使用PlayID,您可以将视频插入另一个播放列表,而不是稍后观看
在下面的代码中,您将找到3个按钮,用于将不同的视频添加到以后观看
播放列表,如
播放列表&收藏
播放列表
Javascript 是一个现场演示(如下所示) 这是一把小提琴。在开发人员控制台中替换客户端id并添加为授权的JavaScript源代码: php脚本:
感谢您抽出时间来整理这些内容,谢谢。这周我要测试一下。我有一个问题。是否可以同时将视频添加到多个播放列表中?例如,在type data属性值中,我们添加了一个数组,如data type=“WL,likes”
,视频被添加到这些播放列表中。不确定YouTube是否对此进行了某种形式的阻止。我不这么认为,它没有实现大容量插入(在使用数组时,playlid
字段需要一个对象,它只考虑第一项)。您需要连续插入2个播放列表
{
"kind": "youtube#channelListResponse",
"etag": "\"m2yskBQFythfE4irbTIeOgYYfBU/S1x68O9aSpvmndklrnSwKw_yYdE\"",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 1
},
"items": [{
"kind": "youtube#channel",
"etag": "\"m2yskBQFythfE4irbTIeOgYYfBU/ura_vsrPt5tCZkjjGbH3ihN3Bq4\"",
"id": "UCnQt5EmYRfX1uVYtwPNj7Dg",
"contentDetails": {
"relatedPlaylists": {
"likes": "LLnQt5EmYRfX1uVYtwPNj7Dg",
"favorites": "FLnQt5EmYRfX1uVYtwPNj7Dg",
"uploads": "UUnQt5EmYRfX1uVYtwPNj7Dg",
"watchHistory": "HL",
"watchLater": "WL"
}
}
}]
}
<!doctype html>
<html>
<head>
<title>Add to multiple playlists</title>
</head>
<body>
<input type="submit" data-youtube-video-id="EH3gqI2NAiE" data-type="WL" value="Add to Watch Later playlist" class="yt_add_to_playlist" />
<input type="submit" data-youtube-video-id="0EMmKIIF-z" data-type="likes" value="Add to Like playlist" class="yt_add_to_playlist" />
<input type="submit" data-youtube-video-id="T4ZE2KtoFzs" data-type="favorites" value="Add to Favorite playlist" class="yt_add_to_playlist" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
var OAUTH2_CLIENT_ID = '28993181493-c9o6hdll3di0ssvebfd4atf13edqfu9g.apps.googleusercontent.com';
var OAUTH2_SCOPES = [
'https://www.googleapis.com/auth/youtube'
];
var init = false;
var button = null;
googleApiClientReady = function() {
gapi.auth.init(function() {
window.setTimeout(checkAuth, 1);
});
}
function checkAuth() {
gapi.auth.authorize({
client_id: OAUTH2_CLIENT_ID,
scope: OAUTH2_SCOPES,
immediate: true
}, handleAuthResult);
}
// Handle the result of a gapi.auth.authorize() call.
function handleAuthResult(authResult) {
jQuery('.yt_add_to_playlist').off('click');
jQuery('.yt_add_to_playlist').click(function(e) {
button = this;
if (authResult && !authResult.error) {
addToPlaylist($(this).attr("data-youtube-video-id"), $(this).attr("data-type"));
} else {
init = true;
gapi.auth.authorize({
client_id: OAUTH2_CLIENT_ID,
scope: OAUTH2_SCOPES,
immediate: false
}, handleAuthResult);
}
return false;
});
if (authResult && !authResult.error) {
// Authorization was successful. Hide authorization prompts and show
// content that should be visible after authorization succeeds.
jQuery('.pre-auth').hide();
jQuery('.post-auth').show();
loadAPIClientInterfaces();
jQuery('#add_to_wl').click(function(e) {
button = this;
addToPlaylist($(this).attr("data-youtube-video-id"), $(this).attr("data-type"));
});
}
}
function loadAPIClientInterfaces() {
gapi.client.load('youtube', 'v3', function() {
if (init) {
init = false;
addToPlaylist($(button).attr("data-youtube-video-id"), $(button).attr("data-type"));
}
});
}
function addToPlaylist(videoId, playlistType) {
console.log("add to playlist type : " + playlistType);
if (playlistType != "WL" && playlistType != "HL") {
var request = gapi.client.youtube.channels.list({
mine: true,
part: 'contentDetails'
});
request.execute(function(response) {
var playlistId = response.result.items[0].contentDetails.relatedPlaylists[playlistType];
if (typeof playlistId != 'undefined') {
console.log("found playlist id : " + playlistId);
insertToPlaylist(videoId, playlistId);
} else {
console.log("playlist not found");
}
});
} else {
insertToPlaylist(videoId, playlistType);
}
}
function insertToPlaylist(videoId, playlistId) {
var details = {
videoId: videoId,
kind: 'youtube#video'
};
var request = gapi.client.youtube.playlistItems.insert({
part: 'snippet',
resource: {
snippet: {
playlistId: playlistId,
resourceId: details
}
}
});
request.execute(function(response) {
console.log(response);
if (!response.code) {
$(button).val('Video added');
} else if (response.code == 409) {
$(button).val('Already added');
} else if (response.code == 404) {
$(button).val('Video not found');
} else {
$(button).val('Error: Try again');
}
});
}
</script>
<script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>
</body>
</html>
composer require google/apiclient:~2.0
<?php
/**
* 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();
$response = "";
/*
* 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 = 'YOUR_CLIENT_ID';
$OAUTH2_CLIENT_SECRET = 'YOUR_CLIENT_SECRET';
$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()) {
try {
$videoId = "";
if (isset($_GET['video'])){
$videoId = $_GET['video'];
}
else if(isset($_SESSION['video'])){
$videoId = $_SESSION['video'];
}
if (isset($_GET['action'])){
$action = $_GET['action'];
}
else if(isset($_SESSION['action'])){
$action = $_SESSION['action'];
}
if(isset($videoId) && isset($action) && !isset($_GET['state'])) {
file_put_contents('php://stderr', print_r("adding video to watch later playlist " . $videoId . "\n", TRUE));
if ($action == "Add to Watch Later playlist") {
$playlistId = "WL";
}
else {
$listResponse = $youtube->channels->listChannels("contentDetails", array(
'mine' => true
));
if (!empty($listResponse)) {
if ($action == "Add to Like playlist"){
$playlistId = $listResponse['items'][0]['contentDetails']['relatedPlaylists']['likes'];
}
else if ($action == "Add to Favorite playlist"){
$playlistId = $listResponse['items'][0]['contentDetails']['relatedPlaylists']['favorites'];
}
}
}
if (isset($playlistId)){
// 5. Add a video to the playlist. First, define the resource being added
// to the playlist by setting its video ID and kind.
$resourceId = new Google_Service_YouTube_ResourceId();
$resourceId->setVideoId($videoId);
$resourceId->setKind('youtube#video');
// Then define a snippet for the playlist item. Set the playlist item's
// title if you want to display a different value than the title of the
// video being added. Add the resource ID and the playlist ID retrieved
// in step 4 to the snippet as well.
$playlistItemSnippet = new Google_Service_YouTube_PlaylistItemSnippet();
$playlistItemSnippet->setTitle('First video in the test playlist');
$playlistItemSnippet->setPlaylistId($playlistId);
$playlistItemSnippet->setResourceId($resourceId);
// Finally, create a playlistItem resource and add the snippet to the
// resource, then call the playlistItems.insert method to add the playlist
// item.
$playlistItem = new Google_Service_YouTube_PlaylistItem();
$playlistItem->setSnippet($playlistItemSnippet);
$playlistItemResponse = $youtube->playlistItems->insert(
'snippet,contentDetails', $playlistItem, array());
$response = json_encode($playlistItem);
}
else{
$response = "no playlist selected";
}
$_SESSION['video'] = "";
$_SESSION["action"] = "";
}
else{
file_put_contents('php://stderr', print_r("no video was specified", TRUE));
}
} catch (Google_Service_Exception $e) {
$response = htmlspecialchars($e->getMessage());
} catch (Google_Exception $e) {
$response = htmlspecialchars($e->getMessage());
}
$_SESSION[$tokenSessionKey] = $client->getAccessToken();
} else {
if(isset($_GET['video'])){
$_SESSION["video"] = $_GET['video'];
$_SESSION["action"] = $_GET['action'];
// If the user hasn't authorized the app, initiate the OAuth flow
$state = mt_rand();
$client->setState($state);
$_SESSION['state'] = $state;
$authUrl = $client->createAuthUrl();
header('Location: ' . $authUrl);
}
}
?>
<!doctype html>
<html>
<head>
<title>Add to playlists</title>
</head>
<body>
<div>
<form id="form" action="multi-playlist.php"">
<input type="hidden" name="video" value="EH3gqI2NAiE">
<input name="action" type="submit" value="Add to Watch Later playlist" />
<input name="action" type="submit" value="Add to Like playlist" />
<input name="action" type="submit" value="Add to Favorite playlist" />
</form>
<div>
<?php echo $response ?>
</div>
</div>
</body>
</html>