首先composer安裝依賴:
composer require socialiteproviders/qq複製程式碼
註冊服務提供者(同時註釋掉原有的Socialite提供者):
'providers' => [
SocialiteProviders\Manager\ServiceProvider::class, // 新增
];複製程式碼
新增Socialite門面(如果已有略過本操作):
'Socialite' => Laravel\Socialite\Facades\Socialite::class,複製程式碼
新增事件監聽器(App/Providers/EventServiceProvider
):
protected $listen = [
'SocialiteProviders\Manager\SocialiteWasCalled' => [
'SocialiteProviders\QQ\QqExtendSocialite@handle',
],
];複製程式碼
在config/services.php中新增:
'qq' => [
'client_id' => env('QQ_KEY'),
'client_secret' => env('QQ_SECRET'),
'redirect' => env('QQ_REDIRECT_URI'),
], 複製程式碼
在.env中新增:
QQ_KEY=qq互聯上申請QQ_KEY
QQ_SECRET=qq互聯上申請QQ_SECRET
QQ_REDIRECT_URI=qq互聯上設定回撥地址
這裡的回撥地址必須要跟qq互聯管理中心(https://connect.qq.com)設定的回撥地址一樣。
路由:
//qq一鍵登入
Route::get('/qq', 'QqController@qq')->name('qq');
Route::get('/qq/callback', 'QqController@qqlogin');複製程式碼
控制器:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Laravel\Socialite\Facades\Socialite;
use App\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
class QqController extends Controller
{
public function qq()
{
return Socialite::with('qq')->redirect();
}
public function qqlogin()
{
$user = Socialite::driver('qq')->user();
// dd($user);
$check = User::where('uid', $user->id)->where('provider', 'qq_connect')->first();
if (!$check) {
$customer = User::create([
'uid' => $user->id,
'provider' => 'qq_connect',
'name' => $user->nickname,
'email' => 'qq_connect+' . $user->id . '@example.com',
'password' => bcrypt(Str::random(60)),
'avatar' => $user->avatar
]);
} else {
$customer = $check;
}
Auth::login($customer, true);
return redirect('/');
}
//判斷是否是移動端訪問
public function isMobile()
{
// 如果有HTTP_X_WAP_PROFILE則一定是移動裝置
if (isset ($_SERVER['HTTP_X_WAP_PROFILE'])) {
return TRUE;
}
// 如果via資訊含有wap則一定是移動裝置,部分服務商會遮蔽該資訊
if (isset ($_SERVER['HTTP_VIA'])) {
return stristr($_SERVER['HTTP_VIA'], "wap") ? TRUE : FALSE;// 找不到為flase,否則為TRUE
}
// 判斷手機傳送的客戶端標誌,相容性有待提高
if (isset ($_SERVER['HTTP_USER_AGENT'])) {
$clientkeywords = array(
'mobile',
'nokia',
'sony',
'ericsson',
'mot',
'samsung',
'htc',
'sgh',
'lg',
'sharp',
'sie-',
'philips',
'panasonic',
'alcatel',
'lenovo',
'iphone',
'ipod',
'blackberry',
'meizu',
'android',
'netfront',
'symbian',
'ucweb',
'windowsce',
'palm',
'operamini',
'operamobi',
'openwave',
'nexusone',
'cldc',
'midp',
'wap'
);
// 從HTTP_USER_AGENT中查詢手機瀏覽器的關鍵字
if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
return TRUE;
}
}
if (isset ($_SERVER['HTTP_ACCEPT'])) { // 協議法,因為有可能不準確,放到最後判斷
// 如果只支援wml並且不支援html那一定是移動裝置
// 如果支援wml和html但是wml在html之前則是移動裝置
if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== FALSE) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === FALSE || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
return TRUE;
}
}
return FALSE;
}
}
複製程式碼
複製程式碼