0duddu / youtube-laravel-api
从alchemyguy/youtube-laravel-api分叉,这是一个基于YouTube Api v3的包装器,以Laravel的方式简化了功能。
1.1.1
2023-07-27 15:59 UTC
Requires
- php: ^8.0
- google/apiclient: ^2.0
- laravel/framework: ^9.0|^10.0
Requires (Dev)
This package is auto-updated.
Last update: 2024-09-27 18:32:41 UTC
README
PHP (Laravel) 包,用于Google / YouTube API V3以及Google Auth
功能
安装
composer require 0duddu/youtube-laravel-api
将服务提供者添加到config/app.php提供者数组中
ZeroDUDDU\YoutubeLaravelApi\YoutubeLaravelApiServiceProvider::class
执行以下命令以获取配置
php artisan vendor:publish --tag='youtube-config'
创建Google OAuth凭据的步骤
- 转到
https://console.developers.google.com
- 使用您的凭据登录,然后创建一个新项目。
- 在创建密钥时启用以下功能
- YouTube数据API
- YouTube分析API
- YouTube报告API
- 然后从凭据选项卡创建
API密钥
。 - 然后在OAuth同意屏幕中输入
产品名称
(您的站点名称)。 - 创建凭据>选择OAuth客户端ID。 (在这里您将获得client_id和client_secret)
- 然后在授权JavaScript来源部分添加
您的站点URL
。 - 在授权重定向URL部分添加
添加一个您希望认证代码返回的URL
(登录回调) - 您将获得值(确切地说 - client_id、client_secret和api_key)
- 然后将这些值 - client_id、client_secret、api_key和redirect_url添加到.env文件中,您现在可以开始使用此包了。
使用
Google Auth
- 添加代码以调用API类
<?php namespace Your\App\NameSpace; use ZeroDUDDU\YoutubeLaravelApi\AuthenticateService;
- 生成Auth-Url
$authObject = new AuthenticateService; # Replace the identifier with a unqiue identifier for account or channel $authUrl = $authObject->getLoginUrl('email','identifier');
- 获取认证代码和标识符 现在一旦用户通过访问该URL进行授权,认证代码将被重定向到.env中指定的redirect_url,参数为code(这将是被授权的代码)和state(这将是我们在制作loginUrl期间添加的标识符)
$code = $request->get('code'); $identifier = $request->get('state');
- 认证令牌和频道详情
$authObject = new AuthenticateService; $authResponse = $authObject->authChannelWithCode($code, true);
- 这将返回一个数组:
$authResponse['token'] (Channel Token)
$authResponse['channel_details']
$authResponse['live_streaming_status'] (enabled or disabled)
- 仅认证令牌
$authObject = new AuthenticateService; $authResponse = $authObject->authChannelWithCode($code, false);
- 这将返回一个数组:
$authResponse['token'] (Channel Token)
- 刷新令牌 如果您的令牌过期,它将使用刷新令牌进行刷新,并且可以通过在任意对象上调用
getNewToken()
来获取新令牌。如果没有获取到新令牌,它将返回null。
完整直播API
- 添加代码以调用API类
<?php namespace Your\App\NameSpace; use ZeroDUDDU\YoutubeLaravelApi\LiveStreamService;
- 创建YouTube事件
# data format creating live event $data = array( "thumbnail_path" => "", // Optional "event_start_date_time" => "", "event_end_date_time" => "", // Optional "time_zone" => "", 'privacy_status' => "", // default: "private" "language_name" => "", // default: "English" "tag_array" => "" // Optional and should not be more than 500 characters ); $ytEventObj = new LiveStreamService($authToken); /** * The broadcast function returns array of details from YouTube. * Store this information & will be required to supply to youtube * for live streaming using encoder of your choice. */ $response = $ytEventObj->broadcast($title, $description, $data); if ( !empty($response) ) { $youtubeEventId = $response['broadcast_response']['id']; $serverUrl = $response['stream_response']['cdn']->ingestionInfo->ingestionAddress; $serverKey = $response['stream_response']['cdn']->ingestionInfo->streamName; }
- 更新YouTube事件
$ytEventObj = new LiveStreamService($authToken); /** * The updateBroadcast response give details of the youtube_event_id,server_url and server_key. * The server_url & server_key gets updated in the process. (save the updated server_key and server_url). */ $response = $ytEventObj->updateBroadcast($data, $youtubeEventId); // $youtubeEventId = $response['broadcast_response']['id']; // $serverUrl = $response['stream_response']['cdn']->ingestionInfo->ingestionAddress; // $serverKey = $response['stream_response']['cdn']->ingestionInfo->streamName
- 删除YouTube事件
$ytEventObj = new LiveStreamService($authToken); # Deleting the event requires authentication token for the channel in which the event is created and the youtube_event_id $ytEventObj->deleteEvent($youtubeEventId);
- 启动YouTube事件流
$ytEventObj = new LiveStreamService($authToken); /** * $broadcastStatus - ["testing", "live"] * Starting the event takes place in 3 steps * 1. Start sending the stream to the server_url via server_key recieved as a response in creating the event via the encoder of your choice. * 2. Once stream sending has started, stream test should be done by passing $broadcastStatus="testing" & it will return response for stream status. * 3. If transitioEvent() returns successfull for testing broadcast status, then start live streaming your video by passing $broadcastStatus="live" * & in response it will return us the stream status. */ $streamStatus = $ytEventObj->transitionEvent($youtubeEventId, $broadcastStatus);
- 停止YouTube事件流
$ytEventObj = new LiveStreamService($authToken); /** * $broadcastStatus - ["complete"] * Once live streaming gets started succesfully. We can stop the streaming the video by passing broadcastStatus="complete" and in response it will give us the stream status. */ $ytEventObj->transitionEvent($youtubeEventId, $broadcastStatus); // $broadcastStatus = ["complete"]
YouTube完整频道API
- 添加代码以调用API类
<?php namespace Your\App\NameSpace; use ZeroDUDDU\YoutubeLaravelApi\ChannelService;
- 按频道ID获取频道详情 如果您想获取多个频道的详情,请在参数中用逗号(,)分隔频道ID
/** * [channelsListById -gets the channnel details and ] * $part 'id,snippet,contentDetails,status, statistics, contentOwnerDetails, brandingSettings' * $params [array channels id(comma separated ids ) or you can get ('forUsername' => 'GoogleDevelopers')] */ $part = 'id,snippet'; $params = array('id'=> 'channel_1_id,channel_2_id'); $channelServiceObject = new ChannelService($authToken); $channelDetails = $channelServiceObject->channelsListById($part, $params);
- 按令牌获取频道详情 已授权令牌的用户频道的详情
$channelServiceObject = new ChannelService; $channelDetails = $channelServiceObject->getChannelDetails($authToken);
- 频道订阅列表 频道的订阅列表
/* * $params array('channelId'=>'', 'totalResults'= 10) * totalResults is different of maxResults from Google Api. * totalResults = the amount of results you want * maxResults = max of results PER PAGE. We don't need this parameter here since it will loop until it gets all the results you want. */ $channelServiceObject = new ChannelService($authToken); $channelDetails = $channelServiceObject->subscriptionByChannelId($params);
- 为授权频道添加订阅
/* * properties array('snippet.resourceId.kind' => 'youtube#channel','snippet.resourceId.channelId' => 'UCqIOaYtQak4-FD2-yI7hFkw') */ $channelServiceObject = new ChannelService; $response = $channelServiceObject->addSubscriptions($properties, $token, $part='snippet', $params=[]);
-为授权频道移除订阅 要移除订阅,我们需要从订阅列表中找到订阅ID。
$response = $channelServiceObject->removeSubscription( $token, $subscriptionId);
- 更新频道品牌设置 更新频道详情和首选项。
/* * $properties array('id' => '', * 'brandingSettings.channel.description' => '', * 'brandingSettings.channel.keywords' => '', * 'brandingSettings.channel.defaultLanguage' => '', * 'brandingSettings.channel.defaultTab' => '', * 'brandingSettings.channel.moderateComments' => '', * 'brandingSettings.channel.showRelatedChannels' => '', * 'brandingSettings.channel.showBrowseView' => '', * 'brandingSettings.channel.featuredChannelsTitle' => '', * 'brandingSettings.channel.featuredChannelsUrls[]' => '', * 'brandingSettings.channel.unsubscribedTrailer' => '') */ $channelServiceObject = new ChannelService($authToken); $response = $channelServiceObject->updateChannelBrandingSettings($properties);
YouTube完整视频API
- 添加代码以调用API类
<?php namespace Your\App\NameSpace; use ZeroDUDDU\YoutubeLaravelApi\VideoService;
- 按ID列出视频
$part ='snippet,contentDetails,id,statistics'; $params =['id'=>'xyzgh']; $videoServiceObject = new VideoService($authToken); $response = $videoServiceObject->videosListById($part, $params);
- 将视频上传到您的频道
$videoServiceObject = new VideoService($authToken); $response = $videoServiceObject->uploadVideo($videoPath, $title, $description, $categoryId, $privacyStatus, $tags, $data);
- 从您的频道删除视频
$videoServiceObject = new VideoService($authToken); $response = $videoServiceObject->deleteVideo($videoId);
- 评分视频 向视频添加喜欢、不喜欢或移除对视频的响应
# rating 'like' or 'dislike' or 'none' $videoServiceObject = new VideoService($authToken); $response = $videoServiceObject->videosRate( $videoId, $rating);