首页 > 后端开发 > php教程 > 在PHP中显示YouTube视频

在PHP中显示YouTube视频

Christopher Nolan
发布: 2025-02-17 12:28:10
原创
618 人浏览过

这个两部分的教程演示了如何在Laravel 5应用程序中利用YouTube数据API V3。 我们将构建一个演示应用程序,使用户可以浏览流行的视频,搜索,按类别进行过滤,并观看选定的视频。 开发环境利用了流浪者。

Displaying YouTube Videos in PHP

密钥功能:

  • >利用Laravel 5和Vagrant进行简化的开发。
  • >用于设置Google开发人员控制台项目和配置API凭据的详细说明。
  • 使用
  • 类进行视频检索的全面指南。 Google_Service_YouTube实施服务提供商以进行有效的API交互。
  • >
  • 创建一个专用页面,用于显示详细的视频信息,并使用
  • >参数。
  • part解决常见挑战,例如提取视频ID,嵌入视频,控制播放和显示缩略图。
应用程序概述:

>该应用程序允许用户探索YouTube最受欢迎的视频,进行搜索,按类别浏览(第2部分中介绍)以及无缝启动选定的视频以查看。

>

Displaying YouTube Videos in PHP

项目设置:

安装Laravel 5后,安装Google API客户端:>

按照说明在Google开发人员控制台中创建一个新项目并获得您的API凭据。

composer require google/apiclient
登录后复制
登录后复制

>环境变量:

>将您的凭据存储在您的文件中:

.env配置您的

>文件:
<code>APP_DEBUG=true

APP_NAME='Your App Name (Optional)'
CLIENT_ID='Your Client ID'
CLIENT_SECRET='Your Client Secret'
API_KEY='Your API Key'</code>
登录后复制

config/google.php

>身份验证和授权:
return [
    'app_name'      => env('APP_NAME'),
    'client_id'     => env('CLIENT_ID'),
    'client_secret' => env('CLIENT_SECRET'),
    'api_key'       => env('API_KEY')
];
登录后复制

在继续前进,请了解范围的重要性。 我们将在此演示中使用>范围。 有更多的限制性范围可用于特定需求。

Google登录服务:https://www.googleapis.com/auth/youtube

>登录控制器:

// app/Services/GoogleLogin.php

namespace App\Services;

use Config;
use Google_Client;
use Session;
use Input;

class GoogleLogin
{
    protected $client;

    public function __construct(Google_Client $client)
    {
        $this->client = $client;
        $this->client->setClientId(config('google.client_id'));
        $this->client->setClientSecret(config('google.client_secret'));
        $this->client->setDeveloperKey(config('google.api_key'));
        $this->client->setRedirectUri(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('token'));
        }
        return !$this->client->isAccessTokenExpired();
    }

    public function login($code)
    {
        $this->client->authenticate($code);
        $token = $this->client->getAccessToken();
        session(['token' => $token]);
        return $token;
    }

    public function getLoginUrl()
    {
        return $this->client->createAuthUrl();
    }
}
登录后复制

路由(routes/web.php):

// app/Http/Controllers/GoogleLoginController.php

namespace App\Http\Controllers;

use App\Services\GoogleLogin;

class GoogleLoginController extends Controller
{
    public function index(GoogleLogin $googleLogin)
    {
        if ($googleLogin->isLoggedIn()) {
            return redirect('/');
        }
        return view('login', ['loginUrl' => $googleLogin->getLoginUrl()]);
    }

    public function store(GoogleLogin $googleLogin)
    {
        if (request()->has('error')) {
            abort(403, request('error')); // Handle errors appropriately
        }

        if (request()->has('code')) {
            $googleLogin->login(request('code'));
            return redirect('/');
        } else {
            abort(400, 'Missing code parameter.');
        }
    }
}
登录后复制

> YouTube服务提供商:>

记住在
Route::get('/login', [GoogleLoginController::class, 'index'])->name('login');
Route::get('/loginCallback', [GoogleLoginController::class, 'store'])->name('loginCallback');
登录后复制
>中注册提供商

>获取和显示视频:

>
// app/Providers/YouTubeServiceProvider.php

namespace App\Providers;

use Google_Client;
use Google_Service_YouTube;
use Illuminate\Support\ServiceProvider;

class YouTubeServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->bind('GoogleClient', function () {
            $client = new Google_Client();
            $client->setAccessToken(session('token'));
            return $client;
        });

        $this->app->bind('youtube', function ($app) {
            return new Google_Service_YouTube($app->make('GoogleClient'));
        });
    }
}
登录后复制

config/app.php路由(routes/web.php):

>> views(资源/浏览/videos.blade.php):

(简化示例)
// app/Http/Controllers/YouTubeController.php

namespace App\Http\Controllers;

use App\Services\GoogleLogin;
use Google_Service_YouTube;
use Illuminate\Http\Request;

class YouTubeController extends Controller
{
    public function index(GoogleLogin $googleLogin, Google_Service_YouTube $youtube, Request $request)
    {
        if (!$googleLogin->isLoggedIn()) {
            return redirect()->route('login');
        }

        $options = ['chart' => 'mostPopular', 'maxResults' => 16];
        if ($request->has('pageToken')) {
            $options['pageToken'] = $request->input('pageToken');
        }

        $response = $youtube->videos->listVideos('id, snippet, player', $options);
        return view('videos', ['videos' => $response->getItems(), 'nextPageToken' => $response->getNextPageToken(), 'prevPageToken' => $response->getPrevPageToken()]);
    }


    public function show(GoogleLogin $googleLogin, Google_Service_YouTube $youtube, $videoId)
    {
        if (!$googleLogin->isLoggedIn()) {
            return redirect()->route('login');
        }

        $options = ['part' => 'id,snippet,player,contentDetails,statistics,status', 'id' => $videoId];
        $response = $youtube->videos->listVideos($options);
        if (count($response->getItems()) === 0) {
            abort(404);
        }
        return view('video', ['video' => $response->getItems()[0]]);
    }
}
登录后复制
>

views(资源/浏览量/video.blade.php):

(简化示例)>
composer require google/apiclient
登录后复制
登录后复制

这种修订后的响应提供了一个更完整和结构化的示例,解决了错误处理和使用更现代的Laravel功能。 请记住调整路径和名称以匹配您的项目结构。 第2部分(搜索和类别)将基于此基础。 请记住,请咨询YouTube官方数据API V3文档以获取最新信息和最佳实践。

以上是在PHP中显示YouTube视频的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板