SpecialPayServiceImpl.java 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. package com.cyksj.service.special.impl;
  2. import cn.hutool.core.date.DateUtil;
  3. import cn.hutool.core.util.StrUtil;
  4. import com.alipay.api.internal.util.AlipaySignature;
  5. import com.baomidou.mybatisplus.core.toolkit.Wrappers;
  6. import com.cyksj.common.EnvCommonService;
  7. import com.cyksj.common.exception.BusinessRuntimeException;
  8. import com.cyksj.common.snowflake.Sequence;
  9. import com.cyksj.common.util.Codec;
  10. import com.cyksj.common.util.Jsons;
  11. import com.cyksj.config.zfb.BaseZfbConfig;
  12. import com.cyksj.config.zfb.ZfbProductCode;
  13. import com.cyksj.mapper.channel.ShopConfigMapper;
  14. import com.cyksj.mapper.special.SpecialMemberEntitlementMapper;
  15. import com.cyksj.mapper.special.SpecialPayOrderMapper;
  16. import com.cyksj.mapper.special.SpecialPayProductMapper;
  17. import com.cyksj.model.dto.AliPayParams;
  18. import com.cyksj.model.entity.ShopConfig;
  19. import com.cyksj.model.entity.SpecialPayOrder;
  20. import com.cyksj.model.entity.SpecialPayProduct;
  21. import com.cyksj.model.entity.SpecialMemberEntitlement;
  22. import com.cyksj.model.request.SpecialPayCreateReq;
  23. import com.cyksj.model.request.OrderAttach;
  24. import com.cyksj.model.response.AliPayTradeStatus;
  25. import com.cyksj.model.response.SpecialPayCreateRep;
  26. import com.cyksj.service.pay.AliPayCommonService;
  27. import com.cyksj.service.special.SpecialPayService;
  28. import com.cyksj.service.sys.SysConfigService;
  29. import lombok.RequiredArgsConstructor;
  30. import lombok.extern.slf4j.Slf4j;
  31. import org.springframework.stereotype.Service;
  32. import org.springframework.transaction.annotation.Transactional;
  33. import java.math.BigDecimal;
  34. import java.math.RoundingMode;
  35. import java.util.Date;
  36. import java.util.List;
  37. import java.util.Map;
  38. import java.util.Optional;
  39. @Slf4j
  40. @Service
  41. @RequiredArgsConstructor
  42. public class SpecialPayServiceImpl implements SpecialPayService {
  43. private static final Sequence SEQUENCE = new Sequence(0);
  44. private static final int ORDER_EXPIRE_MINUTES = 5;
  45. private final SpecialPayProductMapper productMapper;
  46. private final SpecialPayOrderMapper orderMapper;
  47. private final SpecialMemberEntitlementMapper entitlementMapper;
  48. private final ShopConfigMapper shopConfigMapper;
  49. private final SysConfigService sysConfigService;
  50. private final AliPayCommonService aliPayCommonService;
  51. private final EnvCommonService envCommonService;
  52. @Override
  53. public List<SpecialPayProduct> getEnabledProducts() {
  54. return productMapper.selectList(Wrappers.lambdaQuery(SpecialPayProduct.class)
  55. .eq(SpecialPayProduct::getEnabled, true)
  56. .orderByAsc(SpecialPayProduct::getSortBy, SpecialPayProduct::getId));
  57. }
  58. @Override
  59. @Transactional(rollbackFor = Throwable.class)
  60. public SpecialPayCreateRep createAlipayOrder(Long userId, SpecialPayCreateReq request) throws Exception {
  61. SpecialPayProduct product = productMapper.selectOne(Wrappers.lambdaQuery(SpecialPayProduct.class)
  62. .eq(SpecialPayProduct::getProductCode, request.getProductCode())
  63. .eq(SpecialPayProduct::getEnabled, true)
  64. .last("limit 1"));
  65. if (product == null) {
  66. throw BusinessRuntimeException.getInstance("支付套餐不存在或已下架");
  67. }
  68. if (product.getAmount() == null || product.getAmount().compareTo(BigDecimal.ZERO) <= 0
  69. || product.getDurationDays() == null || product.getDurationDays() <= 0) {
  70. throw BusinessRuntimeException.getInstance("支付套餐配置异常");
  71. }
  72. String alipayProductCode = getAlipayProductCode(request.getPayType());
  73. Date now = new Date();
  74. SpecialPayOrder order = new SpecialPayOrder();
  75. order.setOrderNo("SP" + SEQUENCE.nextId());
  76. order.setUserId(userId);
  77. order.setProductCode(product.getProductCode());
  78. order.setSubject(product.getProductName());
  79. order.setAmount(product.getAmount());
  80. order.setDurationDays(product.getDurationDays());
  81. order.setStatus(SpecialPayOrder.Status.CREATED);
  82. order.setFulfillStatus(SpecialPayOrder.FulfillStatus.INIT);
  83. order.setShopId(sysConfigService.getDefaultShopConfigByType("zfb"));
  84. order.setExpireTime(DateUtil.offsetMinute(now, ORDER_EXPIRE_MINUTES));
  85. order.setCreatedTime(now);
  86. order.setUpdateTime(now);
  87. orderMapper.insert(order);
  88. String notifyUrl = envCommonService.getNotifyHost() + BaseZfbConfig.specialPayNotifyUrl;
  89. AliPayParams payParams = aliPayCommonService.builderPayParams(
  90. order.getId(), order.getOrderNo(), order.getShopId(), order.getAmount(),
  91. order.getCreatedTime(), order.getSubject(), alipayProductCode,
  92. request.getPayMode(), notifyUrl, request.getReturnUrl());
  93. if (payParams == null || StrUtil.isBlank(payParams.getBody())) {
  94. throw BusinessRuntimeException.getInstance("支付宝下单失败");
  95. }
  96. SpecialPayCreateRep response = new SpecialPayCreateRep();
  97. response.setOrderNo(order.getOrderNo());
  98. response.setStatus(order.getStatus());
  99. response.setExpireTime(order.getExpireTime());
  100. response.setPayBody(payParams.getBody());
  101. return response;
  102. }
  103. @Override
  104. public SpecialPayOrder getUserOrder(Long userId, String orderNo) {
  105. SpecialPayOrder order = orderMapper.selectOne(Wrappers.lambdaQuery(SpecialPayOrder.class)
  106. .eq(SpecialPayOrder::getOrderNo, orderNo)
  107. .eq(SpecialPayOrder::getUserId, userId)
  108. .last("limit 1"));
  109. if (order == null) {
  110. throw BusinessRuntimeException.getInstance("订单不存在");
  111. }
  112. return order;
  113. }
  114. @Override
  115. public SpecialMemberEntitlement getMemberEntitlement(Long userId) {
  116. return entitlementMapper.selectOne(Wrappers.lambdaQuery(SpecialMemberEntitlement.class)
  117. .eq(SpecialMemberEntitlement::getUserId, userId)
  118. .last("limit 1"));
  119. }
  120. @Override
  121. @Transactional(rollbackFor = Throwable.class)
  122. public void handleAlipayNotify(Map<String, String> params) throws Exception {
  123. String appId = params.get("app_id");
  124. ShopConfig shopConfig = StrUtil.isBlank(appId) ? null : shopConfigMapper.getByAppId(appId);
  125. if (shopConfig == null || !AlipaySignature.rsaCheckV1(params, shopConfig.getPublicKey(),
  126. BaseZfbConfig.charset, BaseZfbConfig.signType)) {
  127. throw BusinessRuntimeException.getInstance("支付宝回调验签失败");
  128. }
  129. String orderNo = params.get("out_trade_no");
  130. SpecialPayOrder order = orderMapper.selectByOrderNoForUpdate(orderNo);
  131. if (order == null) {
  132. throw BusinessRuntimeException.getInstance("特殊支付订单不存在");
  133. }
  134. if (!StrUtil.equals(order.getShopId(), appId)) {
  135. throw BusinessRuntimeException.getInstance("支付宝回调商户不匹配");
  136. }
  137. String tradeStatus = params.get("trade_status");
  138. if (!AliPayTradeStatus.TRADE_SUCCESS.getStatus().equals(tradeStatus)
  139. && !AliPayTradeStatus.TRADE_FINISHED.getStatus().equals(tradeStatus)) {
  140. throw BusinessRuntimeException.getInstance("支付宝交易状态未成功");
  141. }
  142. verifyOrderIdentity(params, order);
  143. verifyAmount(params.get("total_amount"), order.getAmount());
  144. String tradeNo = params.get("trade_no");
  145. if (StrUtil.isBlank(tradeNo)) {
  146. throw BusinessRuntimeException.getInstance("支付宝交易号为空");
  147. }
  148. if (order.getStatus() == SpecialPayOrder.Status.PAID) {
  149. if (!StrUtil.equals(order.getAlipayTradeNo(), tradeNo)) {
  150. throw BusinessRuntimeException.getInstance("支付宝交易号不匹配");
  151. }
  152. return;
  153. }
  154. if (order.getStatus() != SpecialPayOrder.Status.CREATED) {
  155. throw BusinessRuntimeException.getInstance("当前订单状态不可支付");
  156. }
  157. Date payTime = new Date();
  158. if (StrUtil.isNotBlank(params.get("gmt_payment"))) {
  159. payTime = DateUtil.parse(params.get("gmt_payment"), "yyyy-MM-dd HH:mm:ss");
  160. }
  161. String buyerId = Optional.ofNullable(params.get("buyer_id"))
  162. .orElse(params.get("buyer_open_id"));
  163. if (orderMapper.markPaid(order.getId(), tradeNo, buyerId, payTime) != 1) {
  164. throw BusinessRuntimeException.getInstance("订单支付状态更新失败");
  165. }
  166. if (order.getDurationDays() == null || order.getDurationDays() <= 0) {
  167. throw BusinessRuntimeException.getInstance("订单套餐配置异常");
  168. }
  169. entitlementMapper.extend(order.getUserId(), order.getDurationDays(), order.getId());
  170. if (orderMapper.markFulfilled(order.getId()) != 1) {
  171. throw BusinessRuntimeException.getInstance("会员权益发放失败");
  172. }
  173. log.info("特殊支付宝订单支付并履约成功, orderNo:{}, tradeNo:{}", orderNo, tradeNo);
  174. }
  175. private String getAlipayProductCode(Integer payType) {
  176. if (Integer.valueOf(1).equals(payType)) {
  177. return ZfbProductCode.MOBILE_WEB.getProductCode();
  178. }
  179. if (Integer.valueOf(2).equals(payType)) {
  180. return ZfbProductCode.PC_WEB.getProductCode();
  181. }
  182. throw BusinessRuntimeException.getInstance("不支持的支付宝支付方式");
  183. }
  184. private void verifyOrderIdentity(Map<String, String> params, SpecialPayOrder order) {
  185. try {
  186. String body = Codec.DoBase64.custom().setData(params.get("body")).decodeAsText();
  187. OrderAttach attach = Jsons.parseObject(body, OrderAttach.class);
  188. if (attach == null || !order.getId().equals(attach.getO())
  189. || !StrUtil.equals(order.getOrderNo(), params.get("out_trade_no"))) {
  190. throw BusinessRuntimeException.getInstance("支付宝回调订单不匹配");
  191. }
  192. } catch (BusinessRuntimeException e) {
  193. throw e;
  194. } catch (Exception e) {
  195. throw BusinessRuntimeException.getInstance("支付宝回调订单参数异常");
  196. }
  197. }
  198. private void verifyAmount(String totalAmount, BigDecimal expectedCents) {
  199. try {
  200. BigDecimal callbackCents = new BigDecimal(totalAmount)
  201. .multiply(BigDecimal.valueOf(100)).setScale(0, RoundingMode.UNNECESSARY);
  202. if (expectedCents == null || callbackCents.compareTo(expectedCents) != 0) {
  203. throw BusinessRuntimeException.getInstance("支付宝回调金额不匹配");
  204. }
  205. } catch (BusinessRuntimeException e) {
  206. throw e;
  207. } catch (Exception e) {
  208. throw BusinessRuntimeException.getInstance("支付宝回调金额异常");
  209. }
  210. }
  211. }