用PHP显示YouTube视频

tech2022-09-01  98

In this two-part article, we’re going to learn how to work with version 3 of the YouTube API and we’ll build a demo along the way. Let’s get started.

在这篇由两部分组成的文章中,我们将学习如何使用YouTube API第3版,并在此过程中进行演示。 让我们开始吧。

我们正在建设 (What We’re Building)

We’re going to build a demo that lets the user browse popular videos on YouTube, search for a video, browse videos by categories, and select a video to watch.

我们将构建一个演示,使用户可以浏览YouTube上的热门视频,搜索视频,按类别浏览视频以及选择要观看的视频。

I will be using Laravel 5 as my framework of choice, and Vagrant for my development environment. The final product will look something like this:

我将使用Laravel 5作为我的选择框架,并使用Vagrant作为我的开发环境。 最终产品将如下所示:

准备项目 (Preparing the Project)

After installing Laravel 5 on your machine, install google/apiclient:

在您的机器上安装Laravel 5之后,安装google/apiclient :

composer require google/apiclient

To set up a new project on the Google Developers Console, check out this quick tip to get started.

要在Google Developers Console上设置新项目,请查看此快速提示以开始使用。

注册环境变量 (Registering Environment Variables)

After getting our credentials from the Google Developers Console, we need to register them inside our application.

从Google Developers Console获得我们的凭据后,我们需要在我们的应用程序中注册它们。

// .env APP_DEBUG=true app_name='Your app name (optional)' client_id='Your client id' client_secret='Your client secret' api_key='Your developer key' // config/google.php return [ 'app_name' => env('app_name'), 'client_id' => env('client_id'), 'client_secret' => env('client_secret'), 'api_key' => env('api_key') ];

Laravel automatically loads the environment variables from the .env file in the root of our application folder. Now that we have our configuration set up, we can start the login process.

Laravel会自动从应用程序文件夹根目录中的.env文件加载环境变量。 现在我们已经设置好配置,我们可以开始登录过程了。

登录和授权 (Login & Authorization)

Before logging in with the Google API, we need to talk about scopes, and why they are important to the authorization process.

在使用Google API登录之前,我们需要讨论范围,以及它们为什么对授权过程很重要。

范围 (Scopes)

Scopes define the level of authorization accorded to the application, so be sure to only request what you need. YouTube’s API has four scopes:

范围定义了与应用程序匹配的授权级别,因此请确保仅请求您需要的内容。 YouTube的API有四个范围:

https://www.googleapis.com/auth/youtube: Manage your YouTube account.

https://www.googleapis.com/auth/youtube :管理您的YouTube帐户。

https://www.googleapis.com/auth/youtube.readonly: View your YouTube account.

https://www.googleapis.com/auth/youtube.readonly :查看您的YouTube帐户。

https://www.googleapis.com/auth/youtube.upload: Upload YouTube videos and manage your YouTube videos.

https://www.googleapis.com/auth/youtube.upload :上传YouTube视频并管理您的YouTube视频。

https://www.googleapis.com/auth/youtubepartner-channel-audit: Retrieve the auditDetails part in a channel resource.

https://www.googleapis.com/auth/youtubepartner-channel-audit :检索频道资源中的auditDetails部分。

For our demo, I’m only going to use the first one, and we can extend it depending on our application’s needs. You can read more about authorization in the documentation.

对于我们的演示,我将仅使用第一个,我们可以根据应用程序的需求对其进行扩展。 您可以在文档中阅读有关授权的更多信息。

// app/Services/GoogleLogin.php namespace App\Services; class GoogleLogin { protected $client; public function __construct(\Google_Client $client) { $this->client = $client; $this->client->setClientId(\Config::get('google.client_id')); $this->client->setClientSecret(\Config::get('google.client_secret')); $this->client->setDeveloperKey(\Config::get('google.api_key')); $this->client->setRedirectUri(\Config::get('app.url') . "/loginCallback"); $this->client->setScopes([ 'https://www.googleapis.com/auth/youtube', ]); $this->client->setAccessType('offline'); } public function isLoggedIn() { if (\Session::has('token')) { $this->client->setAccessToken(\Session::get('token')); } if ($this->client->isAccessTokenExpired()) { \Session::set('token', $this->client->getRefreshToken()); } return !$this->client->isAccessTokenExpired(); } public function login($code) { $this->client->authenticate($code); $token = $this->client->getAccessToken(); \Session::put('token', $token); return $token; } public function getLoginUrl() { $authUrl = $this->client->createAuthUrl(); return $authUrl; } }

After constructing a Google_Client instance using our credentials, we set the desired scopes. The setAccessType method gives our application the ability to refresh the token when the user is not present.

在使用我们的凭据构造Google_Client实例之后,我们设置所需的范围。 setAccessType方法使我们的应用程序可以在用户不存在时刷新令牌。

登录控制器 (Login Controller)

