Sfoglia il codice sorgente

fix: 补齐汇付延时分账确认手续费

yonge 1 settimana fa
parent
commit
28aa71bf1a

+ 96 - 0
mec-biz/src/main/java/com/ym/mec/biz/service/impl/receipt/gateway/HuifuConfirmationFees.java

@@ -0,0 +1,96 @@
+package com.ym.mec.biz.service.impl.receipt.gateway;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.huifu.adapay.core.exception.BaseAdaPayException;
+import com.huifu.adapay.model.Payment;
+import com.ym.mec.biz.dal.dto.ReceiptChargesDto;
+import com.ym.mec.biz.dal.dto.ReceiptEntryDto;
+
+import java.math.BigDecimal;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+final class HuifuConfirmationFees {
+    private static final ObjectMapper JSON = new ObjectMapper();
+    private static final int PAGE_SIZE = 20;
+    private static final int MAX_PAGES_PER_PAYMENT = 20;
+    private static final long QUERY_BUDGET = TimeUnit.SECONDS.toNanos(30);
+    private final String appId;
+    private final String merchantKey;
+
+    HuifuConfirmationFees(String appId, String merchantKey) {
+        this.appId = appId;
+        this.merchantKey = merchantKey;
+    }
+
+    int supplement(List<ReceiptEntryDto> entries) {
+        long deadline = System.nanoTime() + QUERY_BUDGET;
+        int unavailable = 0;
+        for (ReceiptEntryDto entry : entries) {
+            if (entry.getCharges() != null && entry.getCharges().getFeeAmount().signum() > 0) continue;
+            try {
+                BigDecimal fee = confirmationFee(entry.getTradeNo(), deadline);
+                if (fee != null) entry.setCharges(ReceiptChargesDto.from(entry.getAmount(), fee));
+            } catch (BaseAdaPayException | BillHttp.Failure | IllegalArgumentException failure) {
+                entry.setCharges(null);
+                unavailable++;
+            }
+        }
+        return unavailable;
+    }
+
+    private BigDecimal confirmationFee(String paymentId, long deadline) throws BaseAdaPayException, BillHttp.Failure {
+        Map<String, BigDecimal> fees = new HashMap<>();
+        Map<String, Object> params = new HashMap<>();
+        params.put("app_id", appId);
+        params.put("payment_id", paymentId);
+        params.put("page_size", PAGE_SIZE);
+        for (int page = 1; page <= MAX_PAGES_PER_PAYMENT; page++) {
+            if (System.nanoTime() - deadline >= 0) throw new BillHttp.Failure("支付确认查询超时");
+            params.put("page_index", page);
+            JsonNode result = JSON.valueToTree(Payment.queryConfirmList(params, merchantKey));
+            validateIdentity(result, paymentId);
+            if (!"succeeded".equals(result.path("status").asText()) || !"list".equals(result.path("object").asText()) ||
+                    !"true".equals(result.path("prod_mode").asText())) throw invalidResponse();
+            JsonNode hasMore = result.path("has_more");
+            if (!hasMore.isBoolean()) throw invalidResponse();
+            JsonNode confirmations = result.path("payment_confirms");
+            if (confirmations.isArray()) {
+                for (JsonNode confirmation : confirmations) addFee(fees, confirmation, paymentId);
+            } else if (!confirmations.isMissingNode() && !confirmations.isNull()) {
+                throw invalidResponse();
+            }
+            if (!hasMore.booleanValue()) {
+                return fees.isEmpty() ? null : fees.values().stream().reduce(BigDecimal.ZERO, BigDecimal::add);
+            }
+            if (!confirmations.iterator().hasNext()) throw invalidResponse();
+        }
+        throw new BillHttp.Failure("支付确认记录超过查询上限");
+    }
+
+    private void addFee(Map<String, BigDecimal> fees, JsonNode confirmation, String paymentId) throws BillHttp.Failure {
+        validateIdentity(confirmation, paymentId);
+        String status = confirmation.path("status").asText();
+        if ("pending".equals(status) || "failed".equals(status)) return;
+        String id = confirmation.path("id").asText();
+        if (!"succeeded".equals(status) || id.isEmpty()) throw invalidResponse();
+        BigDecimal amount = BillFiles.money(confirmation.path("fee_amt").asText());
+        BigDecimal previous = fees.putIfAbsent(id, amount);
+        if (previous != null && previous.compareTo(amount) != 0) throw invalidResponse();
+    }
+
+    private void validateIdentity(JsonNode result, String paymentId) throws BillHttp.Failure {
+        if (result == null || !result.isObject()) throw invalidResponse();
+        if (!appId.equals(result.path("app_id").asText()) ||
+                (result.hasNonNull("payment_id") && !paymentId.equals(result.path("payment_id").asText()))) {
+            throw new BillHttp.WrongOwner();
+        }
+    }
+
+    private static BillHttp.Failure invalidResponse() {
+        return new BillHttp.Failure("汇付支付确认响应异常");
+    }
+}

