将视频添加到 YouTube 上用户的收藏/喜欢播放列表 [英] Add video to user's Favorite/Like playlist on YouTube

查看:41
本文介绍了将视频添加到 YouTube 上用户的收藏/喜欢播放列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目的是使用 YouTube API 创建收藏/喜欢按钮.当用户单击该按钮时,视频将保存到用户的收藏/喜欢播放列表中.

就像在您自己的网站上实现 Facebook 点赞按钮一样.

这基本上是对 Bertrand Martel 在我之前的 问题 我们旨在将视频添加到稍后观看"播放列表.

这个特定函数的工作代码是:

<button type="submit" data-youtube-video-id="EH3gqI2NAiE" value="稍后观看" class="ma_youtube_watch_later" name="send"><div class="ma_youtube_watch_later_text">稍后观看</div><!-- 按钮 2 --><button type="submit" data-youtube-video-id="0EMmKIIF-zE" value="稍后观看" class="ma_youtube_watch_later" name="send"><div class="ma_youtube_watch_later_text">稍后观看</div><script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script><脚本>//伯特兰·马特尔:https://stackoverflow.com/a/42561941/1649673var OAUTH2_CLIENT_ID = '28993181493-c9o6hdll3di0ssvebfd4atf13edqfu9g.apps.googleusercontent.com';var OAUTH2_SCOPES = ['https://www.googleapis.com/auth/youtube'];无功初始化=假;var youtube_video_id = '';var 按钮 = null;googleApiClientReady = 函数(){gapi.auth.init(函数(){window.setTimeout(checkAuth, 1);});}函数 checkAuth() {gapi.auth.authorize({client_id:OAUTH2_CLIENT_ID,范围:OAUTH2_SCOPES,立即:真}, handleAuthResult);}//处理 gapi.auth.authorize() 调用的结果.函数 handleAuthResult(authResult) {jQuery('.ma_youtube_watch_later').off('click');jQuery('.ma_youtube_watch_later').click(function(e) {按钮 = 这个;var youtube_video_id = jQuery(this).attr("data-youtube-video-id");//将表单中指定的视频 ID 添加到播放列表中.函数 addVideoToPlaylist() {//addToPlaylist(jQuery('#video-id').val());addToPlaylist(youtube_video_id);}如果 (authResult && !authResult.error) {addVideoToPlaylist();} 别的 {初始化 = 真;gapi.auth.authorize({client_id:OAUTH2_CLIENT_ID,范围:OAUTH2_SCOPES,立即:假}, handleAuthResult);}返回假;});如果 (authResult && !authResult.error) {//授权成功.隐藏授权提示并显示//授权成功后应该可见的内容.jQuery('.pre-auth').hide();jQuery('.post-auth').show();loadAPIClientInterfaces();jQuery('#add_to_wl').click(function(e) {按钮 = 这个;addVideoToPlaylist(self);});}}函数 loadAPIClientInterfaces() {gapi.client.load('youtube', 'v3', function() {如果(初始化){初始化 = 假;addVideoToPlaylist();}});}//将视频添加到播放列表.startPos"和endPos"值让你//在视频播放时的特定时间开始和停止视频//播放列表的一部分.但是,在本示例中未设置这些值.函数 addToPlaylist(id, startPos, endPos) {变量详细信息 = {视频ID:ID,种类:'youtube#video'}如果(开始位置!= 未定义){详细信息['startAt'] = startPos;}如果(endPos != 未定义){详细信息['endAt'] = endPos;}var request = gapi.client.youtube.playlistItems.insert({部分:'片段',资源:{片段:{播放列表 ID:WL",资源 ID:详细信息}}});请求.执行(功能(响应){控制台日志(响应);如果(!响应代码){//jQuery('#status').html('<pre>添加视频成功:' + JSON.stringify(response.result) + '</pre>');//改变按钮文字$(button).text('添加视频');} else if (response.code == 409) {//jQuery('#status').html('<p>Conflict : 此视频已在您的稍后观看"播放列表中</p>');//改变按钮文字$(button).text('已经添加');} else if (response.code == 404) {//jQuery('#status').html('<p>Not Found : 这个视频还没有被找到</p>');//改变按钮文字$(button).text('找不到视频');} 别的 {//jQuery('#status').html('<p>Error : code ' + response.code + '</p>');//改变按钮文字$(button).text('错误:再试一次');}});}<script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>

