1.composer require laravel/socialite
2. 在config/app.php文件中加入providers及aliases加入此扩展包的类设置
'providers' => [
// 社群登入
Laravel\Socialite\SocialiteServiceProvider::class,
],
'aliases' => [
'Socialite' => Laravel\Socialite\Facades\Socialite::class,
],
3.在config/services.php添加Github验证数据相关设置。
'github' => [
'client_id' => env('GITHUB_CLIENT_ID'),
'client_secret' => env('GITHUB_CLIENT_SECRET'),
'redirect' => env('GITHUB_REDIRECT'),
],
4.在.env文件中设置github变量
GITHUB_CLIENT_ID=
GITHUB_CLIENT_SECRET=
GITHUB_REDIRECT=http://shop-laravel.local/user/auth/github-sign-in-callback
5.设置路由
Route::group(['prefix' => 'user'], function(){
// 使用者驗證
Route::group(['prefix' => 'auth'], function(){
// Github 登入
Route::get('/github-sign-in', 'UserAuthController@githubSignInProcess');
// Github 登入重新導向授權資料處理
Route::get('/github-sign-in-callback', 'UserAuthController@githubSignInCallbackProcess');
});
});
6.编写controller
// github 登入
public function githubSignInProcess()
{
$redirect_url = env('GITHUB_REDIRECT');
//driver 里面的参数 为 config/services.php里面配置的github
return Socialite::driver('github')
->redirectUrl($redirect_url)
->redirect();
}
// github 登入重新導向授權資料處理
public function githubSignInCallbackProcess()
{
if (request()->error == 'access_denied') {
throw new Exception('授權失敗,存取錯誤');
}
// 取得第三方使用者資料
$GithubUser = Socialite::driver('github')->user();
$github_email = $GithubUser->email;
if (is_null($github_email)) {
throw new Exception('未授權取得使用者 Email');
}
// 取得 Github 資料
$github_id = $GithubUser->id;
$github_name = $GithubUser->name;
// 取得使用者資料是否有此 Github id 資料
$User = User::where('github_id', $github_id)->first();
if (is_null($User)) {
// 沒有綁定 Github Id 的帳號,透過 Email 尋找是否有此帳號
$User = User::where('email', $github_email)->first();
if (!is_null($User)) {
// 有此帳號,綁定 Github Id
$User->github_id = $github_id;
$User->save();
}
}
if (is_null($User)){
// 尚未註冊
$input = [
'email' => $github_email, // Email
'nickname' => $github_name, // 暱稱
'password' => uniqid(), // 隨機產生密碼
'github_id' => $github_id, // Github ID
'type' => 'G', // 一般使用者
];
// 密碼加密
$input['password'] = Hash::make($input['password']);
// 新增會員資料
$User = User::create($input);
// 寄送註冊通知信
$mail_binding = [
'nickname' => $input['nickname'],
'email' => $input['email'],
];
SendSignUpMailJob::dispatch($mail_binding)
->onQueue('high');
}
// 登入會員
// session 紀錄會員編號
session()->put('user_id', $User->id);
// 重新導向到原先使用者造訪頁面,沒有嘗試造訪頁則重新導向回首頁
return redirect()->intended('/');
}