この2部構成のチュートリアルは、Laravel 5アプリケーション内でYouTube Data API V3を活用する方法を示しています。 ユーザーが人気のあるビデオを閲覧したり、カテゴリごとに検索したり、選択したビデオを視聴できるデモアプリケーションを構築したりできます。 開発環境はVagrantを利用しています
主要な機能:
Google_Service_YouTube
part
プロジェクトのセットアップ:
Laravel 5をインストールした後、Google APIクライアントをインストールした後、
指示に従って、Google Developers Consoleで新しいプロジェクトを作成し、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>
Googleログインサービス:config/google.php
return [ 'app_name' => env('APP_NAME'), 'client_id' => env('CLIENT_ID'), 'client_secret' => env('CLIENT_SECRET'), 'api_key' => env('API_KEY') ];
ログインコントローラー:
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(); } }
プロバイダーを
// 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.'); } } }
に登録することを忘れないでください ビデオの取得と表示:
Route::get('/login', [GoogleLoginController::class, 'index'])->name('login'); Route::get('/loginCallback', [GoogleLoginController::class, 'store'])->name('loginCallback');
ルート(routes/web.php):
// 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
(簡略化された例)
// 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]]); } }
(簡略化された例) この改訂された応答は、より完全で構造化された例を提供し、エラー処理に対処し、より最新のLaravel機能を使用します。 プロジェクト構造に合わせてパスと名前を調整することを忘れないでください。 パート2(検索とカテゴリ)は、この基盤の上に構築されます。 最新の情報とベストプラクティスについては、公式のYouTubeデータAPI V3ドキュメントを参照してください。 以上がPHPにYouTubeビデオを表示しますの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。composer require google/apiclient