我们在 API 文档中有许多 PHP 代码示例.我们还有一些关于将视频添加到播放列表的文档.

如何使用 PHP 或/和 javascript 实现这一点?

解决方案

你可以找到 Like &带有以下参数的频道列表端点的收藏夹播放列表 ID(检查 此示例请求) :

<代码>{我的:真的,部分:'内容详细信息'}

您将在relatedPlaylists 中获得播放列表列表,包括likesfavoritesuploads稍后观看观看历史.

<代码>{"kind": "youtube#channelListResponse","etag": "\"m2yskBQFythfE4irbTIeOgYYfBU/S1x68O9aSpvmndklrnSwKw_yYdE\"",页面信息":{总结果":1,每页结果":1},项目": [{"kind": "youtube#channel","etag": "\"m2yskBQFythfE4irbTIeOgYYfBU/ura_vsrPt5tCZkjjGbH3ihN3Bq4\"","id": "UCnQt5EmYRfX1uVYtwPNj7Dg",内容详细信息":{相关播放列表":{"喜欢": "LLnQt5EmYRfX1uVYtwPNj7Dg","收藏夹": "FLnQt5EmYRfX1uVYtwPNj7Dg","上传": "UUnQt5EmYRfX1uVYtwPNj7Dg","watchHistory": "HL","watchLater": "WL"}}}]}

对于WatchLater &WatchHistory,所有用户(分别是WL & HL)的playlistId都是相同的

您可以使用 gapi.client.youtube.channels.list 在 Javascript 中调用频道列表端点,就像调用播放列表插入 API 一样.

然后使用播放列表 ID,您可以将视频插入到另一个播放列表中,而不是稍后观看.

在下面的代码中,您会发现 3 个按钮可以将不同的视频添加到 Watch Later 播放列表、Like 播放列表 &收藏夹播放列表

<小时>

Javascript

这里是带有源代码(如下)

这里是一个小提琴.替换您的客户端 ID 并在开发者控制台中添加为 Authorized JavaScript origins :https://fiddle.jshell.net>

<头><title>添加到多个播放列表</title><身体><input type="submit" data-youtube-video-id="EH3gqI2NAiE" data-type="WL" value="添加到稍后观看播放列表" class="yt_add_to_playlist"/><input type="submit" data-youtube-video-id="0EMmKIIF-z" data-type="likes" value="添加到喜欢的播放列表" class="yt_add_to_playlist"/><input type="submit" data-youtube-video-id="T4ZE2KtoFzs" data-type="favorites" value="添加到收藏夹播放列表" class="yt_add_to_playlist"/><script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script><脚本>var OAUTH2_CLIENT_ID = '28993181493-c9o6hdll3di0ssvebfd4atf13edqfu9g.apps.googleusercontent.com';var OAUTH2_SCOPES = ['https://www.googleapis.com/auth/youtube'];无功初始化=假;var 按钮 = null;googleApiClientReady = 函数(){gapi.auth.init(函数(){window.setTimeout(checkAuth, 1);});}函数 checkAuth() {gapi.auth.authorize({client_id:OAUTH2_CLIENT_ID,范围:OAUTH2_SCOPES,立即:真实}, handleAuthResult);}//处理 gapi.auth.authorize() 调用的结果.函数 handleAuthResult(authResult) {jQuery('.yt_add_to_playlist').off('click');jQuery('.yt_add_to_playlist').click(function(e) {按钮 = 这个;如果 (authResult && !authResult.error) {addToPlaylist($(this).attr("data-youtube-video-id"), $(this).attr("data-type"));} 别的 {初始化 = 真;gapi.auth.authorize({client_id:OAUTH2_CLIENT_ID,范围:OAUTH2_SCOPES,立即:假}, handleAuthResult);}返回假;});如果 (authResult && !authResult.error) {//授权成功.隐藏授权提示并显示//授权成功后应该可见的内容.jQuery('.pre-auth').hide();jQuery('.post-auth').show();loadAPIClientInterfaces();jQuery('#add_to_wl').click(function(e) {按钮 = 这个;addToPlaylist($(this).attr("data-youtube-video-id"), $(this).attr("data-type"));});}}函数 loadAPIClientInterfaces() {gapi.client.load('youtube', 'v3', function() {如果(初始化){初始化 = 假;addToPlaylist($(button).attr("data-youtube-video-id"), $(button).attr("data-type"));}});}函数 addToPlaylist(videoId, playlistType) {console.log("添加到播放列表类型:" + playlistType);if (playlistType != "WL" && playlistType != "HL") {var request = gapi.client.youtube.channels.list({我的:真的,部分:'内容详细信息'});请求.执行(功能(响应){var playlistId = response.result.items[0].contentDetails.relatedPlaylists[playlistType];if (typeof playlistId != 'undefined') {console.log("找到播放列表ID:" + playlistId);insertToPlaylist(videoId, playlistId);} 别的 {console.log("找不到播放列表");}});} 别的 {insertToPlaylist(videoId, playlistType);}}函数 insertToPlaylist(videoId, playlistId) {变量详细信息 = {视频ID:视频ID,种类:'youtube#video'};var request = gapi.client.youtube.playlistItems.insert({部分:'片段',资源:{片段:{播放列表 ID:播放列表 ID,资源 ID:详细信息}}});请求.执行(功能(响应){控制台日志(响应);如果(!响应代码){$(button).val('添加视频');} else if (response.code == 409) {$(button).val('已经添加');} else if (response.code == 404) {$(button).val('找不到视频');} 别的 {$(button).val('错误:再试一次');}});}<script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script></html>

