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 (empty($wechatUser['id'])) { throw new \Exception('获取用户信息失败'); } else if (empty($wechatUser->original['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->original['unionid'])->first(); if (!$user) { throw new Exception('您的账号未在小程序上登录过,获取用户信息失败'); } $request->session()->put($sessionKey, $user); } } catch (\Exception $exception) { return response($exception->getMessage()); } return $next($request); } }