编程学习网 > PHP技术 > php高级 > Laravel6实现第三方 微信登录
2020
03-25

Laravel6实现第三方 微信登录

attachments-2020-03-Y7fcfSHo5e7ab58a7f885.jpg


目前很多的网站中都会存在很多的交互功能,从而降低用户的操作难度,特此带来微信的第三方登录的项目实战功能开发。对于本实例中的开发内容,就不在使用原生的内容,而是直接使用别人写好的封装的类库。

1. 安装 laravel/socialite

composer require laravel/socialite

2). 在你的 config/app.php 文件中添加以下配置信息

'providers' => [
   
    Laravel\Socialite\SocialiteServiceProvider::class,
],
 
'aliases' => [
    'Socialite' => Laravel\Socialite\Facades\Socialite::class,
],


2. 安装 socialiteProviders/weixin

1). 直接运行以下命令安装扩展包

composer require socialiteproviders/weixin

2). 在你的 config/app.php 文件中添加以下配置信息

'providers' => [

     \SocialiteProviders\Manager\ServiceProvider::class,
],

3). 在你的 app/Providers/EventServiceProvider.php 文件中添加以下事件处理器

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


3. 添加配置

1). 在你的 .env 文件中添加以下配置

WEIXIN_KEY=你的AppID
WEIXIN_SECRET=你的AppSecret
WEIXIN_REDIRECT_URI=你的回调地址

2). 在你的 config/services.php 文件中添加以下配置

'weixin' => [
   'client_id'     => env('WEIXIN_KEY'),
   'client_secret' => env('WEIXIN_SECRET'),
   'redirect'      => env('WEIXIN_REDIRECT_URI'),

   # 这一行配置非常重要,必须要写成这个地址。
   'auth_base_uri' => 'https://open.weixin.qq.com/connect/qrconnect',
],


代码调用

准备工作都完成以后,现在就到了接口对接阶段。

/微信一键登录
Route::get('/weixin', 'WeixinController@weixin')->name('weixin');
Route::get('/weixin/callback', 'WeixinController@weixinlogin');

2). 在你的 app/Http/Controllers/WeixinController.php 文件里添加以下方法

<?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 WeixinController extends Controller
{
    public function weixin(){
        return Socialite::with('weixin')->redirect();
    }

    public function weixinlogin(){
        $user = Socialite::driver('weixin')->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('/');
    }
}

最后就是回调后打印 oauthUser 的结果


v2-080e91e2932985ec056d99348837bace_720w.jpg

扫码二维码 获取免费视频学习资料

Python编程学习

查 看2022高级编程视频教程免费获取