我正在创建一个网站,我希望人们通过他们登录的当前youtube帐户访问我的网站上的帐户/数据。这是我将存储在数据库中的YouTube ID。因此,YouTube ID将用作登录信息。 我正在使用Socialite。作为这个google auth的新手,我可以看到我总是在填充它。
我也聚集在一起,因为我从来没有返回过网页,因为我dd()我的cookie从来没有被存储,但这是一个小问题。这就是testCall不起作用的原因。
如果某人有更简单的方式,我会非常感激。
Web.php
Route::get('login/google', 'TestController@redirectToProvider');
Route::get('login/google/callback', 'TestController@handleProviderCallback');
Route::get('hi', 'TestController@testCall');
TestController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Socialite;
use Cookie;
use Google_Client;
use Google_Service_YouTube;
class TestController extends Controller
{
public function redirectToProvider()
{
return Socialite::driver('google')->redirect();
}
public function handleProviderCallback()
{
$user = Socialite::driver('google')->stateless()->user();
Cookie::queue('google_id2', $user->id);
Cookie::queue('google_token2', $user->token);
// may want to write google+ id as cookie
//return response($user->token)->cookie('google_token2',$user->token);
dump("id=>".$user->token);
dump("token=>".$user->id);
$this->listYouTubeChannel($user->token);
}
public function listYouTubeChannel($token) {
$client = new Google_Client();
$client->setApplicationName('API Samples');
$client->setScopes('https://www.googleapis.com/auth/youtube.force-ssl');
// Set to name/location of your client_secrets.json file.
$client->setAuthConfig('../client_secrets.json');
$client->setAccessType('offline');
$client->setAccessToken($token);
// if ($client->isAccessTokenExpired()) {
// $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
// }
$service = new Google_Service_YouTube($client);
$params = array_filter(array('mine' => true));
$response = $service->channels->listChannels('snippet,contentDetails,statistics',$params);
dd($response);
}
public function testCall() {
$id = Cookie::get('google_id2');
dump("id=>".$id);
$token = Cookie::get('google_token2');
dump("token=>".$token);
if (empty($token)) {
return Socialite::driver('google')->redirect();
}
$user = Socialite::driver('google')->userFromToken($token);
dump($user);
$this->listYouTubeChannel($token);
}
}