From fefb4c3a850032f782a3f48609022fbffd0a555e Mon Sep 17 00:00:00 2001 From: wangw <1594593906@qq.com> Date: Tue, 4 Jun 2024 11:59:58 +0800 Subject: [PATCH] =?UTF-8?q?=E6=94=AF=E4=BB=98=E5=9B=9E=E8=B0=83=20?= =?UTF-8?q?=E8=8E=B7=E5=8F=96=E6=95=B0=E6=8D=AE=E5=88=97=E8=A1=A8=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3=E9=97=AE=E9=A2=98=20token=E6=9C=89=E6=95=88=E6=9C=9F?= =?UTF-8?q?=20=E5=8F=8A=20=E7=BB=AD=E6=9C=9F=20=E8=AE=A2=E5=8D=95=E8=AF=A6?= =?UTF-8?q?=E6=83=85=20=E4=B8=BAnull=E7=9A=84=E6=83=85=E5=86=B5=20?= =?UTF-8?q?=E6=A0=B9=E6=8D=AE=E6=A1=8C=E7=A0=81=E8=8E=B7=E5=8F=96shopid?= =?UTF-8?q?=E6=8E=A5=E5=8F=A3=E8=B0=83=E6=95=B4=20=E9=A6=96=E9=A1=B5=20?= =?UTF-8?q?=E9=BB=98=E8=AE=A4=E5=80=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../system/cashierservice/Shell.java | 4 +- .../cashierservice/auth/LoginFilter.java | 26 +++++-- .../controller/CommonController.java | 70 +++++++++++++++++-- .../controller/OrderController.java | 5 +- .../controller/ProductController.java | 8 +-- .../dao/TbCashierCartMapper.java | 2 - .../entity/dto/HomeBaseDto.java | 26 ++++++- .../cashierservice/rabbit/CartConsumer.java | 4 +- .../system/cashierservice/redis/RedisCst.java | 1 + .../cashierservice/redis/RedisUtil.java | 51 +++++++++++++- .../cashierservice/service/CartService.java | 5 +- .../cashierservice/service/LoginService.java | 2 +- .../cashierservice/service/PayService.java | 17 +++-- .../service/ProductService.java | 55 ++++++++------- .../socket/AppWebSocketServer.java | 61 +++++++++++----- .../cashierservice/util/RedisUtils.java | 5 ++ .../system/cashierservice/util/TokenUtil.java | 13 ++-- src/main/resources/application-dev.yml | 5 +- src/main/resources/application-dev2.yml | 3 + src/main/resources/application-prod.yml | 3 + src/main/resources/application-prod2.yml | 3 + src/main/resources/application.yml | 4 +- .../resources/mapper/TbCashierCartMapper.xml | 28 ++------ src/main/resources/mapper/TbProductMapper.xml | 1 + 24 files changed, 289 insertions(+), 113 deletions(-) diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/Shell.java b/src/main/java/com/chaozhanggui/system/cashierservice/Shell.java index 08e4839..7e62b24 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/Shell.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/Shell.java @@ -14,6 +14,7 @@ import org.springframework.context.ApplicationContext; import org.mybatis.spring.annotation.MapperScan; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; +import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.web.client.RestTemplate; @@ -26,11 +27,12 @@ import java.net.Socket; @EnableScheduling @EntityScan(basePackageClasses = {Shell.class}) @MapperScan(basePackageClasses ={Shell.class} ) -@ComponentScan(basePackageClasses ={Shell.class}) +//@ComponentScan(basePackageClasses ={Shell.class}) @EnableTransactionManagement @EnableAspectJAutoProxy(proxyTargetClass = true) @Slf4j @EnableWebSocket +@EnableAsync public class Shell { private static Logger logger = LoggerFactory.getLogger(Shell.class); diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/auth/LoginFilter.java b/src/main/java/com/chaozhanggui/system/cashierservice/auth/LoginFilter.java index ab31241..9b88dd8 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/auth/LoginFilter.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/auth/LoginFilter.java @@ -10,6 +10,7 @@ import com.chaozhanggui.system.cashierservice.util.TokenUtil; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; import javax.servlet.*; @@ -36,7 +37,7 @@ public class LoginFilter implements Filter { // 忽略静态资源 "css/**", "js/**", - "cashierService/websocket/table/**",//websocket + "cashierService/websocket/table",//websocket "cashierService/phoneValidateCode",//验证码 "cashierService/tbPlatformDict",//获取菜单 "cashierService/location/**",//高德 获取行政区域 @@ -45,7 +46,10 @@ public class LoginFilter implements Filter { "cashierService/order/testMessage",//首页 "cashierService/common/**",//通用接口 "cashierService/distirict/**",//首页其它接口 - "cashierService/login/**",//登录部分接口不校验 + +// "cashierService/login/**",//登录部分接口不校验 + "cashierService/login/wx/**",//登录部分接口不校验 + "cashierService/login/app/login",//登录部分接口不校验 "cashierService/product/queryProduct", "cashierService/product/queryProductSku", "cashierService/product/productInfo", @@ -95,16 +99,18 @@ public class LoginFilter implements Filter { return; } String message = ""; + String tokenKey=""; if(environment.equals("app")){ //获取当前登录人的用户id - String loginName = TokenUtil.parseParamFromToken(token).getString("userId"); + String userId = TokenUtil.parseParamFromToken(token).getString("userId"); + tokenKey=RedisCst.ONLINE_APP_USER.concat(userId); //获取redis中的token - message = redisUtil.getMessage(RedisCst.ONLINE_APP_USER.concat(loginName)); }else if(environment.equals("wx")){ //获取当前登录人的用户id String openId = TokenUtil.parseParamFromToken(token).getString("openId"); - message = redisUtil.getMessage(RedisCst.ONLINE_USER.concat(openId)); + tokenKey=RedisCst.ONLINE_USER.concat(openId); } + message = redisUtil.getMessage(tokenKey); if (StringUtils.isBlank(message)) { Result result = new Result(CodeEnum.TOKEN_EXPIRED); String jsonString = JSONObject.toJSONString(result); @@ -131,9 +137,19 @@ public class LoginFilter implements Filter { response.getWriter().flush();//流里边的缓存刷出 return; } + checkRenewal(tokenKey); chain.doFilter(req, resp); } + @Async + public void checkRenewal(String tokenKey) { + // 判断是否续期token,计算token的过期时间 + long time = redisUtil.getRemainingTime(tokenKey); + if(time<60*60*24*10L){ + redisUtil.setKeyExpirationTime(tokenKey,60*60*24*30L); + } + } + /** * 判断url请求是否配置在urls列表中 */ diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/controller/CommonController.java b/src/main/java/com/chaozhanggui/system/cashierservice/controller/CommonController.java index 3888625..eab2639 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/controller/CommonController.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/controller/CommonController.java @@ -4,11 +4,12 @@ import com.chaozhanggui.system.cashierservice.dao.TbPlatformDictMapper; import com.chaozhanggui.system.cashierservice.entity.TbPlatformDict; import com.chaozhanggui.system.cashierservice.entity.vo.DistrictVo; import com.chaozhanggui.system.cashierservice.exception.MsgException; +import com.chaozhanggui.system.cashierservice.redis.RedisCst; +import com.chaozhanggui.system.cashierservice.redis.RedisUtil; import com.chaozhanggui.system.cashierservice.service.FileService; import com.chaozhanggui.system.cashierservice.sign.CodeEnum; import com.chaozhanggui.system.cashierservice.sign.Result; import com.chaozhanggui.system.cashierservice.util.LocationUtils; -import com.chaozhanggui.system.cashierservice.util.RedisUtils; import com.chaozhanggui.system.cashierservice.util.StringUtil; import com.chaozhanggui.system.cashierservice.util.ValidateCodeUtil; import com.fasterxml.jackson.core.JsonProcessingException; @@ -16,12 +17,13 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.RequiredArgsConstructor; import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Async; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource; import java.util.List; -import java.util.concurrent.TimeUnit; /** * 通用接口 @@ -34,8 +36,9 @@ import java.util.concurrent.TimeUnit; public class CommonController { private final ValidateCodeUtil validateCodeUtil; - @Resource - private RedisUtils redisUtils; + + @Autowired + private RedisUtil redisUtil; @Resource private TbPlatformDictMapper platformDictMapper; @Resource @@ -52,15 +55,24 @@ public class CommonController { * @return */ @GetMapping("/phoneValidateCode") - public Result verifyPhoneIsExist(@RequestParam String phone) { + public Result phoneValidateCode(@RequestParam String phone) { if (StringUtils.isBlank(phone)) { return Result.fail("手机号不可为空!"); } + // 检查手机号格式是否正确 + if (!isValidPhoneNumber(phone)) { + return Result.fail("手机号格式不正确!"); + } + // 检查手机号请求次数是否超出限制 + Result isOk = isRequestLimit(phone); + if (!isOk.getCode().equals("0")) { + return isOk; + } String random = StringUtil.random(6); validateCodeUtil.requestValidateCodeAli(phone, random); //存入缓存 try { - redisUtils.set(phone, random, ONE_MINUTE, TimeUnit.SECONDS); + redisUtil.saveMessage(phone, random, 60L); } catch (Exception e) { throw new MsgException("验证码发送失败"); } @@ -119,4 +131,50 @@ public class CommonController { public Result upload(MultipartFile file) throws Exception { return new Result(CodeEnum.SUCCESS, fileService.uploadFile(file)); } + + // 检查手机号格式是否正确的方法 + private boolean isValidPhoneNumber(String phone) { + return phone.matches("^1[3-9]\\d{9}$"); + } + + // 检查手机号请求次数是否超出限制的方法 + public Result isRequestLimit(String phone) { + Object count = redisUtil.getMessage(RedisCst.PHONE_LIMIT + phone); + if (count != null && Integer.valueOf(count.toString()) >= 5) { + return Result.fail("请求次数超出限制!,请半小时后重试"); + } + long time = redisUtil.getRemainingTime(phone); + if (time > 0) { + return Result.fail("请" + time + "秒后重试"); + } + refreshPhoneLimit(phone,count != null); + return Result.success(CodeEnum.SUCCESS); + } + + // 从 Redis 中获取手机号码的请求次数的方法 + @Async + public void refreshPhoneLimit(String phone,boolean isExist) { + if (isExist) { + phoneRequestrinc(RedisCst.PHONE_LIMIT + phone); + } else { + phoneRequestset(RedisCst.PHONE_LIMIT + phone); + } + } + + /** + * 存储手机号和请求次数的对应关系 时间 半小时 + */ + public void phoneRequestset(String key) { + // 使用 Hash 结构存储手机号和请求次数的对应关系 时间 半小时 + redisUtil.saveMessage(key, "1", 60*30L); + } + + + /** + * 将手机号码的请求次数加1 + */ + public void phoneRequestrinc(String key) { + // 将手机号码的请求次数加1 + redisUtil.getIncrNum(key, "2"); + } } \ No newline at end of file diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/controller/OrderController.java b/src/main/java/com/chaozhanggui/system/cashierservice/controller/OrderController.java index e39372d..5ba73f7 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/controller/OrderController.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/controller/OrderController.java @@ -38,7 +38,10 @@ public class OrderController { * @return */ @GetMapping ("/orderInfo") - private Result orderInfo(@RequestParam Integer orderId){ + private Result orderInfo(@RequestParam(required = false) Integer orderId){ + if (orderId==null) { + return Result.fail("请返回首页订单列表查看"); + } return orderService.orderInfo(orderId); } diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/controller/ProductController.java b/src/main/java/com/chaozhanggui/system/cashierservice/controller/ProductController.java index d6ede94..3602a64 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/controller/ProductController.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/controller/ProductController.java @@ -30,10 +30,10 @@ public class ProductController { * @return shopid */ @RequestMapping("queryShopIdByTableCode") - public Result queryShopIdByTableCode(@RequestHeader String token, @RequestParam("code") String code) { - JSONObject jsonObject = TokenUtil.parseParamFromToken(token); - String userId = jsonObject.getString("userId"); - String openId = jsonObject.getString("openId"); + public Result queryShopIdByTableCode( + @RequestHeader("openId") String openId, + @RequestHeader("id") String userId, + @RequestParam("code") String code) { return productService.queryShopIdByTableCode(userId, openId, code); } diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbCashierCartMapper.java b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbCashierCartMapper.java index 5df9578..e9ed13b 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbCashierCartMapper.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/dao/TbCashierCartMapper.java @@ -20,8 +20,6 @@ public interface TbCashierCartMapper { int updateByPrimaryKeySelective(TbCashierCart record); - int updateByPrimaryKey(TbCashierCart record); - List selectALlByMasterId(@Param("masterId") String masterId, @Param("status") String status); diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/HomeBaseDto.java b/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/HomeBaseDto.java index cca7cbf..143c537 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/HomeBaseDto.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/entity/dto/HomeBaseDto.java @@ -1,7 +1,7 @@ package com.chaozhanggui.system.cashierservice.entity.dto; import lombok.Data; - +import org.apache.commons.lang3.StringUtils; /** @@ -27,4 +27,28 @@ public class HomeBaseDto extends BasePageDto{ private String distanceInKm; private Integer isPage = 1; + + public void setLat(String lat) { + if (StringUtils.isBlank(lat) || lat.equals("undefined")) { + this.lat = "34.343207"; + }else { + this.lat = lat; + } + } + + public void setLng(String lng) { + if (StringUtils.isBlank(lng) || lng.equals("undefined")) { + this.lng = "108.939645"; + }else { + this.lng = lng; + } + } + + public void setAddress(String address) { + if (StringUtils.isBlank(address) || address.equals("undefined")) { + this.address = "西安市"; + }else { + this.address = address; + } + } } diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/rabbit/CartConsumer.java b/src/main/java/com/chaozhanggui/system/cashierservice/rabbit/CartConsumer.java index 6aa17c7..d0d0e61 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/rabbit/CartConsumer.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/rabbit/CartConsumer.java @@ -30,6 +30,7 @@ public class CartConsumer { @RabbitListener(queues = {"${queue}"}) public void listener(String message) { try { + log.info("监听数据进入 "+message); JSONObject jsonObject = JSON.parseObject(message); String tableId = jsonObject.getString("tableId"); String shopId = jsonObject.getString("shopId"); @@ -70,7 +71,8 @@ public class CartConsumer { cartService.clearCart(jsonObject); } } catch (Exception e) { - e.getMessage(); + log.info("数据处理失败:{}",e.getMessage()); + e.printStackTrace(); } } diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/redis/RedisCst.java b/src/main/java/com/chaozhanggui/system/cashierservice/redis/RedisCst.java index 6cd4e31..8d73098 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/redis/RedisCst.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/redis/RedisCst.java @@ -10,6 +10,7 @@ public class RedisCst { //在线用户 public static final String ONLINE_USER = "ONLINE_USER:"; + public static final String PHONE_LIMIT = "PHONE_LIMIT:"; public static final String ONLINE_APP_USER = "ONLINE_APP_USER:"; public static final String LDBL_APP_VERSION = "LDBL_APP_VERSION:"; public static final String TABLE_CART = "TABLE:CART:"; diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/redis/RedisUtil.java b/src/main/java/com/chaozhanggui/system/cashierservice/redis/RedisUtil.java index d45af0f..784732c 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/redis/RedisUtil.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/redis/RedisUtil.java @@ -1,7 +1,5 @@ package com.chaozhanggui.system.cashierservice.redis; -import com.chaozhanggui.system.cashierservice.socket.AppWebSocketServer; -import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; @@ -112,7 +110,7 @@ public class RedisUtil{ * @author wgc * @date 2018-12-19 19:49 */ - public Integer saveMessage(String key, String message, int expire) { + public Integer saveMessage(String key, String message, Long expire) { Jedis jedis = null; try { if (StringUtils.isEmpty(key)) { @@ -162,6 +160,53 @@ public class RedisUtil{ } return flag; } + + /** + * 通过key 获取数据的剩余存活时间 + */ + public long getRemainingTime(String key) { + Jedis jedis = null; + long remainingTime = -1; + try { + // 从jedis池中获取一个jedis实例 + jedis = pool.getResource(); + if (database != 0) { + jedis.select(database); + } + + // 获取键的剩余生存时间 + remainingTime = jedis.ttl(key); + } catch (Exception e) { + e.printStackTrace(); + } finally { + // 释放对象池,即获取jedis实例使用后要将对象还回去 + if (jedis != null) { + jedis.close(); + } + } + return remainingTime; + } + + public void setKeyExpirationTime(String key, long seconds) { + Jedis jedis = null; + try { + // 从jedis池中获取一个jedis实例 + jedis = pool.getResource(); + if (database != 0) { + jedis.select(database); + } + // 设置键的存活时间 + jedis.expire(key, seconds); + } catch (Exception e) { + e.printStackTrace(); + } finally { + // 释放对象池,即获取jedis实例使用后要将对象还回去 + if (jedis != null) { + jedis.close(); + } + } + } + /** * @param key * @param message diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/service/CartService.java b/src/main/java/com/chaozhanggui/system/cashierservice/service/CartService.java index 19cd361..d0910d1 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/service/CartService.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/service/CartService.java @@ -104,6 +104,7 @@ public class CartService { TbCashierCart cashierCart = JSONUtil.parseJSONStr2T(object.toJSONString(), TbCashierCart.class); if (cashierCart.getNumber() > 0) { cashierCart.setTotalAmount(new BigDecimal(cashierCart.getTotalNumber()).multiply(cashierCart.getSalePrice().add(cashierCart.getPackFee()))); + cashierCart.setUserId(jsonObject.getIntValue("userId")); if (StringUtils.isNotEmpty(cashierCart.getStatus())) { cashierCart.setStatus("create"); } @@ -150,6 +151,7 @@ public class CartService { private TbCashierCart addCart(String productId, String skuId, Integer userId, Integer num, String tableId, String shopId) throws Exception { try { + //productId 235 skuId 85 userId 78 num 1 tableId 55246240 shopId 10 TbProduct product = productMapper.selectById(Integer.valueOf(productId)); String key=tableId+"-"+shopId; if (Objects.isNull(product)) { @@ -182,7 +184,6 @@ public class CartService { cashierCart.setSkuName(productSku.getSpecSnap()); cashierCart.setIsPack("false"); cashierCart.setIsGift("false"); - cashierCart.setUserId(userId); cashierCart.setStatus("create"); cashierCart.setType((byte) 0); cashierCart.setSalePrice(productSku.getSalePrice()); @@ -694,7 +695,7 @@ public class CartService { jsonObject1.put("type", jsonObject.getString("type")); jsonObject1.put("data", orderInfo); redisUtil.deleteByKey(RedisCst.TABLE_CART.concat(jsonObject.getString("tableId")).concat("-").concat(shopId)); - redisUtil.saveMessage(RedisCst.TABLE_ORDER.concat(orderInfo.getOrderNo()), JSONObject.toJSONString(orderInfo), 24 * 60 * 60); + redisUtil.saveMessage(RedisCst.TABLE_ORDER.concat(orderInfo.getOrderNo()), JSONObject.toJSONString(orderInfo), 24 * 60 * 60L); AppWebSocketServer.AppSendInfo(jsonObject1,key, jsonObject.getString("userId"), true); JSONObject jsonObject12 = new JSONObject(); jsonObject12.put("status", "success"); diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/service/LoginService.java b/src/main/java/com/chaozhanggui/system/cashierservice/service/LoginService.java index 7f78ca2..d6d5a94 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/service/LoginService.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/service/LoginService.java @@ -125,7 +125,7 @@ public class LoginService { try { map.put("token", token); map.put("userInfo", userInfo); - redisUtil.saveMessage(RedisCst.ONLINE_USER.concat(openId), JSON.toJSONString(map)); + redisUtil.saveMessage(RedisCst.ONLINE_USER.concat(openId), JSON.toJSONString(map),60*60*24*30L); //redis里 获取要关注的公众号信息 //userInfo 某字段存储关注公众号的标识 // userInfo.get diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/service/PayService.java b/src/main/java/com/chaozhanggui/system/cashierservice/service/PayService.java index 61f8b90..34ae139 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/service/PayService.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/service/PayService.java @@ -312,9 +312,10 @@ public class PayService { return Result.fail("未获取到用户信息"); } - - - + if(StringUtils.isBlank(userInfo.getPwd())){ +// return Result.fail("支付密码未设置"); + return Result.success(CodeEnum.SUCCESS,"3"); + } if(!userInfo.getPwd().equals(MD5Utils.md5(pwd))){ return Result.fail("支付密码错误"); } @@ -332,12 +333,14 @@ public class PayService { TbShopUser user = tbShopUserMapper.selectByPrimaryKey(memberId); - if (ObjectUtil.isEmpty(user) || !"1".equals(user.getIsVip().toString())) { - return Result.failCode("会员卡余额不足","1"); + if (ObjectUtil.isEmpty(user) || user.getIsVip()==null || !"1".equals(user.getIsVip().toString())) { +// return Result.failCode("会员卡余额不足","1"); + return Result.success(CodeEnum.SUCCESS,"4"); } if (N.gt(orderInfo.getOrderAmount(), user.getAmount())) { - return Result.failCode("会员卡余额不足","2"); +// return Result.failCode("会员卡余额不足","2"); + return Result.success(CodeEnum.SUCCESS,"2"); } user.setAmount(user.getAmount().subtract(orderInfo.getOrderAmount())); @@ -382,7 +385,7 @@ public class PayService { producer.printMechine(orderId); - return Result.success(CodeEnum.SUCCESS); + return Result.success(CodeEnum.SUCCESS,"1"); } diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/service/ProductService.java b/src/main/java/com/chaozhanggui/system/cashierservice/service/ProductService.java index d850127..ea1f497 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/service/ProductService.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/service/ProductService.java @@ -75,31 +75,36 @@ public class ProductService { } TbShopUser tbShopUser = tbShopUserMapper.selectByUserIdAndShopId(userId, shopId); - if (ObjectUtil.isEmpty(tbShopUser)) { - TbUserInfo tbUserInfo = tbUserInfoMapper.selectByPrimaryKey(Integer.valueOf(userId)); - tbShopUser = new TbShopUser(); - tbShopUser.setName(tbUserInfo.getNickName()); - tbShopUser.setSex(tbUserInfo.getSex()); - tbShopUser.setBirthDay(tbUserInfo.getBirthDay()); - tbShopUser.setLevel(Byte.parseByte("1")); - tbShopUser.setCode(RandomUtil.randomNumbers(8)); - tbShopUser.setTelephone(tbUserInfo.getTelephone()); - tbShopUser.setAmount(BigDecimal.ZERO); - tbShopUser.setIsVip(Byte.parseByte("0")); - tbShopUser.setCreditAmount(BigDecimal.ZERO); - tbShopUser.setConsumeAmount(BigDecimal.ZERO); - tbShopUser.setConsumeNumber(0); - tbShopUser.setLevelConsume(BigDecimal.ZERO); - tbShopUser.setStatus(Byte.parseByte("1")); - tbShopUser.setShopId(shopId); - tbShopUser.setUserId(userId); - tbShopUser.setMiniOpenId(openId); - tbShopUser.setCreatedAt(System.currentTimeMillis()); - tbShopUser.setUpdatedAt(System.currentTimeMillis()); - tbShopUserMapper.insert(tbShopUser); - } else { - tbShopUser.setUpdatedAt(System.currentTimeMillis()); - tbShopUserMapper.updateByPrimaryKey(tbShopUser); + try{ + if (ObjectUtil.isEmpty(tbShopUser)) { + TbUserInfo tbUserInfo = tbUserInfoMapper.selectByPrimaryKey(Integer.valueOf(userId)); + tbShopUser = new TbShopUser(); + tbShopUser.setName(tbUserInfo.getNickName()); + tbShopUser.setSex(tbUserInfo.getSex()); + tbShopUser.setBirthDay(tbUserInfo.getBirthDay()); + tbShopUser.setLevel(Byte.parseByte("1")); + tbShopUser.setCode(RandomUtil.randomNumbers(8)); + tbShopUser.setTelephone(tbUserInfo.getTelephone()); + tbShopUser.setAmount(BigDecimal.ZERO); + tbShopUser.setIsVip(Byte.parseByte("0")); + tbShopUser.setCreditAmount(BigDecimal.ZERO); + tbShopUser.setConsumeAmount(BigDecimal.ZERO); + tbShopUser.setConsumeNumber(0); + tbShopUser.setLevelConsume(BigDecimal.ZERO); + tbShopUser.setStatus(Byte.parseByte("1")); + tbShopUser.setShopId(shopId); + tbShopUser.setUserId(userId); + tbShopUser.setMiniOpenId(openId); + tbShopUser.setCreatedAt(System.currentTimeMillis()); + tbShopUser.setUpdatedAt(System.currentTimeMillis()); + tbShopUserMapper.insert(tbShopUser); + } else { + tbShopUser.setUpdatedAt(System.currentTimeMillis()); + tbShopUserMapper.updateByPrimaryKey(tbShopUser); + } + }catch (Exception e){ + log.info("通过桌码获取shopId 进行用户绑定错误:{}",e.getMessage()); + e.printStackTrace(); } return Result.success(CodeEnum.SUCCESS, shopId); } diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/socket/AppWebSocketServer.java b/src/main/java/com/chaozhanggui/system/cashierservice/socket/AppWebSocketServer.java index 2ad5ca7..018e144 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/socket/AppWebSocketServer.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/socket/AppWebSocketServer.java @@ -29,7 +29,7 @@ import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; -@ServerEndpoint(value = "/websocket/table/{tableId}/{shopId}/{userId}", encoders = WebSocketCustomEncoding.class) +@ServerEndpoint(value = "/websocket/table", encoders = WebSocketCustomEncoding.class) @Component @Slf4j @Data @@ -56,10 +56,6 @@ public class AppWebSocketServer { //一个 AppWebSocketServer 就是一个用户,一个tableId下有一个 List 也就是多个用户 private static HashMap> webSocketMap = new HashMap<>(); public static ConcurrentHashMap> userMap = new ConcurrentHashMap<>(); -// private static ConcurrentHashMap userSocketMap = new ConcurrentHashMap<>(); - //购物车的记录,用于第一次扫码的人同步购物车 -// private static ConcurrentHashMap> recordMap = new ConcurrentHashMap<>(); -// private static ConcurrentHashMap sessionMap = new ConcurrentHashMap<>(); /** * 与某个客户端的连接会话,需要通过它来给客户端发送数据 @@ -85,9 +81,16 @@ public class AppWebSocketServer { * 连接建立成功调用的方法 */ @OnOpen - public void onOpen(Session session, @PathParam("tableId") String tableId, @PathParam("shopId") String shopId, @PathParam("userId") String userId) { - log.info("建立连接参数 tableId:{} shopId:{} userId:{}",tableId,shopId,userId); + public void onOpen(Session session) { this.session = session; + log.info("建立连接开始"); +// public void onOpen(Session session, @PathParam("tableId") String tableId, @PathParam("shopId") String shopId, @PathParam("userId") String userId) { + Map queryParams = getParamMap(); + String tableId = queryParams.get("tableId"); + String shopId = queryParams.get("shopId"); + String userId = queryParams.get("userId"); + + log.info("建立连接参数 tableId:{} shopId:{} userId:{}",tableId,shopId,userId); this.tableId = tableId; this.shopId = shopId; this.userId = userId; @@ -115,13 +118,13 @@ public class AppWebSocketServer { webSocketMap.put(key,userSocketMap); } - if (userMap.containsKey(key)) { - Set userSet = userMap.get(key); + if (userMap.containsKey(tableId)) { + Set userSet = userMap.get(tableId); userSet.add(userId); } else { Set userSet = new HashSet<>(); userSet.add(userId); - userMap.put(key,userSet); + userMap.put(tableId,userSet); } String mes = redisUtils.getMessage(RedisCst.TABLE_CART.concat(key)); if (StringUtils.isEmpty(mes)) { @@ -166,8 +169,8 @@ public class AppWebSocketServer { userSocketMap.remove(userId); log.info("存在的 {}用户数3为:{}",key,userSocketMap.size()); } - if (userMap.containsKey(tableId + "-" + shopId)){ - Set userSet = userMap.get(tableId + "-" + shopId); + if (userMap.containsKey(tableId)){ + Set userSet = userMap.get(tableId); userSet.remove(userId); // if (userSet.isEmpty()){ // userMap.remove(tableId + "-" + shopId); @@ -182,8 +185,7 @@ public class AppWebSocketServer { */ @OnMessage public void onMessage(String message, Session session) { - - log.info("接收消息:"+message); + log.info("接收消息 tableId:{} shopId:{} userId:{} message:{}",this.tableId,this.shopId,this.userId,message); //可以群发消息 //消息保存到数据库、redis if (StringUtils.isNotBlank(message) && !message.equals("undefined")) { @@ -196,10 +198,10 @@ public class AppWebSocketServer { //追加发送人(防止串改) jsonObject.put("tableId", this.tableId); jsonObject.put("shopId", this.shopId); - log.info("tableId:"+this.tableId); - log.info("shopId:"+this.shopId); - if (userMap.containsKey(tableId + "-" + shopId)) { - Set userSet = userMap.get(tableId + "-" + shopId); +// log.info("tableId:"+this.tableId); +// log.info("shopId:"+this.shopId); + if (userMap.containsKey(tableId)) { + Set userSet = userMap.get(tableId); userSet.add(userId); } if (webSocketMap.containsKey(tableId+"-"+shopId)) { @@ -258,6 +260,7 @@ public class AppWebSocketServer { @OnError public void onError(Session session, Throwable error) throws IOException { log.error("用户错误:" + this.tableId + ",原因:" + error.getMessage()); +// error.printStackTrace(); } /** @@ -289,7 +292,7 @@ public class AppWebSocketServer { * @throws IOException */ public static void AppSendInfo(Object message, String tableId,String userId, boolean userFlag) throws IOException { - log.info("发送消息 tableId:{} \n userId:{}\n userFlag:{}\n message:{}",tableId,userId,userFlag,JSONUtil.toJSONString(message)); + log.info("发送消息 tableId:{} userId:{} userFlag:{} message:{}",tableId,userId,userFlag,JSONUtil.toJSONString(message)); if (userFlag) { if (webSocketMap.containsKey(tableId)) { ConcurrentHashMap userSocketMap = webSocketMap.get(tableId); @@ -325,6 +328,26 @@ public class AppWebSocketServer { } + public Map getParamMap(){ + // 获取连接建立时传递的参数 + Map> queryParams = session.getRequestParameterMap(); + // 创建新的Map来存储转换后的参数 + Map parameterMap = new HashMap<>(); + + // 遍历原始参数Map的键值对 + for (Map.Entry> entry : queryParams.entrySet()) { + String key = entry.getKey(); + List values = entry.getValue(); + + // 如果值列表不为空,则将第一个值作为键的值存储在新的Map中 + if (!values.isEmpty()) { + String value = values.get(0); + parameterMap.put(key, value); + } + } + return parameterMap; + } + // public static synchronized ConcurrentHashMap> getWebSocketMap() { // return AppWebSocketServer.webSocketMap; diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/util/RedisUtils.java b/src/main/java/com/chaozhanggui/system/cashierservice/util/RedisUtils.java index 21a5920..5d71683 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/util/RedisUtils.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/util/RedisUtils.java @@ -286,6 +286,11 @@ public class RedisUtils { return false; } } + + public Long strincrement(String key, long delta) { + return stringRedisTemplate.opsForValue().increment(key, delta); + } + /** * 普通缓存放入并设置时间 * diff --git a/src/main/java/com/chaozhanggui/system/cashierservice/util/TokenUtil.java b/src/main/java/com/chaozhanggui/system/cashierservice/util/TokenUtil.java index 16f3bdc..26cc779 100644 --- a/src/main/java/com/chaozhanggui/system/cashierservice/util/TokenUtil.java +++ b/src/main/java/com/chaozhanggui/system/cashierservice/util/TokenUtil.java @@ -1,16 +1,12 @@ package com.chaozhanggui.system.cashierservice.util; -import cn.hutool.core.util.IdUtil; import cn.hutool.core.util.ObjectUtil; import com.alibaba.fastjson.JSONObject; import io.jsonwebtoken.Claims; -import io.jsonwebtoken.JwtBuilder; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import lombok.extern.slf4j.Slf4j; -import java.text.SimpleDateFormat; -import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Map; @@ -25,7 +21,7 @@ public class TokenUtil { /** * 设置过期时间 */ - public static final long EXPIRE_DATE=24*60*60*1000*365; + public static final long EXPIRE_DATE=24L*60*60*1000*365; /** * token秘钥 */ @@ -65,10 +61,10 @@ public class TokenUtil { * @param claims * @return String */ - private static String generateToken(Map claims) throws Exception { + private static String generateToken(Map claims) { return Jwts.builder() .setClaims(claims) -// .setExpiration(new Date(System.currentTimeMillis()+EXPIRE_DATE)) + .setExpiration(new Date(System.currentTimeMillis()+EXPIRE_DATE)) .setIssuedAt(new Date()) .signWith(SignatureAlgorithm.HS256,TOKEN_SECRET) .compact(); @@ -117,12 +113,13 @@ public class TokenUtil { jsonObject = (JSONObject) JSONObject.toJSON(claims); }catch (Exception e){ jsonObject.put("status","-4"); + jsonObject.put("message","token解析失败了"); log.info("token解析失败{}",e.getMessage()); e.printStackTrace(); } return jsonObject; } -// public static void main(String[] args){ +// public static void main(String[] args) throws Exception { // System.out.println(refreshToken("eyJhbGciOiJIUzUxMiJ9.eyJleHAiOjE1OTY4Nzc5MjEsInN1YiI6ImRkZGRkIiwiaWF0IjoxNTk2Njk3OTIxfQ.lrg3KF9h9izbmyD2q5onqnZIKBqanWy9xCcroFpjxPKmJz6kz27G9lVlFpVanrL1I4SFf3Dz3q3Xu01DX2T_dw")); // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // Calendar cld = Calendar.getInstance(); diff --git a/src/main/resources/application-dev.yml b/src/main/resources/application-dev.yml index 38086ab..9d7ee4d 100644 --- a/src/main/resources/application-dev.yml +++ b/src/main/resources/application-dev.yml @@ -58,8 +58,11 @@ ysk: callBackGroupurl: https://wxcashiertest.sxczgkj.cn/cashierService/notify/notifyCallBackGroup callBackIn: https://p40312246f.goho.co/cashierService/notify/memberInCallBack default: 18710449883 +thirdPay: + callInBack: https://wxcashiertest.sxczgkj.cn/cashierService/notify/fstmemberInCallBack + callFSTBack: https://wxcashiertest.sxczgkj.cn/cashierService/notify/notifyfstCallBack server: - port: 9889 + port: 9888 prod: dev1 queue: cart_queue_putdev1 diff --git a/src/main/resources/application-dev2.yml b/src/main/resources/application-dev2.yml index 3287e1e..73b6469 100644 --- a/src/main/resources/application-dev2.yml +++ b/src/main/resources/application-dev2.yml @@ -55,6 +55,9 @@ ysk: callBackGroupurl: https://wxcashiertest.sxczgkj.cn/cashierService/notify/notifyCallBackGroup callBackIn: https://p40312246f.goho.co/cashierService/notify/memberInCallBack default: 18710449883 +thirdPay: + callInBack: https://wxcashiertest.sxczgkj.cn/cashierService/notify/fstmemberInCallBack + callFSTBack: https://wxcashiertest.sxczgkj.cn/cashierService/notify/notifyfstCallBack server: port: 9889 prod: devyhq diff --git a/src/main/resources/application-prod.yml b/src/main/resources/application-prod.yml index f6eccf5..5ac4ba2 100644 --- a/src/main/resources/application-prod.yml +++ b/src/main/resources/application-prod.yml @@ -57,6 +57,9 @@ ysk: callBackGroupurl: https://cashier.sxczgkj.cn/cashierService/notify/notifyCallBackGroup callBackIn: https://cashier.sxczgkj.cn/cashierService/notify/memberInCallBack default: 19191703856 +thirdPay: + callInBack: https://cashier.sxczgkj.cn${server.servlet.context-path}notify/fstmemberInCallBack + callFSTBack: https://cashier.sxczgkj.cn${server.servlet.context-path}notify/notifyfstCallBack prod: prod1 queue: cart_queue_putprod1 diff --git a/src/main/resources/application-prod2.yml b/src/main/resources/application-prod2.yml index 27b9d53..7c8aa90 100644 --- a/src/main/resources/application-prod2.yml +++ b/src/main/resources/application-prod2.yml @@ -57,6 +57,9 @@ ysk: callBackGroupurl: https://cashier.sxczgkj.cn/cashierService/notify/notifyCallBackGroup callBackIn: https://cashier.sxczgkj.cn/cashierService/notify/memberInCallBack default: 19191703856 +thirdPay: + callInBack: https://cashier.sxczgkj.cn${server.servlet.context-path}notify/fstmemberInCallBack + callFSTBack: https://cashier.sxczgkj.cn${server.servlet.context-path}notify/notifyfstCallBack prod: prod2 queue: cart_queue_putprod2 diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 0d3801d..edc4599 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -10,6 +10,8 @@ wx: custom: appId: wxd88fffa983758a30 secrete: a34a61adc0602118b49400baa8812454 +# appId: wxc2bb94c0ddda1032 +# secrete: 5fe6b30f688ae461561250ed3e3db35b # 卓尔 # appId: wx0dcea6001b0a8fb4 # secrete: ba42423cce61f93f02519ff3030ceb1c @@ -60,6 +62,4 @@ aliyun: thirdPay: payType: fushangtong - callInBack: https://cashier.sxczgkj.cn${server.servlet.context-path}notify/fstmemberInCallBack - callFSTBack: https://cashier.sxczgkj.cn${server.servlet.context-path}notify/notifyfstCallBack url: https://paymentapi.sxczgkj.cn diff --git a/src/main/resources/mapper/TbCashierCartMapper.xml b/src/main/resources/mapper/TbCashierCartMapper.xml index 202975b..ae726ec 100644 --- a/src/main/resources/mapper/TbCashierCartMapper.xml +++ b/src/main/resources/mapper/TbCashierCartMapper.xml @@ -310,6 +310,9 @@ updated_at = #{updatedAt,jdbcType=BIGINT}, + + user_id=#{userId,jdbcType=INTEGER}, + pending_at = #{pendingAt,jdbcType=BIGINT}, @@ -322,30 +325,7 @@ where id = #{id,jdbcType=INTEGER} - - update tb_cashier_cart - set master_id = #{masterId,jdbcType=VARCHAR}, - order_id = #{orderId,jdbcType=VARCHAR}, - ref_order_id = #{refOrderId,jdbcType=VARCHAR}, - total_amount = #{totalAmount,jdbcType=DECIMAL}, - product_id = #{productId,jdbcType=VARCHAR}, - cover_img = #{coverImg,jdbcType=VARCHAR}, - is_sku = #{isSku,jdbcType=TINYINT}, - sku_id = #{skuId,jdbcType=VARCHAR}, - name = #{name,jdbcType=VARCHAR}, - sale_price = #{salePrice,jdbcType=DECIMAL}, - number = #{number,jdbcType=REAL}, - total_number = #{totalNumber,jdbcType=REAL}, - refund_number = #{refundNumber,jdbcType=REAL}, - category_id = #{categoryId,jdbcType=VARCHAR}, - status = #{status,jdbcType=VARCHAR}, - type = #{type,jdbcType=TINYINT}, - merchant_id = #{merchantId,jdbcType=VARCHAR}, - shop_id = #{shopId,jdbcType=VARCHAR}, - created_at = #{createdAt,jdbcType=BIGINT}, - updated_at = #{updatedAt,jdbcType=BIGINT} - where id = #{id,jdbcType=INTEGER} - + update tb_cashier_cart set status = #{status} where id = #{id} diff --git a/src/main/resources/mapper/TbProductMapper.xml b/src/main/resources/mapper/TbProductMapper.xml index 9c2c15f..61aa81b 100644 --- a/src/main/resources/mapper/TbProductMapper.xml +++ b/src/main/resources/mapper/TbProductMapper.xml @@ -924,6 +924,7 @@ AND t.product_id = #{productId} AND t.`status` = 'create' AND t.table_id = #{code} + AND user_id IN #{item}