编程

Laravel 集成第三方登录, overtrue/socialite

1727 2022-11-12 10:35:45

微信登录通常是通过OAuth2.0来授权的。

  • 客户端向微信服务端发起请求获取code;
  • 获取到code后向服务端发起请求登录,
  • 服务端通过code向微信服务器换取网页授权access_token和用户的openID,
  • 再通过access_token获取用户信息,保存到服务端。

安装

composer require overtrue/laravel-socialite 

配置

在 config/socialite.php 或 config/services.php 进行配置:

 <?php

 return [
     //...
     'github' => [
         'client_id'     => 'your-app-id',
         'client_secret' => 'your-app-secret',
         'redirect'      => 'http://localhost/socialite/callback.php',
     ],
     //...
 ];

使用

<?php

namespace App\Http\Controllers;

use Socialite;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

class AuthController extends Controller
{
    /**
     * Redirect the user to the GitHub authentication page.
     */
    public function redirectToProvider()
    {
        return redirect()->to(Socialite::create('github')->redirect());
    }

    /**
     * Obtain the user information from GitHub.
     */
    public function handleProviderCallback(Request $request)
    {
        $user = Socialite::create('github')->userFromCode($request->query('code'));

        // $user->getId();
        // $user->getNickname();
        // ...
    }
}

注册路由

Route::get('/oauth/github', 'AuthController@redirectToProvider');
Route::get('/oauth/github/callback', 'AuthController@handleProviderCallback');