laravel qq登录

暂无标签

一、要有APP ID 和 APP Key

二、安装扩展

composer require socialiteproviders/qq

三、配置信息

1.将第三方的登录服务者注册进容器内(config/app.php)

'providers' => [
    ...
    SocialiteProviders\Manager\ServiceProvider::class, // 第三方登录
];

2.添加门脸类(config/app.php)

'aliases' => [
    ...
    'Socialite' => Laravel\Socialite\Facades\Socialite::class,
];

3.添加事件监听器(App/Providers/EventServiceProvider)

protected $listen = [
    \SocialiteProviders\Manager\SocialiteWasCalled::class => [
        'SocialiteProviders\\QQ\\QqExtendSocialite@handle',
    ],
];

4.在config/service.php添加QQ接口信息

'qq' => [
    'client_id' => env('QQ_KEY'),
    'client_secret' => env('QQ_SECRET'),
    'redirect' => env('QQ_REDIRECT_URI'),
],

5.在.env里面QQ接口的信息

QQ_KEY=xxxxxx
QQ_SECRET=xxxxxx
QQ_REDIRECT_URI=xxxxxx

QQ_KEY 是 APP ID
QQ_SECRET 是 APP Key
QQ_REDIRECT_URI 是 回调地址

6.添加路由

routes/web.php

Route ::get('auth/{service}/callback', [App\Http\Controllers\OauthController::class,'handleProviderCallback'])->name('app.oauth.callback');
Route ::get('auth/{service}', [App\Http\Controllers\OauthController::class,'redirectToProvider'])->name('app.oauth.redirect');

7.users表添加字段

添加字段qq_id字段用来判断是否为QQ登录

8.添加控制器

App/Http/Controllers/Auth/OauthController.php

<?php

namespace App\Http\Controllers\Auth;

use Illuminate\Http\Request;
use Laravel\Socialite\Facades\Socialite;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use App\Notifications\OauthNotify;

class OauthController extends Controller
{
    public function redirectToProvider ($service = '')
    {
        return Socialite::with($service)->redirect();
    }

    public function handleProviderCallback($service)
    {
        $user = Socialite::driver('qq')->stateless()->user();
        $check = User::where('qq_id', $user->getId())->first();
      if (!$check) {
        $customer = User::create([
          'qq_id' => $user->id,
          'name' => $user->nickname,
          'email' => '' . $user->id . '@example.com',
          'password' => bcrypt($user->id),
          'avatar' => $user->avatar
        ]);
      } else {
        $customer = $check;
      }
      Auth::login($customer, true);
      return redirect('/');
    }
}

end