OAUTH2_CLIENT_ID 替换为您自己的客户端 ID

在 API 响应中,如果未找到视频 (404),则会检查状态代码.如果视频已在播放列表中但仅用于稍后观看播放列表(将现有视频添加到喜欢/收藏播放列表不会改变任何内容),则返回 409 状态代码

<小时>

PHP

和之前一样,基于 google-api php 示例 :

  • 安装 composer :请参阅说明
  • 安装 google-api 客户端:

    composer 需要 google/apiclient:~2.0

php 脚本 多播放列表.php :

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);//定义一个将用于发出所有 API 请求的对象.$youtube = 新 Google_Service_YouTube($client);//检查所需范围是否存在身份验证令牌$tokenSessionKey = 'token-' .$client->prepareScopes();if (isset($_GET['code'])) {if (strval($_SESSION['state']) !== strval($_GET['state'])) {die('会话状态不匹配.');}$client->authenticate($_GET['code']);$_SESSION[$tokenSessionKey] = $client->getAccessToken();header('位置:' . $redirect);}如果(isset($_SESSION[$tokenSessionKey])){$client->setAccessToken($_SESSION[$tokenSessionKey]);}//检查以确保成功获取访问令牌.如果 ($client->getAccessToken()) {尝试 {$videoId = "";if (isset($_GET['video'])){$videoId = $_GET['video'];}否则 if(isset($_SESSION['video'])){$videoId = $_SESSION['video'];}if (isset($_GET['action'])){$action = $_GET['action'];}否则 if(isset($_SESSION['action'])){$action = $_SESSION['action'];}if(isset($videoId) &&isset($action) && !isset($_GET['state'])) {file_put_contents('php://stderr', print_r("添加视频以稍后观看播放列表" . $videoId . "\n", TRUE));if ($action == "Add to Watch later playlist") {$playlistId = "WL";}别的 {$listResponse = $youtube->channels->listChannels("contentDetails", array('我的' =>真的));如果 (!empty($listResponse)) {if ($action == "添加到喜欢的播放列表"){$playlistId = $listResponse['items'][0]['contentDetails']['relatedPlaylists']['likes'];}else if ($action == "添加到收藏夹播放列表"){$playlistId = $listResponse['items'][0]['contentDetails']['relatedPlaylists']['favorites'];}}}如果(isset($playlistId)){//5. 将视频添加到播放列表中.首先,定义要添加的资源//通过设置视频 ID 和种类到播放列表.$resourceId = new Google_Service_YouTube_ResourceId();$resourceId->setVideoId($videoId);$resourceId->setKind('youtube#video');//然后为播放列表项定义一个片段.设置播放列表项的//title 如果你想显示一个与标题不同的值//正在添加视频.添加资源ID和检索到的播放列表ID//在第 4 步中也到代码段.$playlistItemSnippet = new Google_Service_YouTube_PlaylistItemSnippet();$playlistItemSnippet->setTitle('测试播放列表中的第一个视频');$playlistItemSnippet->setPlaylistId($playlistId);$playlistItemSnippet->setResourceId($resourceId);//最后,创建一个 playlistItem 资源并将代码片段添加到//资源,然后调用 playlistItems.insert 方法添加播放列表//物品.$playlistItem = new Google_Service_YouTube_PlaylistItem();$playlistItem->setSnippet($playlistItemSnippet);$playlistItemResponse = $youtube->playlistItems->insert('snippet,contentDetails', $playlistItem, array());$response = json_encode($playlistItem);}别的{$response = "没有选择播放列表";}$_SESSION['video'] = "";$_SESSION["action"] = "";}别的{file_put_contents('php://stderr', print_r("没有指定视频", TRUE));}} catch (Google_Service_Exception $e) {$response = htmlspecialchars($e->getMessage());} catch (Google_Exception $e) {$response = htmlspecialchars($e->getMessage());}$_SESSION[$tokenSessionKey] = $client->getAccessToken();} 别的 {if(isset($_GET['video'])){$_SESSION["video"] = $_GET['video'];$_SESSION["action"] = $_GET['action'];//如果用户尚未授权应用程序,则启动 OAuth 流程$state = mt_rand();$client->setState($state);$_SESSION['state'] = $state;$authUrl = $client->createAuthUrl();header('位置:'.$authUrl);}}?><!doctype html><头><title>添加到播放列表</title><身体><div><form id="form" action="multi-playlist.php""><input type="hidden" name="video" value="EH3gqI2NAiE"><input name="action" type="submit" value="添加到稍后观看播放列表"/><input name="action" type="submit" value="添加到喜欢的播放列表"/><input name="action" type="submit" value="添加到收藏夹播放列表"/></表单><div><?php echo $response ?>

