OmgPaymentQueryService.java 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. package com.ruoyi.app.omgpay;
  2. import com.ruoyi.app.omgpay.dto.OmgQueryPaymentResponse;
  3. import com.ruoyi.system.omgpay.domain.OmgPaymentAttempt;
  4. import com.ruoyi.system.omgpay.domain.OmgPaymentOrderSnapshot;
  5. import com.ruoyi.system.omgpay.service.IOmgPaymentAttemptService;
  6. import org.slf4j.Logger;
  7. import org.slf4j.LoggerFactory;
  8. import org.springframework.stereotype.Service;
  9. import org.springframework.beans.factory.annotation.Autowired;
  10. import java.math.BigDecimal;
  11. import java.time.Clock;
  12. import java.time.LocalDateTime;
  13. import java.time.ZoneId;
  14. import java.time.format.DateTimeFormatter;
  15. import java.time.format.DateTimeParseException;
  16. import java.util.Date;
  17. import java.util.LinkedHashMap;
  18. import java.util.List;
  19. import java.util.Map;
  20. import static com.ruoyi.app.omgpay.OmgPaymentErrorCode.*;
  21. /** Queries the one current payment attempt and compensates for a lost paid callback. */
  22. @Service
  23. public class OmgPaymentQueryService {
  24. private static final Logger log = LoggerFactory.getLogger(OmgPaymentQueryService.class);
  25. private static final int ATTEMPT_PAID = 1;
  26. private static final String TRADE_UNPAID = "0";
  27. private static final String TRADE_PAID = "1";
  28. private static final String TRADE_FAILED = "10200095";
  29. private static final DateTimeFormatter OMG_DATE = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
  30. private static final ZoneId TAIPEI = ZoneId.of("Asia/Taipei");
  31. private static final List<String> REQUIRED_FIELDS = List.of(
  32. "MerchantID", "MerchantTradeNo", "StoreID", "TradeNo", "TradeAmt",
  33. "PaymentDate", "PaymentType", "HandlingCharge", "PaymentTypeChargeFee",
  34. "TradeDate", "TradeStatus", "ItemName", "CustomField1", "CustomField2",
  35. "CustomField3", "CustomField4", "CheckMacValue");
  36. private final IOmgPaymentAttemptService attempts;
  37. private final OmgPaymentQueryGateway gateway;
  38. private final OmgQueryResponseParser parser;
  39. private final OmgCheckMacSigner signer;
  40. private final OmgPaymentNotifyService settlement;
  41. private final Clock clock;
  42. @Autowired
  43. public OmgPaymentQueryService(IOmgPaymentAttemptService attempts,
  44. OmgPaymentQueryGateway gateway,
  45. OmgQueryResponseParser parser,
  46. OmgCheckMacSigner signer,
  47. OmgPaymentNotifyService settlement) {
  48. this(attempts, gateway, parser, signer, settlement, Clock.systemUTC());
  49. }
  50. OmgPaymentQueryService(IOmgPaymentAttemptService attempts,
  51. OmgPaymentQueryGateway gateway,
  52. OmgQueryResponseParser parser,
  53. OmgCheckMacSigner signer,
  54. OmgPaymentNotifyService settlement,
  55. Clock clock) {
  56. this.attempts = attempts;
  57. this.gateway = gateway;
  58. this.parser = parser;
  59. this.signer = signer;
  60. this.settlement = settlement;
  61. this.clock = clock;
  62. }
  63. public OmgQueryPaymentResponse query(Long userId, String orderId) {
  64. if (userId == null) {
  65. throw business(AUTH_REQUIRED);
  66. }
  67. String normalizedOrderId = normalizeOrderId(orderId);
  68. OmgPaymentOrderSnapshot order = attempts.selectOrder(normalizedOrderId);
  69. if (order == null || !userId.equals(order.getUserId())) {
  70. throw business(ORDER_NOT_AVAILABLE);
  71. }
  72. OmgPaymentAttempt attempt = selectCurrentAttempt(order);
  73. validateAttempt(attempt, order.getStoreId());
  74. log.info("OMG payment query started orderId={}, userId={}, storeId={}, merchantTradeNo={}",
  75. OmgPaymentController.safeLogOrderId(order.getDdId()), userId, order.getStoreId(),
  76. OmgPaymentCreateService.maskMerchantTradeNo(attempt.getMerchantTradeNo()));
  77. return queryAttempt(attempt, order.getDdId(), order.getStoreId(), "USER");
  78. }
  79. /** Reuses the verified query and settlement path for one scheduler-reserved CREATED attempt. */
  80. public OmgQueryPaymentResponse reconcile(OmgPaymentAttempt attempt) {
  81. Long storeId = attempt == null ? null : attempt.getStoreId();
  82. validateAttempt(attempt, storeId);
  83. log.info("OMG automatic compensation query started orderId={}, storeId={}, merchantTradeNo={}, queryCount={}",
  84. OmgPaymentController.safeLogOrderId(attempt.getDdId()), storeId,
  85. OmgPaymentCreateService.maskMerchantTradeNo(attempt.getMerchantTradeNo()),
  86. attempt.getQueryCount());
  87. return queryAttempt(attempt, attempt.getDdId(), storeId, "AUTO");
  88. }
  89. private OmgQueryPaymentResponse queryAttempt(OmgPaymentAttempt attempt, String orderId,
  90. Long storeId, String source) {
  91. try {
  92. Map<String, String> response = parser.parse(gateway.query(buildRequest(attempt)));
  93. validateResponse(response, attempt);
  94. String tradeStatus = response.get("TradeStatus");
  95. String status = synchronizeIfFinal(tradeStatus, response, attempt);
  96. log.info("OMG payment query completed source={}, orderId={}, merchantTradeNo={}, tradeNo={}, "
  97. + "gatewayTradeStatus={}, localStatus={}",
  98. source, OmgPaymentController.safeLogOrderId(orderId),
  99. OmgPaymentCreateService.maskMerchantTradeNo(attempt.getMerchantTradeNo()),
  100. maskTradeNo(response.get("TradeNo")), tradeStatus, status);
  101. return toResponse(status, response);
  102. } catch (OmgPaymentBusinessException exception) {
  103. throw exception;
  104. } catch (Exception exception) {
  105. log.error("OMG payment query failed source={}, orderId={}, merchantTradeNo={}",
  106. source, OmgPaymentController.safeLogOrderId(orderId),
  107. OmgPaymentCreateService.maskMerchantTradeNo(attempt.getMerchantTradeNo()), exception);
  108. throw business(PAYMENT_QUERY_FAILED, storeId);
  109. }
  110. }
  111. private OmgPaymentAttempt selectCurrentAttempt(OmgPaymentOrderSnapshot order) {
  112. if (order.getPayStatus() != null && order.getPayStatus() == 1L) {
  113. return attempts.selectPaidByDdId(order.getDdId());
  114. }
  115. return attempts.selectActiveCreatedByDdId(order.getDdId());
  116. }
  117. private Map<String, String> buildRequest(OmgPaymentAttempt attempt) {
  118. LinkedHashMap<String, String> fields = new LinkedHashMap<>();
  119. fields.put("MerchantID", attempt.getMerchantId());
  120. fields.put("MerchantTradeNo", attempt.getMerchantTradeNo());
  121. fields.put("TimeStamp", String.valueOf(clock.instant().getEpochSecond()));
  122. fields.put("CheckMacValue", signer.sign(fields,
  123. attempt.getHashKeySnapshot(), attempt.getHashIvSnapshot()));
  124. return fields;
  125. }
  126. private void validateResponse(Map<String, String> response, OmgPaymentAttempt attempt) {
  127. if (!REQUIRED_FIELDS.stream().allMatch(response::containsKey)) {
  128. throw new IllegalArgumentException("OMG query response has missing fields");
  129. }
  130. String checkMacValue = response.get("CheckMacValue");
  131. if (checkMacValue == null || !checkMacValue.matches("(?i)[0-9a-f]{64}")) {
  132. throw new IllegalArgumentException("OMG query response signature is malformed");
  133. }
  134. LinkedHashMap<String, String> signingFields = new LinkedHashMap<>(response);
  135. signingFields.remove("CheckMacValue");
  136. String expected = signer.sign(signingFields,
  137. attempt.getHashKeySnapshot(), attempt.getHashIvSnapshot());
  138. if (!OmgPaymentNotifyService.secureEquals(expected, checkMacValue)) {
  139. throw new IllegalArgumentException("OMG query response signature mismatch");
  140. }
  141. if (!attempt.getMerchantId().equals(response.get("MerchantID"))
  142. || !attempt.getMerchantTradeNo().equals(response.get("MerchantTradeNo"))
  143. || !String.valueOf(attempt.getAmount()).equals(response.get("TradeAmt"))) {
  144. throw new IllegalArgumentException("OMG query response identity mismatch");
  145. }
  146. }
  147. private String synchronizeIfFinal(String tradeStatus, Map<String, String> fields,
  148. OmgPaymentAttempt attempt) {
  149. if (attempt.getAttemptStatus() != null && attempt.getAttemptStatus() == ATTEMPT_PAID
  150. && !TRADE_PAID.equals(tradeStatus)) {
  151. log.error("OMG query cannot downgrade paid attempt merchantTradeNo={}, gatewayTradeStatus={}",
  152. OmgPaymentCreateService.maskMerchantTradeNo(attempt.getMerchantTradeNo()), tradeStatus);
  153. return "PAID";
  154. }
  155. if (TRADE_UNPAID.equals(tradeStatus)) {
  156. return "UNPAID";
  157. }
  158. if (!TRADE_PAID.equals(tradeStatus) && !TRADE_FAILED.equals(tradeStatus)) {
  159. return "UNKNOWN";
  160. }
  161. OmgPaymentSettlementResult result = settlement.synchronizeVerifiedQuery(
  162. toGatewayFacts(fields, attempt, Integer.parseInt(tradeStatus)));
  163. return result.name();
  164. }
  165. private static OmgPaymentGatewayFacts toGatewayFacts(Map<String, String> fields,
  166. OmgPaymentAttempt attempt,
  167. int tradeStatus) {
  168. boolean paid = tradeStatus == 1;
  169. String tradeNo = blankToNull(fields.get("TradeNo"));
  170. if (paid && tradeNo == null) {
  171. throw new IllegalArgumentException("paid query response has no TradeNo");
  172. }
  173. String paymentType = blankToNull(fields.get("PaymentType"));
  174. if (paid && paymentType == null) {
  175. throw new IllegalArgumentException("paid query response has no PaymentType");
  176. }
  177. BigDecimal fee = parseDecimal(fields.get("PaymentTypeChargeFee"));
  178. if (fee == null || fee.signum() < 0) {
  179. throw new IllegalArgumentException("invalid payment fee");
  180. }
  181. return new OmgPaymentGatewayFacts(OmgPaymentFactSource.QUERY,
  182. attempt.getMerchantId(), attempt.getMerchantTradeNo(), attempt.getAmount(),
  183. tradeStatus, "TradeStatus=" + tradeStatus, tradeNo, paymentType,
  184. parseDate(fields.get("PaymentDate"), paid),
  185. parseDate(fields.get("TradeDate"), true), fee, null);
  186. }
  187. private static OmgQueryPaymentResponse toResponse(String status, Map<String, String> fields) {
  188. return new OmgQueryPaymentResponse(status, fields.get("TradeStatus"),
  189. fields.get("MerchantTradeNo"), blankToNull(fields.get("TradeNo")),
  190. Integer.valueOf(fields.get("TradeAmt")), blankToNull(fields.get("PaymentDate")),
  191. blankToNull(fields.get("TradeDate")), blankToNull(fields.get("PaymentType")),
  192. fields.get("HandlingCharge"), fields.get("PaymentTypeChargeFee"));
  193. }
  194. private static void validateAttempt(OmgPaymentAttempt attempt, Long storeId) {
  195. if (attempt == null) {
  196. throw business(PAYMENT_QUERY_NOT_AVAILABLE, storeId);
  197. }
  198. if (isBlank(attempt.getMerchantId()) || isBlank(attempt.getMerchantTradeNo())
  199. || attempt.getAmount() == null || attempt.getAmount() <= 0
  200. || isBlank(attempt.getHashKeySnapshot()) || isBlank(attempt.getHashIvSnapshot())) {
  201. throw business(PAYMENT_QUERY_FAILED, storeId);
  202. }
  203. }
  204. private static String normalizeOrderId(String orderId) {
  205. if (isBlank(orderId) || orderId.trim().length() > 64) {
  206. throw business(ORDER_REQUIRED);
  207. }
  208. return orderId.trim();
  209. }
  210. private static Date parseDate(String value, boolean required) {
  211. if (isBlank(value)) {
  212. if (required) {
  213. throw new IllegalArgumentException("required OMG date is missing");
  214. }
  215. return null;
  216. }
  217. try {
  218. return Date.from(LocalDateTime.parse(value, OMG_DATE).atZone(TAIPEI).toInstant());
  219. } catch (DateTimeParseException exception) {
  220. throw new IllegalArgumentException("invalid OMG date", exception);
  221. }
  222. }
  223. private static BigDecimal parseDecimal(String value) {
  224. try {
  225. return isBlank(value) ? null : new BigDecimal(value);
  226. } catch (NumberFormatException exception) {
  227. throw new IllegalArgumentException("invalid OMG decimal", exception);
  228. }
  229. }
  230. private static String blankToNull(String value) {
  231. return isBlank(value) ? null : value;
  232. }
  233. private static String maskTradeNo(String tradeNo) {
  234. if (isBlank(tradeNo)) {
  235. return "<empty>";
  236. }
  237. return tradeNo.length() <= 6 ? "***" : "***" + tradeNo.substring(tradeNo.length() - 6);
  238. }
  239. private static boolean isBlank(String value) {
  240. return value == null || value.isBlank();
  241. }
  242. private static OmgPaymentBusinessException business(OmgPaymentErrorCode code) {
  243. return new OmgPaymentBusinessException(code);
  244. }
  245. private static OmgPaymentBusinessException business(OmgPaymentErrorCode code, Long storeId) {
  246. return new OmgPaymentBusinessException(code, storeId);
  247. }
  248. }