SpecialPayServiceImpl.java 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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.alipay.api.AlipayClient;
  6. import com.alipay.api.domain.AlipayTradeRefundModel;
  7. import com.alipay.api.request.AlipayTradeRefundRequest;
  8. import com.alipay.api.response.AlipayTradeRefundResponse;
  9. import com.baomidou.mybatisplus.core.toolkit.Wrappers;
  10. import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
  11. import com.cyksj.common.EnvCommonService;
  12. import com.cyksj.common.exception.BusinessRuntimeException;
  13. import com.cyksj.common.snowflake.Sequence;
  14. import com.cyksj.common.util.Codec;
  15. import com.cyksj.common.util.Jsons;
  16. import com.cyksj.config.zfb.BaseZfbConfig;
  17. import com.cyksj.config.zfb.AliPayClientFactory;
  18. import com.cyksj.config.zfb.ZfbProductCode;
  19. import com.cyksj.mapper.channel.ShopConfigMapper;
  20. import com.cyksj.mapper.special.SpecialMemberEntitlementMapper;
  21. import com.cyksj.mapper.special.SpecialPayOrderMapper;
  22. import com.cyksj.mapper.special.SpecialPayProductMapper;
  23. import com.cyksj.model.dto.AliPayParams;
  24. import com.cyksj.model.entity.ShopConfig;
  25. import com.cyksj.model.entity.SpecialPayOrder;
  26. import com.cyksj.model.entity.SpecialPayProduct;
  27. import com.cyksj.model.entity.SpecialMemberEntitlement;
  28. import com.cyksj.model.request.SpecialPayCreateReq;
  29. import com.cyksj.model.request.OrderAttach;
  30. import com.cyksj.model.response.AliPayTradeStatus;
  31. import com.cyksj.model.response.SpecialPayCreateRep;
  32. import com.cyksj.model.response.SpecialMemberInfoRep;
  33. import com.cyksj.service.pay.AliPayCommonService;
  34. import com.cyksj.service.special.SpecialPayService;
  35. import lombok.RequiredArgsConstructor;
  36. import lombok.extern.slf4j.Slf4j;
  37. import org.springframework.stereotype.Service;
  38. import org.springframework.transaction.annotation.Transactional;
  39. import java.math.BigDecimal;
  40. import java.math.RoundingMode;
  41. import java.util.Date;
  42. import java.util.List;
  43. import java.util.Map;
  44. import java.util.Optional;
  45. @Slf4j
  46. @Service
  47. @RequiredArgsConstructor
  48. public class SpecialPayServiceImpl implements SpecialPayService {
  49. private static final Sequence SEQUENCE = new Sequence(0);
  50. private static final int ORDER_EXPIRE_MINUTES = 5;
  51. private static final String YING_WANG_FEI_ALIPAY_APP_ID = "2021006115648946";
  52. private final SpecialPayProductMapper productMapper;
  53. private final SpecialPayOrderMapper orderMapper;
  54. private final SpecialMemberEntitlementMapper entitlementMapper;
  55. private final ShopConfigMapper shopConfigMapper;
  56. private final AliPayCommonService aliPayCommonService;
  57. private final EnvCommonService envCommonService;
  58. @Override
  59. @Transactional(rollbackFor = Throwable.class)
  60. public void refundOrder(String orderNo) throws Exception {
  61. SpecialPayOrder order = orderMapper.selectOne(Wrappers.lambdaQuery(SpecialPayOrder.class)
  62. .eq(SpecialPayOrder::getOrderNo, orderNo).last("limit 1 for update"));
  63. if (order == null) throw BusinessRuntimeException.getInstance("订单不存在");
  64. if (order.getStatus() == SpecialPayOrder.Status.REFUNDED) return;
  65. if (order.getStatus() != SpecialPayOrder.Status.PAID || StrUtil.isBlank(order.getAlipayTradeNo())) throw BusinessRuntimeException.getInstance("当前订单状态不支持退款");
  66. SpecialMemberEntitlement entitlement = entitlementMapper.selectOne(Wrappers.lambdaQuery(SpecialMemberEntitlement.class)
  67. .eq(SpecialMemberEntitlement::getUserId, order.getUserId()).last("limit 1 for update"));
  68. if (entitlement != null && !order.getId().equals(entitlement.getLastOrderId())) throw BusinessRuntimeException.getInstance("存在后续会员订单,暂不支持自动退款");
  69. AlipayTradeRefundModel model = new AlipayTradeRefundModel();
  70. model.setTradeNo(order.getAlipayTradeNo());
  71. model.setRefundAmount(order.getAmount().divide(BigDecimal.valueOf(100)).setScale(2, RoundingMode.UNNECESSARY).toPlainString());
  72. model.setRefundReason("特殊会员订单退款");
  73. model.setOutRequestNo("SR" + order.getOrderNo());
  74. AlipayTradeRefundRequest refundRequest = new AlipayTradeRefundRequest();
  75. refundRequest.setBizModel(model);
  76. AlipayTradeRefundResponse response = AliPayClientFactory.getAlipayClient(order.getShopId()).execute(refundRequest);
  77. if (response == null || !response.isSuccess()) throw BusinessRuntimeException.getInstance("支付宝退款失败");
  78. if (orderMapper.markRefunded(order.getId()) != 1) throw BusinessRuntimeException.getInstance("退款状态更新失败");
  79. if (entitlement != null) entitlementMapper.rollbackIfLastOrder(order.getUserId(), order.getDurationDays(), order.getId());
  80. }
  81. @Override
  82. public Page<SpecialPayOrder> getManageOrderPage(Integer start, Integer limit, String orderNo,
  83. Long userId, String productCode, SpecialPayOrder.Status status) {
  84. int pageNo = start == null || start < 1 ? 1 : start;
  85. int pageSize = limit == null || limit < 1 ? 10 : Math.min(limit, 100);
  86. return orderMapper.selectPage(new Page<>(pageNo, pageSize), Wrappers.lambdaQuery(SpecialPayOrder.class)
  87. .like(StrUtil.isNotBlank(orderNo), SpecialPayOrder::getOrderNo, orderNo)
  88. .eq(userId != null, SpecialPayOrder::getUserId, userId)
  89. .eq(StrUtil.isNotBlank(productCode), SpecialPayOrder::getProductCode, productCode)
  90. .eq(status != null, SpecialPayOrder::getStatus, status)
  91. .orderByDesc(SpecialPayOrder::getId));
  92. }
  93. @Override
  94. public List<SpecialPayProduct> getEnabledProducts() {
  95. return productMapper.selectList(Wrappers.lambdaQuery(SpecialPayProduct.class)
  96. .eq(SpecialPayProduct::getEnabled, true)
  97. .orderByAsc(SpecialPayProduct::getSortBy, SpecialPayProduct::getId));
  98. }
  99. @Override
  100. @Transactional(rollbackFor = Throwable.class)
  101. public SpecialPayCreateRep createAlipayOrder(Long userId, SpecialPayCreateReq request) throws Exception {
  102. SpecialPayProduct product = productMapper.selectOne(Wrappers.lambdaQuery(SpecialPayProduct.class)
  103. .eq(SpecialPayProduct::getProductCode, request.getProductCode())
  104. .eq(SpecialPayProduct::getEnabled, true)
  105. .last("limit 1"));
  106. if (product == null) {
  107. throw BusinessRuntimeException.getInstance("支付套餐不存在或已下架");
  108. }
  109. if (product.getAmount() == null || product.getAmount().compareTo(BigDecimal.ZERO) <= 0
  110. || product.getDurationDays() == null || product.getDurationDays() <= 0) {
  111. throw BusinessRuntimeException.getInstance("支付套餐配置异常");
  112. }
  113. String alipayProductCode = getAlipayProductCode(request.getPayType());
  114. ShopConfig shopConfig = shopConfigMapper.getByAppId(YING_WANG_FEI_ALIPAY_APP_ID);
  115. if (shopConfig == null || !StrUtil.equals("zfb", shopConfig.getType())) {
  116. throw BusinessRuntimeException.getInstance("未配置影网飞支付宝商户");
  117. }
  118. Date now = new Date();
  119. SpecialPayOrder order = new SpecialPayOrder();
  120. order.setOrderNo("SP" + SEQUENCE.nextId());
  121. order.setUserId(userId);
  122. order.setProductCode(product.getProductCode());
  123. order.setSubject(product.getProductName());
  124. order.setAmount(product.getAmount());
  125. order.setDurationDays(product.getDurationDays());
  126. order.setStatus(SpecialPayOrder.Status.CREATED);
  127. order.setFulfillStatus(SpecialPayOrder.FulfillStatus.INIT);
  128. order.setShopId(YING_WANG_FEI_ALIPAY_APP_ID);
  129. order.setExpireTime(DateUtil.offsetMinute(now, ORDER_EXPIRE_MINUTES));
  130. order.setCreatedTime(now);
  131. order.setUpdateTime(now);
  132. orderMapper.insert(order);
  133. String notifyUrl = envCommonService.getNotifyHost() + BaseZfbConfig.specialPayNotifyUrl;
  134. AliPayParams payParams = aliPayCommonService.builderPayParams(
  135. order.getId(), order.getOrderNo(), order.getShopId(), order.getAmount(),
  136. order.getCreatedTime(), order.getSubject(), alipayProductCode,
  137. request.getPayMode(), notifyUrl, request.getReturnUrl());
  138. if (payParams == null || StrUtil.isBlank(payParams.getBody())) {
  139. throw BusinessRuntimeException.getInstance("支付宝下单失败");
  140. }
  141. SpecialPayCreateRep response = new SpecialPayCreateRep();
  142. response.setOrderNo(order.getOrderNo());
  143. response.setStatus(order.getStatus());
  144. response.setExpireTime(order.getExpireTime());
  145. response.setPayBody(payParams.getBody());
  146. return response;
  147. }
  148. @Override
  149. public SpecialPayOrder getUserOrder(Long userId, String orderNo) {
  150. SpecialPayOrder order = orderMapper.selectOne(Wrappers.lambdaQuery(SpecialPayOrder.class)
  151. .eq(SpecialPayOrder::getOrderNo, orderNo)
  152. .eq(SpecialPayOrder::getUserId, userId)
  153. .last("limit 1"));
  154. if (order == null) {
  155. throw BusinessRuntimeException.getInstance("订单不存在");
  156. }
  157. return order;
  158. }
  159. @Override
  160. public SpecialMemberEntitlement getMemberEntitlement(Long userId) {
  161. return entitlementMapper.selectOne(Wrappers.lambdaQuery(SpecialMemberEntitlement.class)
  162. .eq(SpecialMemberEntitlement::getUserId, userId)
  163. .last("limit 1"));
  164. }
  165. @Override
  166. public SpecialMemberInfoRep getMemberInfo(Long userId) {
  167. SpecialMemberEntitlement entitlement = getMemberEntitlement(userId);
  168. Date now = new Date();
  169. SpecialMemberInfoRep response = new SpecialMemberInfoRep();
  170. response.setUserId(userId);
  171. response.setMember(entitlement != null && entitlement.getExpireTime() != null
  172. && entitlement.getExpireTime().after(now));
  173. response.setExpireTime(entitlement == null ? null : entitlement.getExpireTime());
  174. response.setRemainingDays(Boolean.TRUE.equals(response.getMember())
  175. ? Math.max(1L, (entitlement.getExpireTime().getTime() - now.getTime() + 86400000L - 1) / 86400000L)
  176. : 0L);
  177. if (entitlement != null && entitlement.getLastOrderId() != null && entitlement.getLastOrderId() > 0) {
  178. SpecialPayOrder lastOrder = orderMapper.selectById(entitlement.getLastOrderId());
  179. if (lastOrder != null && userId.equals(lastOrder.getUserId())) {
  180. response.setLastOrderNo(lastOrder.getOrderNo());
  181. response.setProductCode(lastOrder.getProductCode());
  182. response.setProductName(lastOrder.getSubject());
  183. response.setLastOrderStatus(lastOrder.getStatus());
  184. }
  185. }
  186. return response;
  187. }
  188. @Override
  189. @Transactional(rollbackFor = Throwable.class)
  190. public void handleAlipayNotify(Map<String, String> params) throws Exception {
  191. String appId = params.get("app_id");
  192. ShopConfig shopConfig = StrUtil.isBlank(appId) ? null : shopConfigMapper.getByAppId(appId);
  193. if (shopConfig == null || !AlipaySignature.rsaCheckV1(params, shopConfig.getPublicKey(),
  194. BaseZfbConfig.charset, BaseZfbConfig.signType)) {
  195. throw BusinessRuntimeException.getInstance("支付宝回调验签失败");
  196. }
  197. String orderNo = params.get("out_trade_no");
  198. SpecialPayOrder order = orderMapper.selectByOrderNoForUpdate(orderNo);
  199. if (order == null) {
  200. throw BusinessRuntimeException.getInstance("特殊支付订单不存在");
  201. }
  202. if (!StrUtil.equals(order.getShopId(), appId)) {
  203. throw BusinessRuntimeException.getInstance("支付宝回调商户不匹配");
  204. }
  205. String tradeStatus = params.get("trade_status");
  206. if (!AliPayTradeStatus.TRADE_SUCCESS.getStatus().equals(tradeStatus)
  207. && !AliPayTradeStatus.TRADE_FINISHED.getStatus().equals(tradeStatus)) {
  208. throw BusinessRuntimeException.getInstance("支付宝交易状态未成功");
  209. }
  210. verifyOrderIdentity(params, order);
  211. verifyAmount(params.get("total_amount"), order.getAmount());
  212. String tradeNo = params.get("trade_no");
  213. if (StrUtil.isBlank(tradeNo)) {
  214. throw BusinessRuntimeException.getInstance("支付宝交易号为空");
  215. }
  216. if (order.getStatus() == SpecialPayOrder.Status.PAID) {
  217. if (!StrUtil.equals(order.getAlipayTradeNo(), tradeNo)) {
  218. throw BusinessRuntimeException.getInstance("支付宝交易号不匹配");
  219. }
  220. return;
  221. }
  222. if (order.getStatus() != SpecialPayOrder.Status.CREATED) {
  223. throw BusinessRuntimeException.getInstance("当前订单状态不可支付");
  224. }
  225. Date payTime = new Date();
  226. if (StrUtil.isNotBlank(params.get("gmt_payment"))) {
  227. payTime = DateUtil.parse(params.get("gmt_payment"), "yyyy-MM-dd HH:mm:ss");
  228. }
  229. String buyerId = Optional.ofNullable(params.get("buyer_id"))
  230. .orElse(params.get("buyer_open_id"));
  231. if (orderMapper.markPaid(order.getId(), tradeNo, buyerId, payTime) != 1) {
  232. throw BusinessRuntimeException.getInstance("订单支付状态更新失败");
  233. }
  234. if (order.getDurationDays() == null || order.getDurationDays() <= 0) {
  235. throw BusinessRuntimeException.getInstance("订单套餐配置异常");
  236. }
  237. entitlementMapper.extend(order.getUserId(), order.getDurationDays(), order.getId());
  238. if (orderMapper.markFulfilled(order.getId()) != 1) {
  239. throw BusinessRuntimeException.getInstance("会员权益发放失败");
  240. }
  241. log.info("特殊支付宝订单支付并履约成功, orderNo:{}, tradeNo:{}", orderNo, tradeNo);
  242. }
  243. private String getAlipayProductCode(Integer payType) {
  244. if (Integer.valueOf(1).equals(payType)) {
  245. return ZfbProductCode.MOBILE_WEB.getProductCode();
  246. }
  247. if (Integer.valueOf(2).equals(payType)) {
  248. return ZfbProductCode.PC_WEB.getProductCode();
  249. }
  250. throw BusinessRuntimeException.getInstance("不支持的支付宝支付方式");
  251. }
  252. private void verifyOrderIdentity(Map<String, String> params, SpecialPayOrder order) {
  253. try {
  254. String body = Codec.DoBase64.custom().setData(params.get("body")).decodeAsText();
  255. OrderAttach attach = Jsons.parseObject(body, OrderAttach.class);
  256. if (attach == null || !order.getId().equals(attach.getO())
  257. || !StrUtil.equals(order.getOrderNo(), params.get("out_trade_no"))) {
  258. throw BusinessRuntimeException.getInstance("支付宝回调订单不匹配");
  259. }
  260. } catch (BusinessRuntimeException e) {
  261. throw e;
  262. } catch (Exception e) {
  263. throw BusinessRuntimeException.getInstance("支付宝回调订单参数异常");
  264. }
  265. }
  266. private void verifyAmount(String totalAmount, BigDecimal expectedCents) {
  267. try {
  268. BigDecimal callbackCents = new BigDecimal(totalAmount)
  269. .multiply(BigDecimal.valueOf(100)).setScale(0, RoundingMode.UNNECESSARY);
  270. if (expectedCents == null || callbackCents.compareTo(expectedCents) != 0) {
  271. throw BusinessRuntimeException.getInstance("支付宝回调金额不匹配");
  272. }
  273. } catch (BusinessRuntimeException e) {
  274. throw e;
  275. } catch (Exception e) {
  276. throw BusinessRuntimeException.getInstance("支付宝回调金额异常");
  277. }
  278. }
  279. }