钱包农场 API 开发手记 三 微信登录

安装 socialiteproviders

composer require socialiteproviders/weixin

app/Providers/EventServiceProvider.php

\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

# socialite weixin
WEIXIN_KEY=wxadfaae4fb96ae9da
WEIXIN_SECRET=65e578bb64c218fc763cf87fe8b45374

tinker测试

$code = 'CODE';
$driver = Socialite::driver('weixin');
$response = $driver->getAccessTokenResponse($code);
$driver->setOpenId($response['openid']);
$oauthUser = $driver->userFromToken($response['access_token']);

模型

protected $fillable = [
    'openid', 'name', 'email', 'password',
];

路由

// 第三方登录
$api->post('socials/{social_type}/auth', 'AuthController@socialStore')
    ->name('api.socials.auth.store');

请求验证类

php artisan make:request Api/SocialAuthRequest 
return [
    'code' => 'required|string',
];

控制器

php artisan make:controller Api/V1/AuthController
public function socialStore($type, SocialAuthRequest $request)
{
    if(!in_array($type, ['weixin'])) {
        return $this->response->errorBadRequest();
    }

    $driver = Socialite::driver($type);

    try {
        $response = $driver->getAccessTokenResponse($request->code);
    } catch (\Exception $exception) {
        $this->response->errorUnauthorized('参数错误,为获取用户信息');
    }

    $user = User::where('openid', $response['openid'])->first();
    if(!$user) {
        $user = User::create([
            'openid' => $response['openid']
        ]);
    }

    Log::info('用户ID'. $user->id);
    return $this->response->array(['token' => $user->id]);
}

​​​​​​​钱包农场 API 开发手记 一 开篇

钱包农场 API 开发手记 二 SMS

钱包农场 API 开发手记 三 微信登录

钱包农场 API 开发手记 四 JWT

钱包农场 API 开发手记 五 用户

钱包农场 API 开发手记 六 更新用户信息

钱包农场 API 开发手记 七 绑定手机&&实名认证

钱包农场 API 开发手记 八 土豆

钱包农场 API 开发手记 九 金豆

钱包农场 API 开发手记 十 商品

钱包农场 API 开发手记 十一 订单

钱包农场 API 开发手记 十二 文章

钱包农场 API 开发手记 十三 收货地址

猜你喜欢

转载自my.oschina.net/beanho/blog/1789141