Laravel6实现第三方 微信登录

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

1. 安装 laravel/socialite

composer require laravel/socialite

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

‘providers‘ => [
  
    LaravelSocialiteSocialiteServiceProvider::class,
],

‘aliases‘ => [
    ‘Socialite‘ => LaravelSocialiteFacadesSocialite::class,
],

2. 安装 socialiteProviders/weixin

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

composer require socialiteproviders/weixin

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

‘providers‘ => [

     SocialiteProvidersManagerServiceProvider::class,
],

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

protected $listen = [
    SocialiteProvidersManagerSocialiteWasCalled::class => [
        ‘SocialiteProvidersWeixinWeixinExtendSocialite@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 AppHttpControllers;

use IlluminateHttpRequest;

use LaravelSocialiteFacadesSocialite;
use AppUser;
use IlluminateSupportFacadesAuth;
use IlluminateSupportStr;

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 的结果  

技术分享图片

 

 

 如果有想过操作问题,想交流工作问题以及代码可以加入:647617935

Laravel6实现第三方 微信登录

以上是Laravel6实现第三方 微信登录的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>