// app/Http/routes.php Route::get('/login', ['uses' => 'GoogleLoginController@index', 'as' => 'login']); Route::get('/loginCallback', ['uses' => 'GoogleLoginController@store', 'as' => 'loginCallback']); // app/Http/Controllers/GoogleLoginController.php class GoogleLoginController extends Controller { public function index(\App\Services\GoogleLogin $ga) { if ($ga->isLoggedIn()) { return \Redirect::to('/'); } $loginUrl = $ga->getLoginUrl(); return "<a href='{$loginUrl}'>login</a>"; } public function store(\App\Services\GoogleLogin $ga) { // User rejected the request if(\Input::has('error')){ dd(\Input::get('error')); } if (\Input::has('code')) { $code = \Input::get('code'); $ga->login($code); return \Redirect::to('/'); } else { throw new \InvalidArgumentException("Code attribute is missing."); }//else } }

The GoogleLoginController@index method will test if the user is logged in and if so, will redirect them to the home page. Otherwise, we generate a new login URL.

GoogleLoginController@index方法将测试用户是否登录,如果登录,则将其重定向到主页。 否则,我们将生成一个新的登录URL。

After passing the authorization phase, Google will redirect the user to the callback URL defined in the Google Developers Console with the code parameter. This code is used in exchange for a token.

通过授权阶段后,Google会将用户重定向到Google开发者控制台中使用code参数定义的回调URL。 此代码用于交换令牌。

列出影片 (Listing Videos)

The Google_Service_YouTube class is our door to the YouTube API. It provides access to all YouTube data. The class takes a Google_Client instance as a parameter. It makes sense to create a provider to bind our implementation so that we don’t have to repeat the same code everywhere. You can read more about service providers in the documentation.

Google_Service_YouTube类是我们使用YouTube API的大门。 它提供对所有YouTube数据的访问。 该类将Google_Client实例作为参数。 创建一个提供程序来绑定我们的实现是有意义的,这样我们就不必在各处重复相同的代码。 您可以在文档中阅读有关服务提供商的更多信息。

php artisan make:provider YouTubeServiceProvider

This command will create a new class inside our app/Providers folder. We need to add our service provider to the list of providers inside config/app.php.

此命令将在我们的app/Providers文件夹中创建一个新类。 我们需要将我们的服务提供者添加到config/app.php中的提供者列表config/app.php 。

// config/app.php 'providers' => [ 'App\Providers\YouTubeServiceProvider', ] // app/Providers/YouTubeServiceProvider.php public function register() { $app = $this->app; $this->app->bind('GoogleClient', function () { $googleClient = new \Google_Client(); $googleClient->setAccessToken(\Session::get("token")); return $googleClient; }); $this->app->bind('youtube', function () use ($app) { $googleClient = \App::make('GoogleClient'); $youtube = new \Google_Service_YouTube($googleClient); return $youtube; }); }

The https://www.googleapis.com/youtube/v3/videos endpoint returns the list of videos, and it can be accessed using our YouTube class via $youtube->videos.

https://www.googleapis.com/youtube/v3/videos端点会返回视频列表,可以使用我们的YouTube类通过$youtube->videos对其进行访问。

// app/Http/Controllers/YouTubeAPIController.php public function videos() { $youtube = \App::make('youtube'); $videos = $youtube->videos->listVideos('snippet', ['chart' => 'mostPopular']); dump($video); }

The first parameter to the listVideos method is called part and it defines the information contained in the result. You may add statistics to get data about votes count, likes, etc. We’ll talk more about the partparameter later in this article.You can read more about the supported values in the documentation.

listVideos方法的第一个参数称为part ,它定义了结果中包含的信息。 您可以添加statistics以获得有关选票计数,点赞等的数据。我们将在本文后面详细讨论part参数。您可以在文档中阅读有关受支持值的更多信息。

The second parameter must contain a filter for the videos. In this case, we are getting the most popular videos on YouTube. You may also request your liked or disliked videos, etc. You can read more about filters in the documentation.

第二个参数必须包含视频的过滤器。 在这种情况下,我们会在YouTube上获得最受欢迎的视频。 您也可以要求喜欢或不喜欢的视频等。您可以在文档中阅读有关过滤器的更多信息。

// app/Http/Controllers/YouTubeAPIController.php public function videos() { $options = ['chart' => 'mostPopular', 'maxResults' => 16]; if (\Input::has('page')) { $options['pageToken'] = \Input::get('page'); } $youtube = \App::make('youtube'); $videos = $youtube->videos->listVideos('id, snippet', $options); return view('videos', ['videos' => $videos]); }

This method is self explanatory. The page parameter is for pagination as we’ll see next.

这种方法是不言自明的。 page参数用于分页,我们将在后面看到。

// resources/views/videos.blade.php <ul class="list-unstyled video-list-thumbs row"> @foreach($videos as $video) <li class="col-lg-3 col-sm-4 col-xs-6"> <a href="https://www.youtube.com/watch?v={{ $video->getId() }}" title="{{ $video['snippet']['title'] }}" target="_blank"> <img src="{{ $video['snippet']['thumbnails']['medium']['url'] }}" alt="{{ $video['snippet']['title'] }}" /> <h2 class="truncate">{{ $video['snippet']['title'] }}</h2> </a> </li> @endforeach </ul> <ul class="pagination pagination-lg"> <li @if($videos->getPrevPageToken() == null) class="disabled" @endif> <a href="/videos?page={{$videos->getPrevPageToken()}}" aria-label="Previous"> <span aria-hidden="true">Previous &laquo;</span> </a> </li> <li @if($videos->getNextPageToken() == null) class="disabled" @endif> <a href="/videos?page={{$videos->getNextPageToken()}}" aria-label="Next"> <span aria-hidden="true">Next &raquo;</span> </a> </li> </ul>

