OmgPaymentQueryService.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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 String TRADE_NOT_FOUND = "10200047";
  30. private static final DateTimeFormatter OMG_DATE = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
  31. private static final ZoneId TAIPEI = ZoneId.of("Asia/Taipei");
  32. private static final List<String> CORE_REQUIRED_FIELDS = List.of(
  33. "MerchantID", "MerchantTradeNo", "TradeAmt", "TradeStatus", "CheckMacValue");
  34. private static final List<String> PAID_REQUIRED_FIELDS = List.of(
  35. "TradeNo", "PaymentDate", "PaymentType", "PaymentTypeChargeFee", "TradeDate");
  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(attempt.getGatewayEnvironment() == null
  93. ? gateway.query(buildRequest(attempt))
  94. : gateway.query(buildRequest(attempt), attempt.getGatewayEnvironment()));
  95. validateResponse(response, attempt);
  96. String tradeStatus = response.get("TradeStatus");
  97. String status = synchronizeIfFinal(tradeStatus, response, attempt);
  98. log.info("OMG payment query completed source={}, orderId={}, merchantTradeNo={}, tradeNo={}, "
  99. + "gatewayTradeStatus={}, localStatus={}",
  100. source, OmgPaymentController.safeLogOrderId(orderId),
  101. OmgPaymentCreateService.maskMerchantTradeNo(attempt.getMerchantTradeNo()),
  102. maskTradeNo(response.get("TradeNo")), tradeStatus, status);
  103. return toResponse(status, response);
  104. } catch (OmgPaymentBusinessException exception) {
  105. throw exception;
  106. } catch (Exception exception) {
  107. log.error("OMG payment query failed source={}, orderId={}, merchantTradeNo={}",
  108. source, OmgPaymentController.safeLogOrderId(orderId),
  109. OmgPaymentCreateService.maskMerchantTradeNo(attempt.getMerchantTradeNo()), exception);
  110. throw business(PAYMENT_QUERY_FAILED, storeId);
  111. }
  112. }
  113. private OmgPaymentAttempt selectCurrentAttempt(OmgPaymentOrderSnapshot order) {
  114. if (order.getPayStatus() != null && order.getPayStatus() == 1L) {
  115. return attempts.selectPaidByDdId(order.getDdId());
  116. }
  117. return attempts.selectActiveCreatedByDdId(order.getDdId());
  118. }
  119. private Map<String, String> buildRequest(OmgPaymentAttempt attempt) {
  120. LinkedHashMap<String, String> fields = new LinkedHashMap<>();
  121. fields.put("MerchantID", attempt.getMerchantId());
  122. fields.put("MerchantTradeNo", attempt.getMerchantTradeNo());
  123. fields.put("TimeStamp", String.valueOf(clock.instant().getEpochSecond()));
  124. fields.put("CheckMacValue", signer.sign(fields,
  125. attempt.getHashKeySnapshot(), attempt.getHashIvSnapshot()));
  126. return fields;
  127. }
  128. private void validateResponse(Map<String, String> response, OmgPaymentAttempt attempt) {
  129. List<String> missingCoreFields = missingOrBlankFields(response, CORE_REQUIRED_FIELDS);
  130. if (!missingCoreFields.isEmpty()) {
  131. log.warn("OMG query response rejected merchantTradeNo={} reason=missing_core_fields fields={}",
  132. OmgPaymentCreateService.maskMerchantTradeNo(attempt.getMerchantTradeNo()),
  133. missingCoreFields);
  134. throw new IllegalArgumentException("OMG query response has missing fields");
  135. }
  136. String checkMacValue = response.get("CheckMacValue");
  137. if (checkMacValue == null || !checkMacValue.matches("(?i)[0-9a-f]{64}")) {
  138. throw new IllegalArgumentException("OMG query response signature is malformed");
  139. }
  140. LinkedHashMap<String, String> signingFields = new LinkedHashMap<>(response);
  141. signingFields.remove("CheckMacValue");
  142. String expected = signer.sign(signingFields,
  143. attempt.getHashKeySnapshot(), attempt.getHashIvSnapshot());
  144. if (!OmgPaymentNotifyService.secureEquals(expected, checkMacValue)) {
  145. throw new IllegalArgumentException("OMG query response signature mismatch");
  146. }
  147. String tradeStatus = response.get("TradeStatus");
  148. String expectedAmount = TRADE_NOT_FOUND.equals(tradeStatus)
  149. ? "0" : String.valueOf(attempt.getAmount());
  150. if (!attempt.getMerchantId().equals(response.get("MerchantID"))
  151. || !attempt.getMerchantTradeNo().equals(response.get("MerchantTradeNo"))
  152. || !expectedAmount.equals(response.get("TradeAmt"))) {
  153. throw new IllegalArgumentException("OMG query response identity mismatch");
  154. }
  155. if (TRADE_PAID.equals(tradeStatus)) {
  156. List<String> missingPaidFields = missingOrBlankFields(response, PAID_REQUIRED_FIELDS);
  157. if (!missingPaidFields.isEmpty()) {
  158. log.warn("OMG paid query response rejected merchantTradeNo={} "
  159. + "reason=missing_settlement_fields fields={}",
  160. OmgPaymentCreateService.maskMerchantTradeNo(attempt.getMerchantTradeNo()),
  161. missingPaidFields);
  162. throw new IllegalArgumentException("OMG paid query response has missing fields");
  163. }
  164. }
  165. }
  166. private static List<String> missingOrBlankFields(Map<String, String> response,
  167. List<String> requiredFields) {
  168. return requiredFields.stream()
  169. .filter(field -> isBlank(response.get(field)))
  170. .toList();
  171. }
  172. private String synchronizeIfFinal(String tradeStatus, Map<String, String> fields,
  173. OmgPaymentAttempt attempt) {
  174. if (attempt.getAttemptStatus() != null && attempt.getAttemptStatus() == ATTEMPT_PAID
  175. && !TRADE_PAID.equals(tradeStatus)) {
  176. log.error("OMG query cannot downgrade paid attempt merchantTradeNo={}, gatewayTradeStatus={}",
  177. OmgPaymentCreateService.maskMerchantTradeNo(attempt.getMerchantTradeNo()), tradeStatus);
  178. return "PAID";
  179. }
  180. if (TRADE_UNPAID.equals(tradeStatus)) {
  181. return "UNPAID";
  182. }
  183. if (!TRADE_PAID.equals(tradeStatus)
  184. && !TRADE_FAILED.equals(tradeStatus)
  185. && !TRADE_NOT_FOUND.equals(tradeStatus)) {
  186. return "UNKNOWN";
  187. }
  188. OmgPaymentSettlementResult result = settlement.synchronizeVerifiedQuery(
  189. toGatewayFacts(fields, attempt, Integer.parseInt(tradeStatus)));
  190. return result.name();
  191. }
  192. private static OmgPaymentGatewayFacts toGatewayFacts(Map<String, String> fields,
  193. OmgPaymentAttempt attempt,
  194. int tradeStatus) {
  195. boolean paid = tradeStatus == 1;
  196. String tradeNo = blankToNull(fields.get("TradeNo"));
  197. if (paid && tradeNo == null) {
  198. throw new IllegalArgumentException("paid query response has no TradeNo");
  199. }
  200. String paymentType = blankToNull(fields.get("PaymentType"));
  201. if (paid && paymentType == null) {
  202. throw new IllegalArgumentException("paid query response has no PaymentType");
  203. }
  204. BigDecimal fee = parseDecimal(fields.get("PaymentTypeChargeFee"));
  205. if ((paid && fee == null) || (fee != null && fee.signum() < 0)) {
  206. throw new IllegalArgumentException("invalid payment fee");
  207. }
  208. return new OmgPaymentGatewayFacts(OmgPaymentFactSource.QUERY,
  209. attempt.getMerchantId(), attempt.getMerchantTradeNo(), attempt.getAmount(),
  210. tradeStatus, "TradeStatus=" + tradeStatus, tradeNo, paymentType,
  211. parseDate(fields.get("PaymentDate"), paid),
  212. parseDate(fields.get("TradeDate"), paid), fee, null,
  213. blankToNull(fields.get("gwsr")));
  214. }
  215. private static OmgQueryPaymentResponse toResponse(String status, Map<String, String> fields) {
  216. return new OmgQueryPaymentResponse(status, fields.get("TradeStatus"),
  217. fields.get("MerchantTradeNo"), blankToNull(fields.get("TradeNo")),
  218. Integer.valueOf(fields.get("TradeAmt")), blankToNull(fields.get("PaymentDate")),
  219. blankToNull(fields.get("TradeDate")), blankToNull(fields.get("PaymentType")),
  220. fields.get("HandlingCharge"), fields.get("PaymentTypeChargeFee"));
  221. }
  222. private static void validateAttempt(OmgPaymentAttempt attempt, Long storeId) {
  223. if (attempt == null) {
  224. throw business(PAYMENT_QUERY_NOT_AVAILABLE, storeId);
  225. }
  226. if (isBlank(attempt.getMerchantId()) || isBlank(attempt.getMerchantTradeNo())
  227. || attempt.getAmount() == null || attempt.getAmount() <= 0
  228. || isBlank(attempt.getHashKeySnapshot()) || isBlank(attempt.getHashIvSnapshot())) {
  229. throw business(PAYMENT_QUERY_FAILED, storeId);
  230. }
  231. }
  232. private static String normalizeOrderId(String orderId) {
  233. if (isBlank(orderId) || orderId.trim().length() > 64) {
  234. throw business(ORDER_REQUIRED);
  235. }
  236. return orderId.trim();
  237. }
  238. private static Date parseDate(String value, boolean required) {
  239. if (isBlank(value)) {
  240. if (required) {
  241. throw new IllegalArgumentException("required OMG date is missing");
  242. }
  243. return null;
  244. }
  245. try {
  246. return Date.from(LocalDateTime.parse(value, OMG_DATE).atZone(TAIPEI).toInstant());
  247. } catch (DateTimeParseException exception) {
  248. throw new IllegalArgumentException("invalid OMG date", exception);
  249. }
  250. }
  251. private static BigDecimal parseDecimal(String value) {
  252. try {
  253. return isBlank(value) ? null : new BigDecimal(value);
  254. } catch (NumberFormatException exception) {
  255. throw new IllegalArgumentException("invalid OMG decimal", exception);
  256. }
  257. }
  258. private static String blankToNull(String value) {
  259. return isBlank(value) ? null : value;
  260. }
  261. private static String maskTradeNo(String tradeNo) {
  262. if (isBlank(tradeNo)) {
  263. return "<empty>";
  264. }
  265. return tradeNo.length() <= 6 ? "***" : "***" + tradeNo.substring(tradeNo.length() - 6);
  266. }
  267. private static boolean isBlank(String value) {
  268. return value == null || value.isBlank();
  269. }
  270. private static OmgPaymentBusinessException business(OmgPaymentErrorCode code) {
  271. return new OmgPaymentBusinessException(code);
  272. }
  273. private static OmgPaymentBusinessException business(OmgPaymentErrorCode code, Long storeId) {
  274. return new OmgPaymentBusinessException(code, storeId);
  275. }
  276. }