尧图建网站 尧图建网站 YAOTU WEB BUILD 免费咨询
ARTICLE DETAIL

资讯详情

深耕网站建设与建站编程的一线实战洞察。

小白勇闯《苍穹外卖》Day6

小白勇闯《苍穹外卖》Day6 HttpClientHttpClient作用发送HTTP请求接收响应数据发送请求步骤创建HttpClient对象 创建Http请求对象 调用HttpClient的execute方法发送请求微信小程序开发这里因为我之前用邮箱注册过一个了所以我直接用的测试号注意微信登录导入小程序代码这里注意解压之后有外层的文件夹一定要选择里面那个微信登录流程小程序调用 wx.login 获取临时 code传给后端后端使用 HttpClient 调用微信开放平台接口传入 appid、appsecret、code获取用户 openid依据 openid 完成自动注册生成 JWT 令牌返回小程序后续每次业务请求携带 JWT后端拦截器校验令牌识别用户身份。需求分析和设计业务规则基于微信登录实现小程序的登录功能如果是新用户需要自动完成注册接口设计数据库设计代码开发配置微信登录所需配置项application.ymlsky: jwt: # 设置jwt签名加密时使用的秘钥 admin-secret-key: itcast # 设置jwt过期时间 admin-ttl: 7200000 # 设置前端传递过来的令牌名称 admin-token-name: token user-secret-key: itheima user-ttl: 7200000 user-token-name: authentication wechat: appid: ${sky.wechat.appid} secret: ${sky.wechat.secret}application-dev.ymlsky: wechat: appid: 你的 secret: 你的我用的是测试号在这里看https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?actionshowinfotsandbox/index小程序端调用 wx.login 拿到一次性临时 code将 code 通过请求传给我们的 Java 后端后端读取配置文件里的 appid 和 secret使用 HttpClient 工具去调用微信官方的 jscode2session 接口传入 appid、secret、code从微信返回结果中解析出用户唯一标识 openid拿着 openid 去数据库查询用户如果查不到就自动完成新用户注册之后后端生成项目自己的 JWT 登录令牌把用户信息和 JWT 封装成 VO 返回给小程序小程序将 JWT 存在本地存储后续所有业务请求都在请求头带上这个 JWT后端拦截器校验 JWT 就能识别是哪个用户完成业务处理并返回数据。UserControllerRestController RequestMapping(/user/user) Api(tags C端用户相关接口) Slf4j public class UserController { Autowired private UserService userService; Autowired private JwtProperties jwtProperties; /** * 微信登录 * param userLoginDTO * return */ PostMapping(/login) ApiOperation(微信登录) public ResultUserLoginVO login(RequestBody UserLoginDTO userLoginDTO){ log.info(微信用户登录{},userLoginDTO.getCode()); //微信登录 User user userService.wxLogin(userLoginDTO);//后绪步骤实现 //为微信用户生成jwt令牌 MapString, Object claims new HashMap(); claims.put(JwtClaimsConstant.USER_ID,user.getId()); String token JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims); UserLoginVO userLoginVO UserLoginVO.builder() .id(user.getId()) .openid(user.getOpenid()) .token(token) .build(); return Result.success(userLoginVO); } }UserServicepublic interface UserService { /** * 微信登录 * param userLoginDTO * return */ User wxLogin(UserLoginDTO userLoginDTO); }UserServiceImplService Slf4j public class UserServiceImpl implements UserService { //微信服务接口地址 public static final String WX_LOGIN https://api.weixin.qq.com/sns/jscode2session; Autowired private WeChatProperties weChatProperties; Autowired private UserMapper userMapper; /** * 微信登录 * param userLoginDTO * return */ public User wxLogin(UserLoginDTO userLoginDTO) { String openid getOpenid(userLoginDTO.getCode()); //判断openid是否为空如果为空表示登录失败抛出业务异常 if(openid null){ throw new LoginFailedException(MessageConstant.LOGIN_FAILED); } //判断当前用户是否为新用户 User user userMapper.getByOpenid(openid); //如果是新用户自动完成注册 if(user null){ user User.builder() .openid(openid) .createTime(LocalDateTime.now()) .build(); userMapper.insert(user);//后绪步骤实现 } //返回这个用户对象 return user; } /** * 调用微信接口服务获取微信用户的openid * param code * return */ private String getOpenid(String code){ //调用微信接口服务获得当前微信用户的openid MapString, String map new HashMap(); map.put(appid,weChatProperties.getAppid()); map.put(secret,weChatProperties.getSecret()); map.put(js_code,code); map.put(grant_type,authorization_code); String json HttpClientUtil.doGet(WX_LOGIN, map); JSONObject jsonObject JSON.parseObject(json); String openid jsonObject.getString(openid); return openid; } }UserMapperMapper public interface UserMapper { /** * 根据openid查询用户 * param openid * return */ Select(select * from user where openid #{openid}) User getByOpenid(String openid); /** * 插入数据 * param user */ void insert(User user); }UserMapper.xmlinsert idinsert useGeneratedKeystrue keyPropertyid insert into user (openid, name, phone, sex, id_number, avatar, create_time) values (#{openid}, #{name}, #{phone}, #{sex}, #{idNumber}, #{avatar}, #{createTime}) /insertJwtTokenUserInterceptor/** * jwt令牌校验的拦截器 */ Component Slf4j public class JwtTokenUserInterceptor implements HandlerInterceptor { Autowired private JwtProperties jwtProperties; /** * 校验jwt * * param request * param response * param handler * return * throws Exception */ public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //判断当前拦截到的是Controller的方法还是其他资源 if (!(handler instanceof HandlerMethod)) { //当前拦截到的不是动态方法直接放行 return true; } //1、从请求头中获取令牌 String token request.getHeader(jwtProperties.getUserTokenName()); //2、校验令牌 try { log.info(jwt校验:{}, token); Claims claims JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token); Long userId Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString()); log.info(当前用户的id, userId); BaseContext.setCurrentId(userId); //3、通过放行 return true; } catch (Exception ex) { //4、不通过响应401状态码 response.setStatus(401); return false; } } }WebMvcConfigurationAutowired private JwtTokenUserInterceptor jwtTokenUserInterceptor; /** * 注册自定义拦截器 * param registry */ protected void addInterceptors(InterceptorRegistry registry) { log.info(开始注册自定义拦截器...); //......... registry.addInterceptor(jwtTokenUserInterceptor) .addPathPatterns(/user/**) .excludePathPatterns(/user/user/login) .excludePathPatterns(/user/shop/status); }运行之后发现报错测试号要关注测试公众号后面还是一直显示登录失败我直接把openid写死了。。。String openid o0Abcdef1234567890testmockopenid;//随便一串字符串导入商品浏览功能代码代码已上传
返回列表