微信登录通常是通过OAuth2.0来授权的。
- 客户端向微信服务端发起请求获取code;
- 获取到code后向服务端发起请求登录,
- 服务端通过code向微信服务器换取网页授权access_token和用户的openID,
- 再通过access_token获取用户信息,保存到服务端。
laravel中微信登录有集成的扩展,
socialiteproviders
- 安装扩展
composer require socialiteproviders/weixin
- 配置
app/Providers/EventServiceProvider.php
protected $listen = [
\SocialiteProviders\Manager\SocialiteWasCalled::class => [
// add your listeners (aka providers) here
'SocialiteProviders\Weixin\WeixinExtendSocialite@handle'
],
];
config/services.php
'weixin' => [
'client_id' => env('WEIXIN_KEY'),
'client_secret' => env('WEIXIN_SECRET'),
'redirect' => env('WEIXIN_REDIRECT_URI')
],
.env
# 微信
WEIXIN_KEY=wxbde46abaa8d3xx
WEIXIN_SECRET=ae0059ed19c9367xxxx
WEIXIN_REDIRECT_URI=http://larxxx
- 示例
# 测试路由
Route::get('test', function () {
$code = '081euRI705A3iF1MmoF70TNQI70euRIt';
$driver = Socialite::driver('weixin');
$response = $driver->getAccessTokenResponse($code);
$driver->setOpenId($response['openid']);
$oauthUser = $driver->userFromToken($response['access_token']);
dd($oauthUser);
});