如何通过YouTube API保存和检索自定义元数据字段

时间:2019-08-24 17:39:03

标签: youtube youtube-api youtube-data-api youtube-javascript-api

我想将字符串存储为播放列表的每个YouTube视频中的自定义字段。

(具体来说,我的网站检索了该播放列表,并显示了每个视频的缩略图,我想在每个图像下显示一个报价。)

我从https://developers.google.com/youtube/v3/docs/playlistItems/list的文档中知道,我可以通过执行以下操作来检索YouTube播放列表的详细信息:

$service = new Google_Service_YouTube($client);
$queryParams = [
    'maxResults' => 50,
    'playlistId' => '{myID}'
];
$response = $service->playlistItems->listPlaylistItems('id,snippet,contentDetails,status', $queryParams);

但是从那些文档和https://developers.google.com/youtube/v3/docs/videos以及其他文档中,我还没有看到如何保存任何自定义字段。

我想我可以使用“描述”字段,但这并不理想,因为我希望面向公众的描述独立于我要保存的自定义字符串字段。

您将如何建议实现我的目标(最好不要创建自己的数据库)?

1 个答案:

答案 0 :(得分:0)

如果任何人都对“说明”字段感到满意,这就是我的选择,因为我没有发现更好的东西。

希望这段代码对某人有所帮助,并且我甚至希望有人能提供有关更好方法的答案。

<?php

namespace App\Helpers;

use Cache;
use \Google_Client as Google_Client;
use \Google_Service_YouTube as Google_Service_YouTube;

class YouTubeHelper {

    const CACHE_KEY_PREFIX = 'youtubePlayListCache_';
    const CACHE_TEMPLATE = self::CACHE_KEY_PREFIX . '{put playlist ID here}';

    /**
     * @param string $playlistId
     * @param int $maxResults
     * @return array
     */
    public static function getVideoIdsAndQuotations($playlistId, $maxResults = 50) {
        $result = [];
        /* @var $ytResponse \Google_Service_YouTube_PlaylistItemListResponse */
        $ytResponse = self::getPlaylistItemListResponse($playlistId, $maxResults);
        foreach ($ytResponse->getItems() as $item) {
            $videoId = $item->getContentDetails()->getVideoId();
            $desc = $item->getSnippet()->getDescription();
            $result[$videoId] = self::getQuotationFromDesc($desc);
        }
        return $result;
    }

    /**
     * 
     * @param string $desc
     * @return string
     */
    public static function getQuotationFromDesc($desc) {
        $lines = explode(PHP_EOL, $desc);
        $firstLine = $lines[0];
        $firstLineWithoutSurroundingQuotes = trim($firstLine, '"');
        return $firstLineWithoutSurroundingQuotes;
    }

    /**
     * @param string $playlistId
     * @param int $maxResults
     * @return \Google_Service_YouTube_PlaylistItemListResponse
     */
    public static function getPlaylistItemListResponse($playlistId, $maxResults = 50) {
        return Cache::rememberForever(self::CACHE_KEY_PREFIX . $playlistId, function()use ($playlistId, $maxResults) {
                    $client = self::getYouTubeClient();
                    $service = new Google_Service_YouTube($client); // Define service object for making API requests.
                    $queryParams = [
                        'maxResults' => $maxResults,
                        'playlistId' => $playlistId
                    ];
                    $response = $service->playlistItems->listPlaylistItems('id,snippet,contentDetails,status', $queryParams);
                    return $response;
                });
    }

    /**
     * @return Google_Client
     */
    public static function getYouTubeClient() {
        $client = new Google_Client();
        $client->setApplicationName('');
        $key = config('services.google.youtubeApiKey');
        $client->setDeveloperKey($key); //https://github.com/googleapis/google-api-php-client
        $client->setScopes(['https://www.googleapis.com/auth/youtube.readonly']);
        $headers = ['Referer' => config('app.url')];
        $guzzleClient = new \GuzzleHttp\Client(['headers' => $headers]);
        $client->setHttpClient($guzzleClient); //https://stackoverflow.com/a/44421003/470749
        return $client;
    }

}