瑞吉外卖实操笔记五----店铺营业状态设置与用户端微信登录实现
店铺营业状态设置与用户端微信登录实现
一.店铺营业状态设置
由于店铺营业状态可以算是一个单独的内容,没有必要为其单独设置一个表,因此将营业状态单独设置到redis缓存中。
设置营业店铺状态只需要一个获取状态的接口即可;
@RestController("userShopController")
@RequestMapping("/user/shop")
@Api(tags = "客户端店铺相关接口")
@Slf4j
public class ShopController {
@Autowired
private RedisTemplate redisTemplate;
/**
* 用户端获取店铺营业状态
* @return
*/
@GetMapping("/status")
public Result<Integer> getStatus(){
//获取到的店铺营业状态可能为空;此时应该设置为营业,并且默认加入到redis中;
Integer status = (Integer) redisTemplate.opsForValue().get("SHOP_STATUS");
if(status==null){
redisTemplate.opsForValue().set("SHOP_STATUS", ShopConstant.SHOP_TRADE);
status=ShopConstant.SHOP_TRADE;
}
log.info("获取店铺营业状态为{}",status==ShopConstant.SHOP_TRADE?"营业中":"打烊中");
return Result.success(status);
}
}
二.微信登陆
微信登录流程:
1.小程序调用wx.login()获取code(授权码);调用直接获取,不必经过开发者服务器
2.小程序调用wx.request()发送code,发送给开发者服务器;一个授权码只能使用一次;
3.开发者服务器调用微信接口服务,传递appid+appsecret+code参数;
4.微信接口服务返回session_key和openid(微信用户的唯一标识);
5.由于后续小程序还有其他业务请求开发者服务器,因此应该将自定义登陆状态(token)与openid,session_key关联
6.开发者服务器将jwt-token返回给小程序;
7.小程序将自定义登录状态jwt-token存入storage;
8.小程序发起业务请求,携带jwt-token;
9.开发者服务器通过jwt-token查询openid,session_key;
10.开发者服务器返回业务数据;
/*
controller层代码
*/
@RestController
@RequestMapping("/user/user")
@Slf4j
public class UserController {
@Autowired
private UserService userService;
@Autowired
private JwtProperties jwtProperties;
@PostMapping("/login")
public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO){
//userLoginDTO中仅仅包含授权码code
log.info("微信登录:{}",userLoginDTO);
//微信登录,业务层返回登陆/注册的用户对象;
User user=userService.wxlogin(userLoginDTO);
//为微信用户设置JWT令牌;并将令牌返回给用户端;
Map<String,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);
}
}
/*
service层代码
*/
/**
* 微信登录返回User对象
* @param userLoginDTO
* @return
*/
@Override
public User wxlogin(UserLoginDTO userLoginDTO) {
//根据传递过来的code调用getOpenId请求微信接口服务获得对应的openid;
String openid = this.getOpenId(userLoginDTO.getCode());
//判断openid是否为空,如果为空表示登录失败,抛出业务异常;
if(openid==null){
throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
}
//判断当前用户是否为新的用户;插叙当前openId对应的用户是否已经存在
User user = userMapper.getByOpenId(openid);
//如果查询不对应的用户(user为Null),说明是新用户,自动完成注册;
if(user==null){
user = User.builder()
.openid(openid)
.createTime(LocalDateTime.now())
.build();
//将该用户插入(完成注册);
userMapper.insert(user);
}
//返回这个用户对象;
return user;
}
private String getOpenId(String code){
//调用微信接口服务,获得当前用户openId;
Map<String ,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;
}
/*
mapper层代码
*/
@Select("select * from user where openid=#{openId}")
User getByOpenId(String openId);
另外,同样应该对大部分请求进行拦截,拦截器代码与管理端大概一致;
/**
* jwt令牌校验的拦截器
*/
@Component
@Slf4j
public class WechatTokenUserInterceptor 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;
}
try {
String token = request.getHeader(jwtProperties.getUserTokenName());
Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
//一个小bug,解析出来的载荷中的有数字的部分都是Integer,然而设置的时候不一定是数据部分,所以
//可以先转换为String,再按照需要转换为其他类型;
Long userId=Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
//取出id之后,将id存放在该线程的内存空间之中,由于这是同一个请求时同一个线程,所以后续Controller与Service
//可以单独取出该线程使用;
BaseContext.setCurrentId(userId);
log.info("解析到的员工ID为:{}",userId);
if(userId!=null){
//如果有登录数据,代表一登录,放行
return true;
}else{
//否则,发送未认证错误信息
response.setStatus(401);
return false;
}
} catch (NumberFormatException e) {
throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
}
}
}
在配置类中进行配置
/**
* 带有“###”为新增配置
*/
/**
* 配置类,注册web层相关组件
*/
@Configuration
@Slf4j
public class WebMvcConfiguration extends WebMvcConfigurationSupport {
@Autowired
private JwtTokenAdminInterceptor jwtTokenAdminInterceptor;
// ###新增配置
@Autowired
private WechatTokenUserInterceptor wechatTokenUserInterceptor;
/**
* 注册自定义拦截器
*
* @param registry
*/
protected void addInterceptors(InterceptorRegistry registry) {
log.info("开始注册自定义拦截器...");
registry.addInterceptor(jwtTokenAdminInterceptor)
.addPathPatterns("/admin/**")
.excludePathPatterns("/admin/employee/login","/admin/employee/logout");
// ###新增配置
registry.addInterceptor(wechatTokenUserInterceptor)
.addPathPatterns("/user/**")
.excludePathPatterns("/user/user/login","/user/shop/status");
}
/**
* 通过knife4j生成接口文档
* @return
*/
@Bean
public Docket docket() {
ApiInfo apiInfo = new ApiInfoBuilder()
.title("苍穹外卖项目接口文档")
.version("2.0")
.description("苍穹外卖项目接口文档")
.build();
Docket docket = new Docket(DocumentationType.SWAGGER_2)
.groupName("管理端接口")
.apiInfo(apiInfo)
.select()
.apis(RequestHandlerSelectors.basePackage("com.sky.controller.admin"))
.paths(PathSelectors.any())
.build();
return docket;
}
@Bean
public Docket docketUser() {
ApiInfo apiInfo = new ApiInfoBuilder()
.title("苍穹外卖项目接口文档")
.version("2.0")
.description("苍穹外卖项目接口文档")
.build();
Docket docket = new Docket(DocumentationType.SWAGGER_2)
.groupName("用户端接口")
.apiInfo(apiInfo)
.select()
.apis(RequestHandlerSelectors.basePackage("com.sky.controller.user"))
.paths(PathSelectors.any())
.build();
return docket;
}
/**
* 设置静态资源映射
* @param registry
*/
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/doc.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
/**
* 扩展Spring MVC的消息转化器,统一对后端返回给前端的数据进行处理;
* @param converters
*/
@Override
protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
log.info("扩展消息转换器......");
//创建一个消息转换器对象
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
//为消息转换器设置对象转换器,可以将Java对象序列化为JSON;
converter.setObjectMapper(new JacksonObjectMapper());
//将自己的消息转换器加入容器之中;并设置优先使用自己的消息转换器;
converters.add(0,converter);
}
}