Our view is very basic – we only output the video title, thumbnail and a link. Our API response also contains likes, dislikes, view count, etc, so you may use them to enrich your page using some special markup. The pagination links give the user the ability to navigate through videos. You may have noticed that it’s done through tokens and not the normal page parameter.

我们的观点非常基础-我们仅输出视频标题,缩略图和链接。 我们的API响应还包含喜欢,不喜欢,观看次数等,因此您可以使用它们通过一些特殊的标记来丰富您的页面。 分页链接使用户能够浏览视频。 您可能已经注意到,这是通过令牌而不是普通的page参数完成的。

When you click on a video, you will be redirected to watch the video on YouTube using the ID. Why not get the video details and create a page containing the player along with more info about the video?

单击视频时,您将被重定向到使用ID在YouTube上观看视频。 为什么不获取视频详细信息并创建一个包含播放器以及有关视频的更多信息的页面?

单个视频页面 (Single Video Page)

Getting a single video is just a matter of specifying an option to the same endpoint from before. Since the result is a single item, we set the maxResults parameter to 1, and we remove the chart attribute because it’s not relevant in this request.

获取单个视频仅是从以前为同一端点指定一个选项的问题。 由于结果是单个项目,因此我们将maxResults参数设置为1 ,并删除了chart属性,因为它与该请求无关。

// app/Http/routes.php Route::get('/video/{id}', ['uses' => 'YouTubeAPIController@video', 'as' => 'video']); // app/Http/Controllers/YouTubeAPIController.php public function video($id){ $options = ['maxResults' => 1, 'id' => $id]; $youtube = \App::make('youtube'); $videos = $youtube->videos->listVideos('id, snippet, player, contentDetails, statistics, status', $options); if(count($videos->getItems()) == 0){ return redirect('404'); } return view('video', ['video' => $videos[0]]); }

Because it’s a single item page, I tried to pull as much information as I can using the part parameter. If the item doesn’t exist, we redirect the user to the 404 not found page. Otherwise, we render our view with the first item from the list.

因为它是单个项目页面,所以我尝试使用part参数获取尽可能多的信息。 如果该项目不存在,我们会将用户重定向到404找不到页面。 否则,我们将使用列表中的第一项渲染视图。

// resources/views/video.blade.php <div class="row"> <h2>{{ $video["snippet"]["title"] }}</h2> </div> <div class="row"> <iframe type='text/html' src='http://www.youtube.com/embed/{{ $video->getId() }}' width='100%' height='500' frameborder='0' allowfullscreen='true'></iframe> </div> <div class="row"> (<span>{{ $video["statistics"]["likeCount"] }} <i class="glyphicon glyphicon-thumbs-up"></i></span>) (<span>{{ $video["statistics"]["dislikeCount"] }} <i class="glyphicon glyphicon-thumbs-down"></i></span>) (<span>{{ $video["statistics"]["favoriteCount"] }} <i class="glyphicon glyphicon-heart"></i></span>) (<span>{{ $video["statistics"]["commentCount"] }} <i class="glyphicon glyphicon-bullhorn"></i></span>) </div> <hr/> <div class="row"> <p>{{ $video["snippet"]["description"] }}</p> </div>

Because we asked the YouTube API for the player part, we can directly access it using $video['player']['embedHtml'], but if you want to customize the player dimensions you can build it using the video ID as we did in our example.

因为我们要求player部分使用YouTube API,所以我们可以使用$video['player']['embedHtml']直接访问它,但是如果您要自定义播放器尺寸,则可以像我们一样使用视频ID来构建它在我们的例子中。

One thing to note: every request has a cost of one call, and when you ask for the snippet, statistics, etc, you add up new costs. You can read more about quotas and costs in the documentation.

需要注意的一件事:每个请求的通话费用为一,而当您请求摘要,统计信息等时,您便会增加新的费用。 您可以在文档中阅读有关配额和成本的更多信息。

结语 (Wrapping Up)

In this first part, we introduced the YouTube API and built a small demo to query the list of most popular videos on YouTube with the pagination links, and a page to view a single video. In the next part we will be exploring video categories and the search functionality, so stay tuned. You can check the final result on Github, and if you have any questions or comments, you can post them below.

在第一部分中,我们介绍了YouTube API,并构建了一个小示例,用于使用分页链接查询YouTube上最受欢迎的视频列表,并提供一个页面以查看单个视频。 在下一部分中,我们将探索视频类别和搜索功能,请继续关注。 您可以在Github上查看最终结果,如果有任何疑问或意见,可以在下面发布。

翻译自: https://www.sitepoint.com/displaying-youtube-videos-php/

最新回复(0)