1.代客下单 创建订单增加锁

2.代客下单 主扫支付
This commit is contained in:
2024-09-02 14:50:40 +08:00
parent 94e875008b
commit be4f8cbbdd
13 changed files with 902 additions and 259 deletions

View File

@@ -0,0 +1,25 @@
package cn.ysk.cashier.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
@Configuration//加上这个注解作用可以被Spring扫描
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory){
return new RestTemplate(factory);
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setReadTimeout(500000);//单位为ms
factory.setConnectTimeout(500000);//单位为ms
return factory;
}
}

View File

@@ -18,6 +18,9 @@ public interface RedisConstant {
String ADD_TABLE_CART_LOCK = "ADD_TABLE_CART";
String PC_OUT_NUMBER = "PC_OUT_NUMBER:";
String LOCK_KEY = "LOCK:";
String CREATE_ORDER = "CREATE_ORDER";
static String getCurrentOrderKey(String tableId, String shopId) {
return CURRENT_TABLE_ORDER + shopId + ":" + tableId;
@@ -26,4 +29,12 @@ public interface RedisConstant {
static String getTableCartKey(String tableId, String shopId) {
return TABLE_CART + tableId + "-" + shopId;
}
static String getLockKey(String sign, Object... args) {
StringBuilder key = new StringBuilder(LOCK_KEY + ":" + sign + ":");
for (Object arg : args) {
key.append(":").append(arg.toString());
}
return key.toString();
}
}

View File

@@ -0,0 +1,7 @@
package cn.ysk.cashier.mybatis.mapper;
import cn.ysk.cashier.mybatis.entity.TbOrderPayment;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
public interface MpOrderPaymentMapper extends BaseMapper<TbOrderPayment> {
}

View File

@@ -0,0 +1,51 @@
package cn.ysk.cashier.mybatis.vo.pay;
import lombok.Data;
import java.io.Serializable;
import java.util.ArrayList;
@Data
public class MainScanReq implements Serializable {
private String subject;
private String body;
private Long amount;
private String subAppid;
private String currency;
private String authCode;
private String mchOrderNo;
private String storeId;
private String notifyUrl;
private int divisionMode;
private ArrayList divList;
private String divTemplateNo;
public MainScanReq(String subject, String body, Long amount, String subAppid, String currency, String authCode, String mchOrderNo, String storeId, String notifyUrl, int divisionMode, String divTemplateNo, ArrayList divList) {
this.subject = subject;
this.body = body;
this.amount = amount;
this.subAppid = subAppid;
this.currency = currency;
this.authCode = authCode;
this.mchOrderNo = mchOrderNo;
this.storeId = storeId;
this.notifyUrl = notifyUrl;
this.divisionMode=divisionMode;
this.divList=divList;
this.divTemplateNo=divTemplateNo;
}
}

View File

@@ -0,0 +1,47 @@
package cn.ysk.cashier.mybatis.vo.pay;
import lombok.Data;
import java.io.Serializable;
@Data
public class MainScanResp implements Serializable {
private Long amount;
private String mchOrderNo;
private String payOrderId;
private String mercNo;
private String channelSendNo;
private String channelTradeNo;
private String state;
private String payType;
private String ifCode;
private String extParam;
private String note;
private String tradeFee;
private String storeId;
private String subject;
private String drType;
private Long refundAmt;
private Integer refundState;
private Long cashFee;
private String settlementType;
}

View File

@@ -0,0 +1,13 @@
package cn.ysk.cashier.pojo.order;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.persistence.Table;
@EqualsAndHashCode(callSuper = true)
@Data
public class TbFullOrderDetail extends TbOrderDetail{
private boolean isPack;
private boolean isGift;
}

View File

@@ -1,6 +1,7 @@
package cn.ysk.cashier.repository.order;
import cn.ysk.cashier.dto.product.StockCountDTO;
import cn.ysk.cashier.pojo.order.TbFullOrderDetail;
import cn.ysk.cashier.pojo.order.TbOrderDetail;
import cn.ysk.cashier.vo.TbOrderPayCountVo;
import cn.ysk.cashier.vo.TbOrderSaleVO;
@@ -36,6 +37,7 @@ public interface TbOrderDetailRepository extends JpaRepository<TbOrderDetail, In
@Query("SELECT cart FROM TbOrderDetail cart WHERE cart.orderId = :orderId")
List<TbOrderDetail> searchDetailByOrderId(@Param("orderId")Integer orderId);
@Query("SELECT cart FROM TbOrderDetail cart WHERE cart.orderId in :ids")
List<TbOrderDetail> searchDetailByOrderIds(@Param("ids")List<Integer> ids);

View File

@@ -2,6 +2,7 @@ package cn.ysk.cashier.service.impl;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.ysk.cashier.dto.ScanPayDTO;
import cn.ysk.cashier.dto.shoptable.PayDTO;
import cn.ysk.cashier.enums.TableStateEnum;
@@ -11,6 +12,9 @@ import cn.ysk.cashier.mybatis.entity.TbOrderPayment;
import cn.ysk.cashier.mybatis.entity.TbShopUserFlow;
import cn.ysk.cashier.mybatis.mapper.*;
import cn.ysk.cashier.mybatis.service.TbOrderPaymentService;
import cn.ysk.cashier.mybatis.vo.pay.MainScanReq;
import cn.ysk.cashier.mybatis.vo.pay.MainScanResp;
import cn.ysk.cashier.mybatis.vo.pay.ScanPayReq;
import cn.ysk.cashier.pojo.TbShopPayType;
import cn.ysk.cashier.pojo.order.TbCashierCart;
import cn.ysk.cashier.pojo.order.TbOrderDetail;
@@ -19,32 +23,45 @@ import cn.ysk.cashier.pojo.shop.TbMerchantThirdApply;
import cn.ysk.cashier.pojo.shop.TbShopTable;
import cn.ysk.cashier.repository.shop.TbMerchantThirdApplyRepository;
import cn.ysk.cashier.service.TbPayService;
import cn.ysk.cashier.utils.RabbitMsgUtils;
import cn.ysk.cashier.utils.SnowFlakeUtil;
import cn.ysk.cashier.thirdpay.constants.SignTypeEnum;
import cn.ysk.cashier.thirdpay.req.PublicParam;
import cn.ysk.cashier.thirdpay.resp.PublicResp;
import cn.ysk.cashier.thirdpay.service.ThirdPayService;
import cn.ysk.cashier.utils.*;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Map;
import static cn.ysk.cashier.thirdpay.service.ThirdPayService.sortFields;
import static cn.ysk.cashier.thirdpay.service.ThirdPayService.sortFieldsAndPrint;
@Service
@Slf4j
public class TbPayServiceImpl implements TbPayService {
// @Value("${gateway.url}")
// private String gateWayUrl;
// @Value("${client.backUrl}")
// private String backUrl;
// @Value("${thirdPay.payType}")
// private String thirdPayType;
// @Value("${thirdPay.url}")
// private String url;
// @Value("${thirdPay.callBack}")
// private String callBack;
@Value("${gateway.url}")
private String gateWayUrl;
@Value("${client.backUrl}")
private String backUrl;
@Value("${thirdPay.payType}")
private String thirdPayType;
@Value("${thirdPay.url}")
private String url;
@Value("${thirdPay.callBack}")
private String callBack;
private final TbOrderInfoMapper orderInfoMapper;
private final TbCashierCartMapper cashierCartMapper;
@@ -55,10 +72,13 @@ public class TbPayServiceImpl implements TbPayService {
private final RabbitTemplate rabbitTemplate;
private final RabbitMsgUtils rabbitMsgUtils;
private final MpShopTableMapper mpShopTableMapper;
private final RestTemplate restTemplate;
private final MpOrderPaymentMapper mpOrderPaymentMapper;
private final ThirdPayService thirdPayService;
public TbPayServiceImpl(TbOrderInfoMapper orderInfoMapper, TbCashierCartMapper cashierCartMapper, TbMerchantThirdApplyRepository merchantThirdApplyRepository, TbOrderPaymentService orderPaymentService, TbShopPayTypeMapper shopPayTypeMapper, TbOrderDetailMapper orderDetailMapper, RabbitTemplate rabbitTemplate, RabbitMsgUtils rabbitMsgUtils, MpShopTableMapper mpShopTableMapper, TbMShopUserMapper shopUserMapper, TbShopUserFlowMapper shopUserFlowMapper) {
public TbPayServiceImpl(TbOrderInfoMapper orderInfoMapper, TbCashierCartMapper cashierCartMapper, TbMerchantThirdApplyRepository merchantThirdApplyRepository, TbOrderPaymentService orderPaymentService, TbShopPayTypeMapper shopPayTypeMapper, TbOrderDetailMapper orderDetailMapper, RabbitTemplate rabbitTemplate, RabbitMsgUtils rabbitMsgUtils, MpShopTableMapper mpShopTableMapper, RestTemplate restTemplate, MpOrderPaymentMapper mpOrderPaymentMapper, ThirdPayService thirdPayService, TbMShopUserMapper shopUserMapper, TbShopUserFlowMapper shopUserFlowMapper) {
this.orderInfoMapper = orderInfoMapper;
this.cashierCartMapper = cashierCartMapper;
this.merchantThirdApplyRepository = merchantThirdApplyRepository;
@@ -68,6 +88,9 @@ public class TbPayServiceImpl implements TbPayService {
this.rabbitTemplate = rabbitTemplate;
this.rabbitMsgUtils = rabbitMsgUtils;
this.mpShopTableMapper = mpShopTableMapper;
this.restTemplate = restTemplate;
this.mpOrderPaymentMapper = mpOrderPaymentMapper;
this.thirdPayService = thirdPayService;
this.shopUserMapper = shopUserMapper;
this.shopUserFlowMapper = shopUserFlowMapper;
}
@@ -209,31 +232,33 @@ public class TbPayServiceImpl implements TbPayService {
// JSONObject jsonObject = new JSONObject();
// jsonObject.put("type", "create");
// jsonObject.put("orderId", scanPayDTO.getOrderId());
//
// rabbitMsgUtils.sendOrderCollectMsg(jsonObject);
// rabbitMsgUtils.printTicket(scanPayDTO.getOrderId().toString());
//
//
// producer.printMechine(orderId);
//
// return Result.success(CodeEnum.SUCCESS, object.getJSONObject("data"));
// } else {
// String status = ObjectUtil.isNotEmpty(object.getJSONObject("data")) ? object.getJSONObject("data").getString("status") : null;
// if (ObjectUtil.isNotNull(status) && "7".equals(status)) {
//
// orderInfo.setStatus("paying");
// orderInfo.setPayOrderNo(payment.getTradeNumber());
// tbOrderInfoMapper.updateByPrimaryKeySelective(orderInfo);
// orderInfoMapper.updateById(orderInfo);
//
// payment.setTradeNumber(object.getJSONObject("data").get("orderNumber").toString());
// payment.setUpdatedAt(System.currentTimeMillis());
// tbOrderPaymentMapper.updateByPrimaryKeySelective(payment);
// return Result.success(CodeEnum.PAYING);
// mpOrderPaymentMapper.updateById(payment);
//
//
// // 修改台桌状态
// mpShopTableMapper.update(null, new LambdaUpdateWrapper<TbShopTable>()
// .eq(TbShopTable::getQrcode, orderInfo.getTableId())
// .set(TbShopTable::getStatus, TableStateEnum.IDLE.getState()));
// rabbitMsgUtils.printTicket(scanPayDTO.getOrderId().toString());
// }
//// orderInfo.setStatus("fail");
//// orderInfo.setPayOrderNo(payment.getTradeNumber());
//// tbOrderInfoMapper.updateByPrimaryKeySelective(orderInfo);
//
// return Result.fail(object.getString("msg"));
// }
// }
// } else {
@@ -246,46 +271,56 @@ public class TbPayServiceImpl implements TbPayService {
// reqbody = body.toString();
// }
//
// PublicResp<MainScanResp> publicResp = thirdPayService.mainScan(url, thirdApply.getAppId(), reqbody, reqbody, payment.getAmount().setScale(2, RoundingMode.DOWN).multiply(new BigDecimal(100)).longValue(), payType.equals("wechatPay") ? thirdApply.getSmallAppid() : null, authCode, DateUtils.getSsdfTimes(), thirdApply.getStoreId(), callBack, thirdApply.getAppToken());
// PublicResp<MainScanResp> publicResp = thirdPayService.mainScan(url, thirdApply.getAppId(),
// reqbody, reqbody,
// BigDecimal.valueOf(payment.getAmount()).setScale(2, RoundingMode.DOWN).multiply(new BigDecimal(100)).longValue(),
// payType.equals("wechatPay") ? thirdApply.getSmallAppid() : null,
// scanPayDTO.getAuthCode(), DateUtils.getSsdfTimes(), thirdApply.getStoreId(), callBack, thirdApply.getAppToken());
// if (ObjectUtil.isNotNull(publicResp) && ObjectUtil.isNotEmpty(publicResp)) {
// if ("000000".equals(publicResp.getCode())) {
// MainScanResp mainScanResp = publicResp.getObjData();
// if ("TRADE_SUCCESS".equals(mainScanResp.getState())) {
// payment.setTradeNumber(mainScanResp.getPayOrderId());
// payment.setUpdatedAt(System.currentTimeMillis());
// tbOrderPaymentMapper.updateByPrimaryKeySelective(payment);
// orderPaymentService.updateById(payment);
//
// //处理支付成功的订单
// orderInfo.setStatus("closed");
// orderInfo.setPayOrderNo(mainScanResp.getPayOrderId());
// tbOrderInfoMapper.updateByPrimaryKeySelective(orderInfo);
// orderInfoMapper.updateById(orderInfo);
//
// //更新购物车状态
// int cartCount = tbCashierCartMapper.updateByOrderId(orderId, "final");
// int cartCount = cashierCartMapper.update(null, new LambdaUpdateWrapper<TbCashierCart>()
// .eq(TbCashierCart::getOrderId, orderInfo.getId())
// .set(TbCashierCart::getStatus, "final"));
// log.info("更新购物车:{}", cartCount);
//
// //更新子单状态
// tbOrderDetailMapper.updateStatusByOrderIdAndStatus(Integer.valueOf(orderId), "closed");
// orderDetailMapper.update(null, new LambdaUpdateWrapper<TbOrderDetail>()
// .eq(TbOrderDetail::getOrderId, orderInfo.getId())
// .set(TbOrderDetail::getStatus, "closed"));
//
// JSONObject jsonObject = new JSONObject();
// jsonObject.put("token", token);
// jsonObject.put("token", null);
// jsonObject.put("type", "create");
// jsonObject.put("orderId", orderId);
// jsonObject.put("orderId", scanPayDTO.getOrderId());
//
// producer.putOrderCollect(jsonObject.toJSONString());
//
// producer.printMechine(orderId);
//
// return Result.success(CodeEnum.SUCCESS, mainScanResp);
// // 修改台桌状态
// mpShopTableMapper.update(null, new LambdaUpdateWrapper<TbShopTable>()
// .eq(TbShopTable::getQrcode, orderInfo.getTableId())
// .set(TbShopTable::getStatus, TableStateEnum.IDLE.getState()));
// } else if ("TRADE_AWAIT".equals(mainScanResp.getState())) {
// orderInfo.setStatus("paying");
// orderInfo.setPayOrderNo(payment.getTradeNumber());
// tbOrderInfoMapper.updateByPrimaryKeySelective(orderInfo);
// orderInfoMapper.updateById(orderInfo);
//
// payment.setTradeNumber(mainScanResp.getPayOrderId());
// payment.setUpdatedAt(System.currentTimeMillis());
// tbOrderPaymentMapper.updateByPrimaryKeySelective(payment);
// return Result.success(CodeEnum.PAYING);
// orderPaymentService.updateById(payment);
//
// rabbitMsgUtils.printTicket(scanPayDTO.getOrderId().toString());
//
// }
// }
// }
@@ -294,6 +329,8 @@ public class TbPayServiceImpl implements TbPayService {
}
private final TbMShopUserMapper shopUserMapper;
private final TbShopUserFlowMapper shopUserFlowMapper;

View File

@@ -18,6 +18,7 @@ import cn.ysk.cashier.mybatis.service.TbActivateInRecordService;
import cn.ysk.cashier.mybatis.service.TbActivateOutRecordService;
import cn.ysk.cashier.mybatis.service.TbOrderPaymentService;
import cn.ysk.cashier.pojo.TbShopPayType;
import cn.ysk.cashier.pojo.order.TbFullOrderDetail;
import cn.ysk.cashier.pojo.order.TbOrderDetail;
import cn.ysk.cashier.pojo.order.TbOrderInfo;
import cn.ysk.cashier.pojo.product.TbProduct;

View File

@@ -114,6 +114,7 @@ public class TbShopTableServiceImpl implements TbShopTableService {
private final TbPayServiceImpl tbPayServiceImpl;
private final TbCashierCartMapper tbCashierCartMapper;
private final TbOrderDetailMapper tbOrderDetailMapper;
private final StringRedisTemplate stringRedisTemplate;
@Override
public Map<String, Object> queryAll(TbShopTableQueryCriteria criteria, Pageable pageable) {
@@ -143,13 +144,13 @@ public class TbShopTableServiceImpl implements TbShopTableService {
String orderId = redisTemplate.opsForValue().get(RedisConstant.CURRENT_TABLE_ORDER + date.getShopId() + ":" + date.getQrcode());
if (StrUtil.isBlank(date.getQrcode())) {
date.setStatus("closed");
}else if (tbCashierCartMapper.selectCount(new LambdaQueryWrapper<TbCashierCart>()
} else if (tbCashierCartMapper.selectCount(new LambdaQueryWrapper<TbCashierCart>()
.eq(TbCashierCart::getShopId, date.getShopId())
.eq(TbCashierCart::getTableId, date.getQrcode())
.eq(TbCashierCart::getStatus, "create")) < 1 || (orderId != null &&
tbOrderDetailMapper.selectCount(new LambdaQueryWrapper<TbOrderDetail>()
.eq(TbOrderDetail::getShopId, date.getShopId())
.eq(TbOrderDetail::getStatus, "unpaid")
.eq(TbOrderDetail::getStatus, "unpaid")
.eq(TbOrderDetail::getOrderId, orderId)) < 1)
) {
date.setStatus("idle");
@@ -477,9 +478,9 @@ public class TbShopTableServiceImpl implements TbShopTableService {
if (cashierCart.getOrderId() != null) {
orderDetailMapper.delete(new LambdaQueryWrapper<TbOrderDetail>()
.eq(TbOrderDetail::getShopId, cashierCart.getShopId())
.eq(TbOrderDetail::getProductId, cashierCart.getProductId())
.eq(TbOrderDetail::getProductSkuId, cashierCart.getSkuId())
.eq(TbOrderDetail::getShopId, cashierCart.getShopId())
.eq(TbOrderDetail::getProductId, cashierCart.getProductId())
.eq(TbOrderDetail::getProductSkuId, cashierCart.getSkuId())
.eq(TbOrderDetail::getOrderId, cashierCart.getOrderId()));
}
cashierCartMapper.delete(new LambdaQueryWrapper<TbCashierCart>().eq(TbCashierCart::getShopId, removeCartDTO.getShopId())
@@ -488,7 +489,9 @@ public class TbShopTableServiceImpl implements TbShopTableService {
// 清空购物车 出票
long carCount = countCar(cashierCart.getTableId(), cashierCart.getShopId(), cashierCart.getMasterId());
if (cashierCart.getOrderId() != null && carCount < 1) {
log.info("购物车数量: {}", carCount);
if (cashierCart.getOrderId() != null && carCount < 1) {
rabbitMsgUtils.printTicket(String.valueOf(cashierCart.getOrderId()));
}
@@ -498,17 +501,32 @@ public class TbShopTableServiceImpl implements TbShopTableService {
@Override
public void clearCart(ClearCartDTO clearCartDTO) {
if (clearCartDTO.getVipUserId() != null) {
cashierCartMapper.delete(new LambdaQueryWrapper<TbCashierCart>().eq(TbCashierCart::getShopId, clearCartDTO.getShopId())
.eq(TbCashierCart::getTableId, clearCartDTO.getTableId())
.eq(TbCashierCart::getUserId, clearCartDTO.getVipUserId()));
} else {
cashierCartMapper.delete(new LambdaQueryWrapper<TbCashierCart>().eq(TbCashierCart::getShopId, clearCartDTO.getShopId())
.eq(TbCashierCart::getTableId, clearCartDTO.getTableId())
.eq(TbCashierCart::getMasterId, clearCartDTO.getMasterId())
.isNull(TbCashierCart::getUserId));
String orderId = redisTemplate.opsForValue().get(RedisConstant.getCurrentOrderKey(clearCartDTO.getTableId().toString(), clearCartDTO.getShopId()));
cashierCartMapper.delete(new LambdaQueryWrapper<TbCashierCart>()
.eq(TbCashierCart::getShopId, clearCartDTO.getShopId())
.eq(TbCashierCart::getTableId, clearCartDTO.getTableId())
.and(q -> {
q.eq(TbCashierCart::getMasterId, clearCartDTO.getMasterId())
.or()
.isNull(TbCashierCart::getMasterId)
.or()
.eq(TbCashierCart::getMasterId, "");
})
.and(q -> {
q.eq(TbCashierCart::getOrderId, orderId)
.or()
.isNull(TbCashierCart::getOrderId);
})
);
// tbShopTableRepository.deleteByTableIdAndShopId(clearCartDTO.getTableId(), clearCartDTO.getShopId());
if (StrUtil.isNotBlank(orderId)) {
orderDetailMapper.delete(new LambdaQueryWrapper<TbOrderDetail>().eq(TbOrderDetail::getShopId, clearCartDTO.getShopId())
.eq(TbOrderDetail::getOrderId, orderId));
rabbitMsgUtils.printTicket(orderId);
}
tbShopTableRepository.deleteByTableIdAndShopId(clearCartDTO.getTableId(), clearCartDTO.getShopId());
}
@@ -516,7 +534,7 @@ public class TbShopTableServiceImpl implements TbShopTableService {
String orderId = redisTemplate.opsForValue().get(RedisConstant.getCurrentOrderKey(tableId.toString(), shopId));
return tbOrderDetailMapper.selectCount(new LambdaQueryWrapper<TbOrderDetail>()
.eq(TbOrderDetail::getShopId, shopId)
.eq(TbOrderDetail::getStatus, "unpaid")
.eq(TbOrderDetail::getStatus, "unpaid")
.eq(TbOrderDetail::getOrderId, orderId));
}
@@ -534,7 +552,7 @@ public class TbShopTableServiceImpl implements TbShopTableService {
})
.or((query4 -> {
query4.isNull(TbCashierCart::getTradeDay)
.eq(TbCashierCart::getMasterId, "");
.isNull(TbCashierCart::getMasterId);
}));
});
@@ -858,201 +876,212 @@ public class TbShopTableServiceImpl implements TbShopTableService {
@Override
public TbOrderInfo createOrder(CreateOrderDTO createOrderDTO, boolean addMaterId, boolean isPrint) {
String currentOrderKey = RedisConstant.getCurrentOrderKey(createOrderDTO.getTableId(), createOrderDTO.getShopId().toString());
String orderIdValue = redisTemplate.opsForValue().get(currentOrderKey);
Integer orderId = orderIdValue == null ? null : Integer.parseInt(orderIdValue);
orderId = createOrderDTO.getOrderId() != null ? createOrderDTO.getOrderId() : orderId;
return Utils.runFunAndCheckKey(() -> {
String currentOrderKey = RedisConstant.getCurrentOrderKey(createOrderDTO.getTableId(),
createOrderDTO.getShopId().toString());
String orderIdValue = redisTemplate.opsForValue().get(currentOrderKey);
Integer orderId = orderIdValue == null ? null : Integer.parseInt(orderIdValue);
orderId = createOrderDTO.getOrderId() != null ? createOrderDTO.getOrderId() : orderId;
String day = DateUtils.getDay();
LambdaQueryWrapper<TbCashierCart> queryWrapper = new LambdaQueryWrapper<TbCashierCart>()
.eq(TbCashierCart::getShopId, createOrderDTO.getShopId())
.eq(TbCashierCart::getTableId, createOrderDTO.getTableId())
.in(TbCashierCart::getStatus, "create", "refund")
.and(query2 -> {
query2.or(query3 -> {
query3.eq(TbCashierCart::getTradeDay, DateUtils.getDay())
.eq(TbCashierCart::getMasterId, createOrderDTO.getMasterId());
})
.or((query4 -> {
query4.isNull(TbCashierCart::getTradeDay)
.eq(TbCashierCart::getMasterId, "");
}));
});
String day = DateUtils.getDay();
LambdaQueryWrapper<TbCashierCart> queryWrapper = new LambdaQueryWrapper<TbCashierCart>()
.eq(TbCashierCart::getShopId, createOrderDTO.getShopId())
.eq(TbCashierCart::getTableId, createOrderDTO.getTableId())
.in(TbCashierCart::getStatus, "create", "refund")
.and(query2 -> {
query2.or(query3 -> {
query3.eq(TbCashierCart::getTradeDay, DateUtils.getDay())
.eq(TbCashierCart::getMasterId, createOrderDTO.getMasterId());
})
.or((query4 -> {
query4.isNull(TbCashierCart::getTradeDay)
.eq(TbCashierCart::getMasterId, "");
}));
});
// if (createOrderDTO.getVipUserId() != null) {
// queryWrapper.eq(TbCashierCart::getUserId, createOrderDTO.getVipUserId());
// }else {
// queryWrapper.eq(TbCashierCart::getMasterId, createOrderDTO.getMasterId())
// .isNull(TbCashierCart::getUserId);
// }
List<TbCashierCart> cashierCarts = cashierCartMapper
.selectList(queryWrapper);
if (cashierCarts.isEmpty()) {
throw new BadRequestException("购物车为空,请先添加商品");
}
TbShopTable tbShopTable = mpShopTableMapper.selectOne(new LambdaQueryWrapper<TbShopTable>()
.eq(TbShopTable::getQrcode, createOrderDTO.getTableId())
.in(TbShopTable::getStatus, "idle", "using"));
if (tbShopTable == null) {
throw new BadRequestException("台桌未开台或不存在");
}
BigDecimal totalAmount = BigDecimal.ZERO;
BigDecimal packAMount = BigDecimal.ZERO;
BigDecimal feeAmount = BigDecimal.ZERO;
BigDecimal saleAmount = BigDecimal.ZERO;
List<TbOrderDetail> orderDetails = new ArrayList<>();
for (TbCashierCart cashierCart : cashierCarts) {
totalAmount = totalAmount.add(cashierCart.getTotalAmount());
packAMount = packAMount.add(cashierCart.getPackFee());
feeAmount = cashierCart.getPackFee();
TbProductSku productSku = productSkuRepository.findById(Integer.valueOf(cashierCart.getSkuId())).orElse(null);
TbOrderDetail orderDetail = new TbOrderDetail();
if (Objects.nonNull(productSku)) {
saleAmount = saleAmount.add(productSku.getSalePrice());
orderDetail.setProductSkuName(productSku.getSpecSnap());
List<TbCashierCart> cashierCarts = cashierCartMapper
.selectList(queryWrapper);
if (cashierCarts.isEmpty()) {
throw new BadRequestException("购物车为空,请先添加商品");
}
orderDetail.setCreateTime(DateUtil.date().toTimestamp());
orderDetail.setNum(cashierCart.getNumber());
orderDetail.setPrice(cashierCart.getSalePrice());
orderDetail.setPriceAmount(cashierCart.getTotalAmount());
orderDetail.setProductId(Integer.valueOf(cashierCart.getProductId()));
orderDetail.setProductSkuId(Integer.valueOf(cashierCart.getSkuId()));
orderDetail.setProductName(cashierCart.getName());
orderDetail.setShopId(Integer.valueOf(cashierCart.getShopId()));
orderDetail.setPackAmount(cashierCart.getPackFee());
orderDetail.setStatus("unpaid");
orderDetail.setProductImg(cashierCart.getCoverImg());
orderDetails.add(orderDetail);
if (cashierCart.getOrderId() != null) {
orderId = cashierCart.getOrderId();
TbShopTable tbShopTable = mpShopTableMapper.selectOne(new LambdaQueryWrapper<TbShopTable>()
.eq(TbShopTable::getQrcode, createOrderDTO.getTableId())
.in(TbShopTable::getStatus, "idle", "using"));
if (tbShopTable == null) {
throw new BadRequestException("台桌未开台或不存在");
}
orderDetail.setOrderId(orderId);
}
TbOrderInfo orderInfo = null;
if (orderId != null) {
orderInfo = orderInfoMapper.selectById(orderId);
BigDecimal totalAmount = BigDecimal.ZERO;
BigDecimal packAMount = BigDecimal.ZERO;
BigDecimal feeAmount = BigDecimal.ZERO;
BigDecimal saleAmount = BigDecimal.ZERO;
List<TbOrderDetail> orderDetails = new ArrayList<>();
if (orderInfo == null || !"unpaid".equals(orderInfo.getStatus())) {
redisTemplate.delete(currentOrderKey);
for (TbCashierCart cashierCart : cashierCarts) {
totalAmount = totalAmount.add(cashierCart.getTotalAmount());
packAMount = packAMount.add(cashierCart.getPackFee());
feeAmount = cashierCart.getPackFee();
TbProductSku productSku = productSkuRepository.findById(Integer.valueOf(cashierCart.getSkuId())).orElse(null);
TbOrderDetail orderDetail = new TbOrderDetail();
if (Objects.nonNull(productSku)) {
saleAmount = saleAmount.add(productSku.getSalePrice());
orderDetail.setProductSkuName(productSku.getSpecSnap());
}
orderDetail.setCreateTime(DateUtil.date().toTimestamp());
orderDetail.setNum(cashierCart.getNumber());
orderDetail.setPrice(cashierCart.getSalePrice());
orderDetail.setPriceAmount(cashierCart.getTotalAmount());
orderDetail.setProductId(Integer.valueOf(cashierCart.getProductId()));
orderDetail.setProductSkuId(Integer.valueOf(cashierCart.getSkuId()));
orderDetail.setProductName(cashierCart.getName());
orderDetail.setShopId(Integer.valueOf(cashierCart.getShopId()));
orderDetail.setPackAmount(cashierCart.getPackFee());
orderDetail.setStatus("unpaid");
orderDetail.setProductImg(cashierCart.getCoverImg());
orderDetails.add(orderDetail);
if (cashierCart.getOrderId() != null) {
orderId = cashierCart.getOrderId();
}
orderDetail.setOrderId(orderId);
}
}
// 修改订单信息
if (orderInfo != null) {
// 删除历史订单
// 更新取餐号
orderInfo.setOutNumber(updateOutNumber(String.valueOf(createOrderDTO.getShopId())).toString());
orderDetailMapper.delete(new LambdaQueryWrapper<TbOrderDetail>().eq(TbOrderDetail::getOrderId, orderId));
orderInfo.setUpdatedAt(System.currentTimeMillis());
orderInfo.setSettlementAmount(totalAmount);
orderInfo.setAmount(totalAmount);
orderInfo.setOriginAmount(totalAmount);
TbOrderInfo orderInfo = null;
if (orderId != null) {
orderInfo = orderInfoMapper.selectById(orderId);
if (orderInfo == null || !"unpaid".equals(orderInfo.getStatus())) {
redisTemplate.delete(currentOrderKey);
}
}
// 修改订单信息
if (orderInfo != null) {
// 删除历史订单
// 更新取餐号
orderInfo.setOutNumber(updateOutNumber(String.valueOf(createOrderDTO.getShopId())).toString());
orderDetailMapper.delete(new LambdaQueryWrapper<TbOrderDetail>().eq(TbOrderDetail::getOrderId, orderId));
orderInfo.setUpdatedAt(System.currentTimeMillis());
orderInfo.setSettlementAmount(totalAmount);
orderInfo.setAmount(totalAmount);
orderInfo.setOriginAmount(totalAmount);
// orderInfo.setStatus("unpaid");
orderInfo.setOrderAmount(totalAmount);
orderInfo.setRemark(createOrderDTO.getNote());
orderInfo.setFreightAmount(feeAmount);
orderInfo.setProductAmount(saleAmount);
orderInfo.setTradeDay(DateUtils.getDay());
orderInfo.setUseType(createOrderDTO.isPostPay() ? "postPay" : "afterPay");
orderInfo.setUserId(createOrderDTO.getVipUserId() == null ? null : String.valueOf(createOrderDTO.getVipUserId()));
orderInfoMapper.updateById(orderInfo);
} else {
String orderNo = generateOrderNumber();
orderInfo = new TbOrderInfo();
orderInfo.setOrderNo(orderNo);
orderInfo.setUseType(createOrderDTO.isPostPay() ? "postPay" : "afterPay");
orderInfo.setAmount(totalAmount);
orderInfo.setPayAmount(BigDecimal.ZERO);
orderInfo.setPackFee(packAMount);
orderInfo.setSettlementAmount(totalAmount);
orderInfo.setOriginAmount(totalAmount);
orderInfo.setProductAmount(saleAmount);
orderInfo.setOrderAmount(totalAmount);
orderInfo.setFreightAmount(feeAmount);
orderInfo.setTableId(String.valueOf(createOrderDTO.getTableId()));
orderInfo.setSendType("table");
orderInfo.setOrderType("cash");
orderInfo.setShopId(createOrderDTO.getShopId().toString());
orderInfo.setRefundAble(1);
orderInfo.setTradeDay(day);
orderInfo.setMasterId(createOrderDTO.getMasterId());
orderInfo.setOutNumber(createOrderDTO.getMasterId());
orderInfo.setRemark(createOrderDTO.getNote());
orderInfo.setUserId(createOrderDTO.getVipUserId() == null ? null : String.valueOf(createOrderDTO.getVipUserId()));
orderInfo.setCreatedAt(DateUtil.current());
orderInfo.setTableName(tbShopTable.getName());
TbMerchantAccount merchantAccount = merchantAccountMapper.selectOne(new LambdaQueryWrapper<TbMerchantAccount>()
.eq(TbMerchantAccount::getShopId, createOrderDTO.getShopId())
.eq(TbMerchantAccount::getStatus, 1));
if (merchantAccount == null) {
throw new BadRequestException("商户信息不存在");
orderInfo.setOrderAmount(totalAmount);
orderInfo.setRemark(createOrderDTO.getNote());
orderInfo.setFreightAmount(feeAmount);
orderInfo.setProductAmount(saleAmount);
orderInfo.setTradeDay(DateUtils.getDay());
orderInfo.setUseType(createOrderDTO.isPostPay() ? "postPay" : "afterPay");
orderInfo.setUserId(createOrderDTO.getVipUserId() == null ? null : String.valueOf(createOrderDTO.getVipUserId()));
orderInfo.setCreatedAt(DateUtil.current());
orderInfoMapper.updateById(orderInfo);
} else {
String orderNo = generateOrderNumber();
orderInfo = new TbOrderInfo();
orderInfo.setOrderNo(orderNo);
orderInfo.setUseType(createOrderDTO.isPostPay() ? "postPay" : "afterPay");
orderInfo.setAmount(totalAmount);
orderInfo.setPayAmount(BigDecimal.ZERO);
orderInfo.setPackFee(packAMount);
orderInfo.setSettlementAmount(totalAmount);
orderInfo.setOriginAmount(totalAmount);
orderInfo.setProductAmount(saleAmount);
orderInfo.setOrderAmount(totalAmount);
orderInfo.setFreightAmount(feeAmount);
orderInfo.setTableId(String.valueOf(createOrderDTO.getTableId()));
orderInfo.setSendType("table");
orderInfo.setOrderType("cash");
orderInfo.setShopId(createOrderDTO.getShopId().toString());
orderInfo.setRefundAble(1);
orderInfo.setTradeDay(day);
orderInfo.setMasterId(createOrderDTO.getMasterId());
orderInfo.setOutNumber(createOrderDTO.getMasterId());
orderInfo.setRemark(createOrderDTO.getNote());
orderInfo.setUserId(createOrderDTO.getVipUserId() == null ? null : String.valueOf(createOrderDTO.getVipUserId()));
orderInfo.setCreatedAt(DateUtil.current());
orderInfo.setTableName(tbShopTable.getName());
TbMerchantAccount merchantAccount = merchantAccountMapper.selectOne(new LambdaQueryWrapper<TbMerchantAccount>()
.eq(TbMerchantAccount::getShopId, createOrderDTO.getShopId())
.eq(TbMerchantAccount::getStatus, 1));
if (merchantAccount == null) {
throw new BadRequestException("商户信息不存在");
}
orderInfo.setMerchantId(merchantAccount.getId().toString());
orderInfoMapper.insert(orderInfo);
redisTemplate.opsForValue().set(currentOrderKey, orderInfo.getId().toString());
}
orderInfo.setMerchantId(merchantAccount.getId().toString());
orderInfoMapper.insert(orderInfo);
redisTemplate.opsForValue().set(currentOrderKey, orderInfo.getId().toString());
}
// 添加订单详细数据
orderId = orderInfo.getId();
for (TbOrderDetail orderDetail : orderDetails) {
orderDetail.setOrderId(orderId);
orderDetailMapper.insert(orderDetail);
}
// 添加订单详细数据
orderId = orderInfo.getId();
for (TbOrderDetail orderDetail : orderDetails) {
orderDetail.setOrderId(orderId);
orderDetailMapper.insert(orderDetail);
}
// 更新购物车记录的orderId
// 是否是第一次添加的商品
boolean isFirst = true;
for (TbCashierCart cashierCart : cashierCarts) {
TbProduct product = productMapper.selectById(cashierCart.getProductId());
TbProductSku productSku = productSkuRepository.findById(Integer.valueOf(cashierCart.getSkuId())).orElse(null);
// 更新购物车记录的orderId
// 是否是第一次添加的商品
boolean isFirst = true;
for (TbCashierCart cashierCart : cashierCarts) {
TbProduct product = productMapper.selectById(cashierCart.getProductId());
TbProductSku productSku = productSkuRepository.findById(Integer.valueOf(cashierCart.getSkuId())).orElse(null);
log.info("下单,开始校验库存预警,购物车id:{}", cashierCart.getId());
CompletableFuture.runAsync(() -> checkWarnLineAndSendMsg(productSku, product, Integer.valueOf(cashierCart.getShopId()), cashierCart.getNumber()));
log.info("下单,开始校验库存预警,购物车id:{}", cashierCart.getId());
CompletableFuture.runAsync(() -> checkWarnLineAndSendMsg(productSku, product, Integer.valueOf(cashierCart.getShopId()), cashierCart.getNumber()));
// 已经添加的商品,修改数量
isFirst = updateStock(cashierCart);
cashierCart.setOrderId(orderId);
cashierCart.setUpdatedAt(System.currentTimeMillis());
cashierCart.setStatus("pending".equals(orderInfo.getStatus()) ? "refund" : cashierCart.getStatus());
cashierCartMapper.updateById(cashierCart);
}
if (isFirst) {
// 后付费,不增加当前台桌取餐号
if (createOrderDTO.isPostPay()) {
addGlobalCode(day, "pc", String.valueOf(createOrderDTO.getShopId()));
// 已经添加的商品,修改数量
isFirst = updateStock(cashierCart);
cashierCart.setOrderId(orderId);
cashierCart.setUpdatedAt(System.currentTimeMillis());
cashierCart.setStatus("pending".equals(orderInfo.getStatus()) ? "refund" : cashierCart.getStatus());
cashierCartMapper.updateById(cashierCart);
}
if (isFirst) {
// 后付费,不增加当前台桌取餐号
if (createOrderDTO.isPostPay()) {
addGlobalCode(day, "pc", String.valueOf(createOrderDTO.getShopId()));
// String key = "SHOP:CODE:USER:pc" + ":" + createOrderDTO.getShopId() + ":" + day + ":" + orderInfo.getTableId();
// redisTemplate.delete(key);
}
if (!createOrderDTO.isPostPay() || (addMaterId && "pending".equals(orderInfo.getStatus()))) {
String key = "SHOP:CODE:USER:pc" + ":" + createOrderDTO.getShopId() + ":" + day + ":" + orderInfo.getTableId();
redisTemplate.delete(key);
}
}
if (!createOrderDTO.isPostPay() || addMaterId){
String key = "SHOP:CODE:USER:pc" + ":" + createOrderDTO.getShopId() + ":" + day + ":" + orderInfo.getTableId();
redisTemplate.delete(key);
// 推送耗材信息
pushConsMsg(orderInfo, cashierCarts);
mpShopTableMapper.update(null, new LambdaUpdateWrapper<TbShopTable>()
.eq(TbShopTable::getShopId, createOrderDTO.getShopId())
.eq(TbShopTable::getQrcode, createOrderDTO.getTableId())
.set(TbShopTable::getStatus, TableStateEnum.USING.getState()));
if (createOrderDTO.isPostPay() && isPrint) {
Long count = orderInfoMapper.selectCount(new LambdaQueryWrapper<TbOrderInfo>()
.eq(TbOrderInfo::getStatus, "unpaid")
.eq(TbOrderInfo::getId, orderId));
if (count != 0) {
rabbitMsgUtils.printTicket(String.valueOf(orderId));
}
}
}
// 推送耗材信息
pushConsMsg(orderInfo, cashierCarts);
return orderInfo;
}, stringRedisTemplate, RedisConstant.getLockKey(RedisConstant.CREATE_ORDER,createOrderDTO.getShopId(),
createOrderDTO.getTableId(), createOrderDTO.getMasterId(), createOrderDTO.isPostPay()));
mpShopTableMapper.update(null, new LambdaUpdateWrapper<TbShopTable>()
.eq(TbShopTable::getShopId, createOrderDTO.getShopId())
.eq(TbShopTable::getQrcode, createOrderDTO.getTableId())
.set(TbShopTable::getStatus, TableStateEnum.USING.getState()));
if (createOrderDTO.isPostPay() && isPrint) {
rabbitMsgUtils.printTicket(String.valueOf(orderId));
}
return orderInfo;
}
@@ -1205,56 +1234,59 @@ public class TbShopTableServiceImpl implements TbShopTableService {
@Override
public Object pay(PayDTO payDTO) {
return Utils.runFunAndCheckKey(() -> {
TbOrderInfo orderInfo = null;
switch (payDTO.getPayType()) {
case "vipPay":
orderInfo = tbPayServiceImpl.vipPay(payDTO.getShopId(), payDTO.getOrderId(), payDTO.getDiscount(), payDTO.getVipUserId());
break;
case "cash":
orderInfo = tbPayServiceImpl.cashPay(payDTO);
break;
default:
throw new BadRequestException("未知支付方式");
}
TbOrderInfo orderInfo = null;
switch (payDTO.getPayType()) {
case "vipPay":
orderInfo = tbPayServiceImpl.vipPay(payDTO.getShopId(), payDTO.getOrderId(), payDTO.getDiscount(), payDTO.getVipUserId());
break;
case "cash":
orderInfo = tbPayServiceImpl.cashPay(payDTO);
break;
default:
throw new BadRequestException("未知支付方式");
}
log.info("更新购物车");
log.info("更新购物车");
JSONObject jsonObject = new JSONObject();
jsonObject.put("token", null);
jsonObject.put("type", "create");
jsonObject.put("orderId", orderInfo.getId());
JSONObject jsonObject = new JSONObject();
jsonObject.put("token", null);
jsonObject.put("type", "create");
jsonObject.put("orderId", orderInfo.getId());
// 打印消息
rabbitMsgUtils.sendOrderCollectMsg(jsonObject);
rabbitMsgUtils.printTicket(String.valueOf(orderInfo.getId()));
// 打印消息
rabbitMsgUtils.sendOrderCollectMsg(jsonObject);
rabbitMsgUtils.printTicket(String.valueOf(orderInfo.getId()));
// 发送库存记录mq消息
JSONObject mqData = new JSONObject();
mqData.put("orderId", payDTO.getOrderId());
mqData.put("type", "pc");
rabbitTemplate.convertAndSend(RabbitConstants.EXCHANGE_STOCK_RECORD, RabbitConstants.ROUTING_STOCK_RECORD_SALE, mqData.toJSONString(), new CorrelationData(UUID.randomUUID().toString()));
// 发送库存记录mq消息
JSONObject mqData = new JSONObject();
mqData.put("orderId", payDTO.getOrderId());
mqData.put("type", "pc");
rabbitTemplate.convertAndSend(RabbitConstants.EXCHANGE_STOCK_RECORD, RabbitConstants.ROUTING_STOCK_RECORD_SALE, mqData.toJSONString(), new CorrelationData(UUID.randomUUID().toString()));
// 修改台桌状态
mpShopTableMapper.update(null, new LambdaUpdateWrapper<TbShopTable>()
.eq(TbShopTable::getQrcode, orderInfo.getTableId())
.set(TbShopTable::getStatus, TableStateEnum.IDLE.getState()));
// 修改台桌状态
mpShopTableMapper.update(null, new LambdaUpdateWrapper<TbShopTable>()
.eq(TbShopTable::getQrcode, orderInfo.getTableId())
.set(TbShopTable::getStatus, TableStateEnum.IDLE.getState()));
if ("postPay".equals(orderInfo.getUseType())) {
String day = DateUtils.getDay();
String key = "SHOP:CODE:USER:pc" + ":" + payDTO.getShopId() + ":" + day + ":" + orderInfo.getTableId();
redisTemplate.delete(key);
}
if ("postPay".equals(orderInfo.getUseType())) {
String day = DateUtils.getDay();
String key = "SHOP:CODE:USER:pc" + ":" + payDTO.getShopId() + ":" + day + ":" + orderInfo.getTableId();
redisTemplate.delete(key);
}
String currentOrderKey = RedisConstant.CURRENT_TABLE_ORDER + payDTO.getShopId() + ":" + orderInfo.getTableId();
redisTemplate.delete(currentOrderKey);
String currentOrderKey = RedisConstant.CURRENT_TABLE_ORDER + payDTO.getShopId() + ":" + orderInfo.getTableId();
redisTemplate.delete(currentOrderKey);
// 小程序购物车缓存
String tableCartKey = RedisConstant.getTableCartKey(orderInfo.getTableId(), orderInfo.getShopId());
redisTemplate.delete(tableCartKey);
return null;
}, stringRedisTemplate, RedisConstant.getLockKey("", payDTO.getShopId(), payDTO.getOrderId()));
// 小程序购物车缓存
String tableCartKey = RedisConstant.getTableCartKey(orderInfo.getTableId(), orderInfo.getShopId());
redisTemplate.delete(tableCartKey);
return null;
}
@Override

View File

@@ -2,6 +2,8 @@ package cn.ysk.cashier.thirdpay.service;
import cn.hutool.http.HttpRequest;
import cn.ysk.cashier.mybatis.vo.pay.MainScanReq;
import cn.ysk.cashier.mybatis.vo.pay.MainScanResp;
import cn.ysk.cashier.thirdpay.constants.SignTypeEnum;
import cn.ysk.cashier.thirdpay.req.OrderRefundReq;
import cn.ysk.cashier.thirdpay.req.OrderReturnQueryReq;
@@ -11,6 +13,7 @@ import cn.ysk.cashier.thirdpay.resp.OrderReturnResp;
import cn.ysk.cashier.thirdpay.resp.OrderStatusQueryResp;
import cn.ysk.cashier.thirdpay.resp.PublicResp;
import cn.ysk.cashier.utils.JSONUtil;
import cn.ysk.cashier.utils.MD5Util;
import cn.ysk.cashier.utils.MD5Utils;
import com.dianguang.cloud.ossservice.model.DateUtils;
import lombok.extern.slf4j.Slf4j;
@@ -25,6 +28,13 @@ import java.util.LinkedHashMap;
@Slf4j
public class ThirdPayService {
private static String micropay="/api/open/payment/micropay";
private static String ltpay="/api/open/payment/ltpay";
private static String refund="/api/open/order/refund";
private static String trade="/api/open/query/trade";
@@ -197,6 +207,45 @@ public class ThirdPayService {
return map;
}
public PublicResp<MainScanResp> mainScan(String url, String appId, String subject, String body, Long amount, String subAppId, String authCode, String orderNo, String storeId, String notifyUrl,
String key
) {
MainScanReq mainScanReq=null;
if("66bab943ae82f63b50ae3cff".equals(appId)){
mainScanReq = new MainScanReq(subject, body, amount, subAppId, "cny", authCode, orderNo, storeId, notifyUrl,1,"TA1824003985261588482",null);
url="https://paymentweb.sxczgkj.cn";
}else {
mainScanReq = new MainScanReq(subject, body, amount, subAppId, "cny", authCode, orderNo, storeId, notifyUrl,0,null,null);
}
PublicParam param = new PublicParam(appId, "", SignTypeEnum.MD5.getValue(), null, cn.ysk.cashier.utils.DateUtils.getSdfTimes(), "1.0", String.valueOf(System.currentTimeMillis()));
try {
String str = JSONUtil.toJSONString(sortFields(mainScanReq));
param.setBizData(str);
String tt = sortFieldsAndPrint(param);
String MD5 = tt.concat("appSecret=" + key);
log.info("加签原传:{}", MD5);
String sign = MD5Util.encrypt(MD5);
param.setSign(sign);
String reqbody = JSONUtil.toJSONString(param);
log.info("请求参数:{}", reqbody);
String response = HttpRequest.post(url.concat(micropay)).body(reqbody).execute().body();
log.info("返回结果:{}", response);
PublicResp<MainScanResp> resp =JSONUtil.parseJSONStr2T(response,PublicResp.class);
resp.setObjData(JSONUtil.parseJSONStr2T(resp.getBizData(),MainScanResp.class));
return resp;
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}

View File

@@ -0,0 +1,360 @@
package cn.ysk.cashier.utils;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* Created by SEELE on 2018/4/19.
*/
public class DateUtils {
private final static SimpleDateFormat sdfYear = new SimpleDateFormat("yyyy");
private final static SimpleDateFormat sdfDay = new SimpleDateFormat("yyyy-MM-dd");
private final static SimpleDateFormat sdfDays = new SimpleDateFormat("yyyyMMdd");
private final static SimpleDateFormat sdfTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private final static SimpleDateFormat sdfTimeSS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
private final static SimpleDateFormat sdfTimes = new SimpleDateFormat("yyyyMMddHHmmss");
private final static SimpleDateFormat sdfTimesSs = new SimpleDateFormat("yyyyMMddHHmmssSSS");
private final static SimpleDateFormat sdfday = new SimpleDateFormat("MM-dd HH:mm");
public static Date getNewDate(Date date, Integer type, Integer interval) throws ParseException {
Calendar c = Calendar.getInstance();
c.setTime(date);
switch (type) {
case 1:
c.set(Calendar.YEAR, (c.get(Calendar.YEAR) + interval));
break;
case 2:
c.set(Calendar.MONTH, (c.get(Calendar.MONTH) + interval));
break;
case 3:
c.set(Calendar.DATE, (c.get(Calendar.DATE) + interval));
break;
case 4:
c.set(Calendar.HOUR, (c.get(Calendar.HOUR) + interval));
break;
case 5:
c.set(Calendar.MINUTE, (c.get(Calendar.MINUTE) + interval));
break;
default:
c.set(Calendar.SECOND, (c.get(Calendar.SECOND) + interval));
break;
}
Date newDate = c.getTime();
return sdfTime.parse(sdfTime.format(newDate));
}
/**
* 获取YYYY格式
* @return
*/
public static String getSdfTimes() {
return sdfTimes.format(new Date());
}
public static String getSsdfTimes() {
return sdfTimesSs.format(new Date());
}
public static String getNextSdfTimes(Date date){
return sdfTimes.format(date);
}
public static String getTimes(Date date){
return sdfday.format(date);
}
/**
* 获取YYYY格式
* @return
*/
public static String getYear() {
return sdfYear.format(new Date());
}
/**
* 获取YYYY-MM-DD格式
* @return
*/
public static String getDay() {
return sdfDay.format(new Date());
}
/**
* 获取YYYYMMDD格式
* @return
*/
public static String getDays(){
return sdfDays.format(new Date());
}
/**
* 获取YYYY-MM-DD HH:mm:ss格式
* @return
*/
public static String getTime(Date date) {
return sdfTime.format(date);
}
/**
* @Title: compareDate
* @Description: TODO(日期比较如果s>=e 返回true 否则返回false)
* @param s
* @param e
* @return boolean
* @throws
* @author fh
*/
public static boolean compareDate(String s, String e) {
if(fomatDate(s)==null||fomatDate(e)==null){
return false;
}
return fomatDate(s).getTime() >=fomatDate(e).getTime();
}
/**
* 格式化日期
* @return
*/
public static Date fomatDate(String date) {
DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
try {
return fmt.parse(date);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
/**
* 校验日期是否合法
* @return
*/
public static boolean isValidDate(String s) {
DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
try {
fmt.parse(s);
return true;
} catch (Exception e) {
// 如果throw java.text.ParseException或者NullPointerException就说明格式不对
return false;
}
}
/**
* @param startTime
* @param endTime
* @return
*/
public static int getDiffYear(String startTime,String endTime) {
DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
try {
//long aa=0;
int years=(int) (((fmt.parse(endTime).getTime()-fmt.parse(startTime).getTime())/ (1000 * 60 * 60 * 24))/365);
return years;
} catch (Exception e) {
// 如果throw java.text.ParseException或者NullPointerException就说明格式不对
return 0;
}
}
/**
* <li>功能描述:时间相减得到天数
* @param beginDateStr
* @param endDateStr
* @return
* long
* @author Administrator
*/
public static long getDaySub(String beginDateStr,String endDateStr){
long day=0;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date beginDate = null;
Date endDate = null;
try {
beginDate = format.parse(beginDateStr);
endDate= format.parse(endDateStr);
} catch (ParseException e) {
e.printStackTrace();
}
day=(endDate.getTime()-beginDate.getTime())/(24*60*60*1000);
//System.out.println("相隔的天数="+day);
return day;
}
/**
* 得到n天之后的日期
* @param days
* @return
*/
public static String getAfterDayDate(String days) {
int daysInt = Integer.parseInt(days);
Calendar canlendar = Calendar.getInstance(); // java.util包
canlendar.add(Calendar.DATE, daysInt); // 日期减 如果不够减会将月变动
Date date = canlendar.getTime();
SimpleDateFormat sdfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr = sdfd.format(date);
return dateStr;
}
/**
* 得到n天之后的日期
* @param days
* @return
*/
public static String getAfterDate(Date openDate,String days) {
int daysInt = Integer.parseInt(days);
Calendar canlendar = Calendar.getInstance(); // java.util包
canlendar.setTime(openDate);
canlendar.add(Calendar.DATE, daysInt); // 日期减 如果不够减会将月变动
Date date = canlendar.getTime();
SimpleDateFormat sdfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr = sdfd.format(date);
return dateStr;
}
public static String getAfterDate1(Date openDate,String year) {
int daysInt = Integer.parseInt(year);
Calendar canlendar = Calendar.getInstance(); // java.util包
canlendar.setTime(openDate);
canlendar.add(Calendar.YEAR, daysInt); // 日期减 如果不够减会将月变动
Date date = canlendar.getTime();
SimpleDateFormat sdfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr = sdfd.format(date);
return dateStr;
}
public static Date getAfterDateStr(Date openDate,String days) {
int daysInt = Integer.parseInt(days);
Calendar canlendar = Calendar.getInstance(); // java.util包
canlendar.setTime(openDate);
canlendar.add(Calendar.DATE, daysInt); // 日期减 如果不够减会将月变动
Date date = canlendar.getTime();
return date;
}
/**
* 得到n天之后是周几
* @param days
* @return
*/
public static String getAfterDayWeek(String days) {
int daysInt = Integer.parseInt(days);
Calendar canlendar = Calendar.getInstance(); // java.util包
canlendar.add(Calendar.DATE, daysInt); // 日期减 如果不够减会将月变动
Date date = canlendar.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("E");
String dateStr = sdf.format(date);
return dateStr;
}
public static void main(String[] args) {
System.out.println(getTimes(new Date()));
}
/**
* 格式化日期为时分秒
* @param date
* @return
*/
public static Date fomatDateTime(String date) {
DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
return fmt.parse(date);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
public static Date fomatDateTime1(String date) {
DateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmss");
try {
return fmt.parse(date);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
public static Date parse(String dateString, String dateFormat) {
if ("".equals(dateString.trim()) || dateString == null) {
return null;
}
DateFormat sdf = new SimpleDateFormat(dateFormat);
Date date = null;
try {
date = sdf.parse(dateString);
} catch (Exception e) {
e.printStackTrace();
}
return date;
}
private final static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
public static Date convertDate(String date) {
try {
return sdf.parse(date);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
private final static SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static Date convertDateByString(String str){
StringBuilder sb=new StringBuilder();
sb.append(str.substring(0,4));
sb.append("-");
sb.append(str.substring(4,6));
sb.append("-");
sb.append(str.substring(6,8));
sb.append(" ");
sb.append(str.substring(8,10));
sb.append(":");
sb.append(str.substring(10,12));
sb.append(":");
sb.append(str.substring(12,14));
return convertDate1(sb.toString());
}
public static Date convertDate1(String date) {
try {
return sdf1.parse(date);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
public static String formatDateToStr(Date date) {
return sdfTime.format(date);
}
}

View File

@@ -60,6 +60,8 @@ qrcode: https://kysh.sxczgkj.cn/codeplate?code=
thirdPay:
groupCallBack: https://wxcashiertest.sxczgkj.cn/cashierService/notify/notifyCallBackGroup
payType: fushangtong
callBack: https://cashierclient.sxczgkj.cn/cashier-client/notify/notifyPay
url: https://paymentapi.sxczgkj.cn
mybatis-plus:
@@ -85,3 +87,9 @@ wx:
secrete: 8492a7e8d55bbb1b57f5c8276ea1add0
operationMsgTmpId: wFdoUG-dUT7bDRHq8bMJD9CF5TjyH9x_uJQgQByZqHg
warnMsgTmpId: C08OUr80x6wGmUN1zpFhSQ3Sv7VF5vksdZigiEx2pD0
gateway:
url: https://gateway.api.sxczgkj.cn/gate-service/
client:
backUrl: https://cashierclient.sxczgkj.cn/cashier-client/notify/notifyPay