如何通过 YouTube 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 以及其他文档中,我还没有看到如何保存任何自定义字段。

我想我可以使用"描述"字段,但这并不理想,因为我宁愿面向公众的描述独立于我想保存的这个自定义字符串字段。

您建议如何实现我的目标(理想情况下不创建自己的数据库)?

如果有人对使用"描述"字段感到满意,这就是我决定的,因为我没有找到更好的东西。

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

<?php
namespace AppHelpers;
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 GuzzleHttpClient(['headers' => $headers]);
$client->setHttpClient($guzzleClient); //https://stackoverflow.com/a/44421003/470749
return $client;
}
}

最新更新