+ 12 - 5
mec-biz/src/main/java/com/ym/mec/biz/service/impl/receipt/gateway/ProviderBills.java

@@ -25,6 +25,8 @@ final class ProviderBills {
     }
     private static final ObjectMapper JSON = new ObjectMapper().enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION);
     private static final String WX = "api.mch.weixin.qq.com";
+    private static final String HUIFU = "HUIFU";
+    private static final String MERCHANT_KEY = "merchantKey";
     private final String channel;
     private final BillCredentials keys;
     private final BillHttp http;
@@ -38,7 +40,7 @@ final class ProviderBills {
             keys.value("merchantSerial");
         } else {
             keys.value("appId");
-            if ("HUIFU".equals(channel)) keys.value("merchantKey");
+            if (HUIFU.equals(channel)) keys.value(MERCHANT_KEY);
             else keys.value("userId");
         }
     }
@@ -61,7 +63,7 @@ final class ProviderBills {
             return BillFiles.parse(channel, keys.value("merchantId"), day, data);
         }
         String owner;
-        if ("HUIFU".equals(channel)) {
+        if (HUIFU.equals(channel)) {
             byte[] file = huifuFile(day);
             return BillFiles.parse(channel, keys.value("appId"), day, file);
         } else {
@@ -91,7 +93,7 @@ final class ProviderBills {
     }
 
     BigDecimal withdrawableBalance() throws Exception {
-        if ("HUIFU".equals(channel)) return huifuBasicBalance();
+        if (HUIFU.equals(channel)) return huifuBasicBalance();
         if ("WECHAT".equals(channel)) {
             JsonNode cents = wxJson("/v3/merchant/fund/balance/BASIC").path("available_amount");
             if (!cents.isIntegralNumber() || !cents.canConvertToLong() || cents.longValue() < 0) throw new BillHttp.Failure("余额字段异常");
@@ -100,6 +102,11 @@ final class ProviderBills {
         throw new BillHttp.Failure("支付宝余额账户未提供已确认的可提现金额");
     }
 
+    int supplementFees(List<ReceiptEntryDto> entries) throws BillHttp.Failure {
+        if (!HUIFU.equals(channel) || entries.isEmpty()) return 0;
+        return new HuifuConfirmationFees(keys.value("appId"), keys.value(MERCHANT_KEY)).supplement(entries);
+    }
+
     private BigDecimal huifuBasicBalance() throws Exception {
         String appId = keys.value("appId");
         Map<String, Object> params = new HashMap<>();
@@ -108,7 +115,7 @@ final class ProviderBills {
         params.put("acct_type", "01");
         JsonNode balance;
         try {
-            balance = JSON.valueToTree(SettleAccount.balance(params, keys.value("merchantKey")));
+            balance = JSON.valueToTree(SettleAccount.balance(params, keys.value(MERCHANT_KEY)));
         } catch (BaseAdaPayException failure) {
             throw huifuSdkFailure("汇付基本户余额查询失败", failure);
         }
@@ -130,7 +137,7 @@ final class ProviderBills {
         try {
             Map<String, Object> params = new HashMap<>();
             params.put("bill_date", day.format(DateTimeFormatter.BASIC_ISO_DATE));
-            JsonNode ticket = JSON.valueToTree(Bill.download(params, keys.value("merchantKey")));
+            JsonNode ticket = JSON.valueToTree(Bill.download(params, keys.value(MERCHANT_KEY)));
             String status = ticket.path("status").asText();
             if (!"pending".equals(status) && !"succeeded".equals(status))
                 throw rejected(ticket, "error_code");

+ 4 - 0
mec-biz/src/main/java/com/ym/mec/biz/service/impl/receipt/gateway/ReceiptBillGateway.java

@@ -36,6 +36,10 @@ public class ReceiptBillGateway {
                     bill.getEntries().addAll(provider.entries(day, now()));
                     bill.setStatus("READY");
                     bill.setMessage(bill.getEntries().isEmpty() ? "该日无成功收款,无需重试" : "日账单已获取");
+                    int unavailable = provider.supplementFees(bill.getEntries());
+                    if (unavailable > 0) {
+                        bill.setMessage(bill.getMessage() + ";" + unavailable + " 笔延时分账手续费未核实,请重新取账核对");
+                    }
                 } catch (ProviderBills.NotReady pending) {
                     bill.setStatus("NOT_READY");
                     bill.setMessage(pending.getMessage());

+ 108 - 5
mec-biz/src/test/java/com/ym/mec/biz/service/impl/receipt/gateway/ReceiptBillGatewayTest.java

@@ -1,6 +1,8 @@
 package com.ym.mec.biz.service.impl.receipt.gateway;
 
 import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
 import com.github.binarywang.wxpay.service.WxPayService;
 import com.github.binarywang.wxpay.v3.auth.Verifier;
 import com.huifu.adapay.Adapay;
@@ -47,6 +49,15 @@ public class ReceiptBillGatewayTest {
     private static final String ALI_CSV = "#商户ID:" + PID + "\n支付宝交易号,商户订单号,业务类型,商品名称,完成时间,订单金额(元)\nali,order,交易,\"课程,一期\"," + DATE + ",12.34\nrefund,order,退款,课程," + DATE + ",-2.00\n#业务明细列表结束\n";
     private static final String ADA_CSV = "#支付流水记录\n交易时间,app_id,支付ID,商户订单号,交易类型,交易金额,手续费金额,货币种类,交易状态,第三方订单号,支付完成时间\n20261119150401,ada,charge,order,支付宝正扫,12.34,0.01,cny,S,,\n20261119150401,other,foreign,other,支付宝正扫,9.00,0.01,cny,S,,\n20261119150401,ada,failed,other,支付宝正扫,9.00,0.01,cny,F,,\n#合计:3笔,共30.34元\n";
     private static final String WX_MERCHANT = "10001";
+    private static final String CONFIRM_LIST_PATH = "/v1/payments/confirm/list";
+    private static final String DELAYED_PAYMENT = "delayed-payment";
+    private static final String CONFIRM_WRONG_PAYMENT = "confirmWrongPayment";
+    private static final String CONFIRM_CONFLICTING_DUPLICATE = "confirmConflictingDuplicate";
+    private static final String AUTHORIZATION_HEADER = "Authorization";
+    private static final String APP_ID_FIELD = "app_id";
+    private static final String SIGNATURE_FIELD = "signature";
+    private static final String HUIFU_SIGN_ALGORITHM = "SHA1withRSA";
+    private static final String SUCCEEDED = "succeeded";
 
     @Test public void billFeesComeFromSuccessfulMerchantRows() throws Exception {
         ReceiptChargesDto ada = BillFiles.parse("HUIFU", "ada", DAY, zip("Charge.csv", ADA_CSV, UTF_8)).get(0).getCharges();
@@ -78,6 +89,7 @@ public class ReceiptBillGatewayTest {
     private static final String MERCHANT_KEY = "receipt-test-merchant";
     private MerConfig originalAccount;
     private int requests, downloads, tickets;
+    private int confirmationPages;
     private LocalDateTime clock = DAY.plusDays(1).atTime(10, 0);
 
     @BeforeClass public static void generateTestKeys() throws Exception {
@@ -100,6 +112,7 @@ public class ReceiptBillGatewayTest {
         huifuServer = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
         huifuServer.createContext("/", this::handleHuifu);
         huifuServer.createContext("/v1/settle_accounts/balance", this::handleBasicBalance);
+        huifuServer.createContext(CONFIRM_LIST_PATH, this::handleConfirmations);
         huifuServer.start();
         AdapayCore.apiBase = "http://127.0.0.1:" + huifuServer.getAddress().getPort();
         stored.setTenantId(101);
@@ -183,7 +196,11 @@ public class ReceiptBillGatewayTest {
                 assertEquals("https://file.cloudpnr.com/test?Signature=a%2Bb%3D", uri.toASCIIString());
                 return new BillHttp.Reply(200, zip("Charge_payment.csv", ADA_CSV, UTF_8));
             }
-            if (uri.getHost().equals("jarvisfile.oss-cn-shanghai.aliyuncs.com")) return new BillHttp.Reply(200, zip("Charge_payment.csv", ADA_CSV, UTF_8));
+            if (uri.getHost().equals("jarvisfile.oss-cn-shanghai.aliyuncs.com")) {
+                String csv = mode.startsWith("confirm") ? ADA_CSV.replace("charge,order,支付宝正扫,12.34,0.01",
+                        DELAYED_PAYMENT + ",order,支付宝正扫,680.00,0.00") : ADA_CSV;
+                return new BillHttp.Reply(200, zip("Charge_payment.csv", csv, UTF_8));
+            }
             assertEquals("billdownload.cloud.alipay.com", uri.getHost());
             return new BillHttp.Reply(200, zip((mode.equals("foreignName") ? OTHER : PID) + "_业务明细.csv", mode.equals("foreignHeader") ? ALI_CSV.replace(PID, OTHER) : ALI_CSV, Charset.forName("GBK")));
         }
@@ -210,15 +227,15 @@ public class ReceiptBillGatewayTest {
         try {
             requests++;
             assertEquals("GET", exchange.getRequestMethod());
-            assertEquals("offline-api", exchange.getRequestHeaders().getFirst("Authorization"));
+            assertEquals("offline-api", exchange.getRequestHeaders().getFirst(AUTHORIZATION_HEADER));
             List<String> query = Arrays.asList(exchange.getRequestURI().getQuery().split("&"));
             Collections.sort(query);
             assertEquals(Arrays.asList("acct_type=01", "app_id=ada", "member_id=0"), query);
             Map<String, Object> result = new HashMap<>();
             result.put("object", "account_balance");
-            result.put("status", "succeeded");
+            result.put("status", SUCCEEDED);
             result.put("prod_mode", true);
-            result.put("app_id", "foreignBalance".equals(mode) ? "other" : "ada");
+            result.put(APP_ID_FIELD, "foreignBalance".equals(mode) ? "other" : "ada");
             result.put("acct_balance", "90.00");
             result.put("avl_balance", "zeroBalance".equals(mode) ? "0.00" : "12.34");
             if ("missingBalance".equals(mode)) result.remove("avl_balance");
@@ -226,7 +243,7 @@ public class ReceiptBillGatewayTest {
             String data = JSON.writeValueAsString(result);
             Map<String, String> envelope = new HashMap<>();
             envelope.put("data", data);
-            envelope.put("signature", sign("SHA1withRSA", "badBalanceSignature".equals(mode) ? "changed" : data));
+            envelope.put(SIGNATURE_FIELD, sign(HUIFU_SIGN_ALGORITHM, "badBalanceSignature".equals(mode) ? "changed" : data));
             byte[] response = JSON.writeValueAsBytes(envelope);
             exchange.sendResponseHeaders(200, response.length);
             exchange.getResponseBody().write(response);
@@ -238,6 +255,56 @@ public class ReceiptBillGatewayTest {
         }
     }
 
+    private void handleConfirmations(HttpExchange exchange) throws IOException {
+        try {
+            int page = ++confirmationPages;
+            assertEquals("GET", exchange.getRequestMethod());
+            assertEquals(stored.getApiKey(), exchange.getRequestHeaders().getFirst(AUTHORIZATION_HEADER));
+            assertEquals(CONFIRM_LIST_PATH, exchange.getRequestURI().getPath());
+            List<String> query = Arrays.asList(exchange.getRequestURI().getQuery().split("&"));
+            Collections.sort(query);
+            assertEquals(Arrays.asList("app_id=" + stored.getAppId(), "page_index=" + page, "page_size=20", "payment_id=" + DELAYED_PAYMENT), query);
+
+            ObjectNode payload = JSON.createObjectNode();
+            payload.put("status", SUCCEEDED).put("object", "list").put("prod_mode", true)
+                    .put(APP_ID_FIELD, stored.getAppId()).put("payment_id", DELAYED_PAYMENT);
+            boolean hasMore = page == 1 && !"confirmEmpty".equals(mode);
+            payload.put("has_more", hasMore);
+            ArrayNode confirmations = payload.putArray("payment_confirms");
+            if (!"confirmEmpty".equals(mode)) {
+                ObjectNode confirmed = confirmation("confirm-1", "1.20", SUCCEEDED);
+                confirmations.add(confirmed);
+                if (hasMore) {
+                    confirmations.add(confirmation("pending-id", "0.50", "pending"));
+                    confirmations.add(confirmation("failed-id", "0.50", "failed"));
+                } else {
+                    ObjectNode another = confirmation("confirm-2", "0.70", SUCCEEDED);
+                    if (CONFIRM_WRONG_PAYMENT.equals(mode)) another.put("payment_id", "other-payment");
+                    if (CONFIRM_CONFLICTING_DUPLICATE.equals(mode)) confirmed.put("fee_amt", "9.99");
+                    confirmations.add(another);
+                }
+            }
+            String data = JSON.writeValueAsString(payload);
+            Map<String, String> envelope = new HashMap<>();
+            envelope.put("data", data);
+            envelope.put(SIGNATURE_FIELD, sign(HUIFU_SIGN_ALGORITHM, "confirmInvalidSignature".equals(mode) && !hasMore ? "invalid" : data));
+            byte[] response = JSON.writeValueAsBytes(envelope);
+            exchange.sendResponseHeaders(200, response.length);
+            exchange.getResponseBody().write(response);
+        } catch (Exception | AssertionError failure) {
+            handlerFailure = failure;
+            exchange.sendResponseHeaders(500, -1);
+        } finally {
+            exchange.close();
+        }
+    }
+
+    private ObjectNode confirmation(String id, String fee, String status) {
+        return JSON.createObjectNode().put("id", id).put(APP_ID_FIELD, stored.getAppId()).put("payment_id", DELAYED_PAYMENT)
+                .put("created_time", DAY.plusDays(1).atStartOfDay(ReceiptBillGateway.CHINA).toEpochSecond())
+                .put("status", status).put("fee_amt", fee);
+    }
+
     private void handleHuifu(HttpExchange exchange) throws IOException {
         int status = 200;
         byte[] response;
@@ -343,6 +410,7 @@ public class ReceiptBillGatewayTest {
         assertEquals("READY", fetch("101", "HUIFU", DAY).getStatus());
         org.mockito.Mockito.verify(payments, never()).getPaymentService("ADAPAY_101");
         assertEquals(1, tickets);
+        assertEquals(0, confirmationPages);
 
         stored.setApiKey("different-account");
         ReceiptBillDto rejected = fetch("101", "HUIFU", DAY);
@@ -351,6 +419,41 @@ public class ReceiptBillGatewayTest {
         assertEquals(1, tickets);
     }
 
+    @Test public void delayedHuifuFeeFollowsTheOriginalPaymentAcrossDatesAndPages() throws Exception {
+        mode = "confirmDelayed";
+        ReceiptBillDto bill = fetch("101", "HUIFU", DAY);
+        assertEquals(bill.getMessage(), "READY", bill.getStatus());
+        assertEquals(2, confirmationPages);
+        assertEquals(1, bill.getEntries().size());
+        assertEquals(new BigDecimal("680.00"), bill.getEntries().get(0).getAmount());
+        assertEquals(new BigDecimal("1.90"), bill.getEntries().get(0).getCharges().getFeeAmount());
+        ReceiptReconcileResultVo result = ReceiptLedger.compare("101", DAY, Collections.emptyList(), Collections.singletonList(bill));
+        ReceiptChannelVo summary = result.getChannels().get(0);
+        assertEquals(Integer.valueOf(1), summary.getThirdCount());
+        assertEquals(new BigDecimal("678.10"), summary.getCharges().getNetAmount());
+    }
+
+    @Test public void huifuZeroFeeRemainsWhenThereAreNoConfirmations() throws Exception {
+        mode = "confirmEmpty";
+        ReceiptBillDto bill = fetch("101", "HUIFU", DAY);
+        assertEquals(bill.getMessage(), "READY", bill.getStatus());
+        assertEquals(1, confirmationPages);
+        assertEquals(0, bill.getEntries().get(0).getCharges().getFeeAmount().signum());
+    }
+
+    @Test public void unresolvedHuifuFeesDoNotSuppressPaymentsOrDisplayFalseZero() throws Exception {
+        for (String scenario : Arrays.asList(CONFIRM_WRONG_PAYMENT, CONFIRM_CONFLICTING_DUPLICATE, "confirmInvalidSignature")) {
+            mode = scenario;
+            confirmationPages = 0;
+            ReceiptBillDto bill = fetch("101", "HUIFU", DAY);
+            assertEquals(bill.getMessage(), "READY", bill.getStatus());
+            assertEquals(2, confirmationPages);
+            assertEquals(1, bill.getEntries().size());
+            assertNull(bill.getEntries().get(0).getCharges());
+            assertTrue(bill.getMessage().contains("1 笔延时分账手续费未核实"));
+        }
+    }
+
     @Test public void huifuDoesNotFallBackToStartupKeysForMissingSdkAccount() throws Exception {
         stored.setMerKey("receipt-test-unregistered");
         assertTrue(fetch("101", "HUIFU", DAY).getMessage().contains("未注册该机构"));