</html>

对于这个PHP版本,注意除了当前session中的video id$_SESSION["video"]之外,目标action也存储在$_SESSION["action"] 能够确定使用哪个播放列表.使用带有 $youtube->channels->listChannels 的频道列表端点检索播放列表.

<小时>

请注意,视频显示在播放列表中可能需要一些时间(有时需要几秒钟)

The aim is to create a Favorite/Like button using the YouTube API. When a user clicks the button, the video is saved into the user's Favorite/Like playlist.

Just like how it works when you implement a Facebook like button on your own site.

This is essentially a follow up question to the fantastic solution posted by Bertrand Martel on my previous question where we aimed to add a video to the Watch Later playlist.

The working code for this particular function is:

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

And we have a number of PHP code samples on the API docs. We also have some documentation on adding a video to playlist.

How can this be achieved using either PHP or/and javascript?

解决方案

You can find Like & Favorite playlist ID with channel list endpoint with the following parameters (check this sample request) :

{
    mine: true,
    part: 'contentDetails'
}

You will get the list of playlists in relatedPlaylists including likes, favorites, uploads, watch later and watch history.

{
    "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"
            }
        }
    }]
}

For WatchLater & WatchHistory, the playlistId is the same for all users (respectively WL & HL)

You can call channel list endpoint in Javascript with gapi.client.youtube.channels.list the same way as you've called the playlist insert API.

Then with the playlistId you can insert your video to another playlist than Watch Later.

In the following code, you will find 3 buttons to add different videos to Watch Later playlist, Like playlist & Favorite playlist


Javascript

Here is a live demo with the source code (as below)

Here is a fiddle. Replace your client id and add as Authorized JavaScript origins in developer console : https://fiddle.jshell.net

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

Replace OAUTH2_CLIENT_ID with your own client ID

In the API response, the status code is checked in case the video is not found (404). The 409 status code is returned if the video is already in the playlist but only for watch later playlist (adding an existing video to like/favorite playlist will not changed anything though)


PHP

The same as before, based on google-api php sample :

  • install composer : see instructions
  • install google-api client :

    composer require google/apiclient:~2.0
    

The php script multi-playlist.php :

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

For this PHP version, note that in addition to the video id in the current session $_SESSION["video"], the target action is also stored in $_SESSION["action"] to be able to determine which playlist to use. Playlists are retrieved with channel list endpoint with $youtube->channels->listChannels.


Note that it can take some time for the video to appear in the playlists (sometimes a few seconds)

这篇关于将视频添加到 YouTube 上用户的收藏/喜欢播放列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
PHP最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