安装 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 开发手记 一 开篇