From d81f190cb11de27cd0b1b77ba62a85c71eec97c2 Mon Sep 17 00:00:00 2001 From: li kesong Date: Sun, 23 Jan 2022 13:46:54 +0800 Subject: [PATCH] =?UTF-8?q?=E4=B8=AD=E9=97=B4=E4=BB=B6=E5=BC=82=E5=B8=B8?= =?UTF-8?q?=E8=BE=93=E5=87=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Http/Middleware/WechatAuth.php | 50 ++++++++++++++++-------------- 1 file changed, 27 insertions(+), 23 deletions(-) diff --git a/app/Http/Middleware/WechatAuth.php b/app/Http/Middleware/WechatAuth.php index 3287c8e..970700c 100644 --- a/app/Http/Middleware/WechatAuth.php +++ b/app/Http/Middleware/WechatAuth.php @@ -20,33 +20,37 @@ class WechatAuth */ public function handle(Request $request, Closure $next) { - $sessionKey = 'wechat_user'; - $user = $request->session()->get($sessionKey); - if (!$user) { - $config = config('wechat.official_account.default'); - $app = Factory::officialAccount($config); + try { + $sessionKey = 'wechat_user'; + $user = $request->session()->get($sessionKey); + if (!$user) { + $config = config('wechat.official_account.default'); + $app = Factory::officialAccount($config); - $code = $request->input('code'); - if (empty($code)) { - return $app->oauth->scopes(['snsapi_userinfo'])->redirect($request->url()); - } else { - $wechatUser = $app->oauth->user(); - if (!$wechatUser) { - throw new \Exception('获取用户信息失败'); - } else if (empty($user->unionid)) { - # TODO 调试unionid - if (config('app.debug') && $request->server('REMOTE_ADDR') == '127.0.0.1') { - $wechatUser['unionid'] = 'onhl355f-ofX5e0-4I4vn0bswVPM'; - } else - throw new Exception('获取UnionId失败'); + $code = $request->input('code'); + if (empty($code)) { + return $app->oauth->scopes(['snsapi_userinfo'])->redirect($request->url()); + } else { + $wechatUser = $app->oauth->user(); + if (empty($wechatUser['id'])) { + throw new \Exception('获取用户信息失败'); + } else if (empty($user['unionid'])) { + # TODO 调试unionid + if (config('app.debug') && $request->server('REMOTE_ADDR') == '127.0.0.1') { + $wechatUser['unionid'] = 'onhl355f-ofX5e0-4I4vn0bswVPM'; + } else + throw new Exception('获取UnionId失败'); + } } - } - $user = User::where('unionid', $wechatUser->unionid)->first(); - if (!$user) { - throw new Exception('您的账号未在小程序上登录过,获取用户信息失败'); + $user = User::where('unionid', $wechatUser->unionid)->first(); + if (!$user) { + throw new Exception('您的账号未在小程序上登录过,获取用户信息失败'); + } + $request->session()->put($sessionKey, $user); } - $request->session()->put($sessionKey, $user); + } catch (\Exception $exception) { + return response($exception->getMessage()); } return $next($request); }