首頁 > 後端開發 > 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'));
        });
    }
}
登入後複製

路由(routes/web.php): config/app.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
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板