Просмотр исходного кода

fix: 收款对账显示机构汇付基本户可用余额

yonge 1 неделя назад
Родитель
Сommit
ffc025715b

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

@@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.JsonNode;
 import com.fasterxml.jackson.databind.ObjectMapper;
 import com.huifu.adapay.core.exception.BaseAdaPayException;
 import com.huifu.adapay.model.Bill;
+import com.huifu.adapay.model.SettleAccount;
 import com.ym.mec.biz.dal.dto.ReceiptEntryDto;
 
 import java.math.BigDecimal;
@@ -90,12 +91,38 @@ final class ProviderBills {
     }
 
     BigDecimal withdrawableBalance() throws Exception {
+        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("余额字段异常");
             return BigDecimal.valueOf(cents.longValue(), 2);
         }
-        throw new BillHttp.Failure("HUIFU".equals(channel) ? "汇付可用余额未证实等于当前可提现金额" : "支付宝余额账户未提供已确认的可提现金额");
+        throw new BillHttp.Failure("支付宝余额账户未提供已确认的可提现金额");
+    }
+
+    private BigDecimal huifuBasicBalance() throws Exception {
+        String appId = keys.value("appId");
+        Map<String, Object> params = new HashMap<>();
+        params.put("app_id", appId);
+        params.put("member_id", "0");
+        params.put("acct_type", "01");
+        JsonNode balance;
+        try {
+            balance = JSON.valueToTree(SettleAccount.balance(params, keys.value("merchantKey")));
+        } catch (BaseAdaPayException failure) {
+            throw huifuSdkFailure("汇付基本户余额查询失败", failure);
+        }
+        if (!"succeeded".equals(balance.path("status").asText())) throw rejected(balance, "error_code");
+        if (!"true".equals(balance.path("prod_mode").asText()) || !"account_balance".equals(balance.path("object").asText()))
+            throw new BillHttp.Failure("汇付基本户余额响应类型或环境不符");
+        if (!appId.equals(balance.path("app_id").asText()) ||
+                (balance.has("member_id") && !"0".equals(balance.path("member_id").asText())) ||
+                (balance.has("acct_type") && !"01".equals(balance.path("acct_type").asText())))
+            throw new BillHttp.Failure("汇付余额响应与本机构商户基本户不符");
+        String available = text(balance, "avl_balance");
+        if (available.length() > 16 || !available.matches("[0-9]+(\\.[0-9]{1,2})?"))
+            throw new BillHttp.Failure("汇付基本户可用余额格式异常");
+        return new BigDecimal(available);
     }
 
     private byte[] huifuFile(LocalDate day) throws Exception {
@@ -113,15 +140,7 @@ final class ProviderBills {
         } catch (NotReady pending) {
             throw pending;
         } catch (BaseAdaPayException failure) {
-            String code = failure.getCode();
-            String reason = "SDK 调用失败";
-            String message = failure.getMessage();
-            if ("Response sign check error. Please check your pubkey.".equals(message)) reason = "汇付响应验签失败";
-            else if ("Sign error. Please check your privateKey.".equals(message)) reason = "机构商户请求签名失败";
-            else if ("Request no response. Please check your network.".equals(message)) reason = "汇付未返回响应内容";
-            else if (message != null && message.startsWith("Parse response error.")) reason = "汇付响应格式异常";
-            throw new BillHttp.Failure("汇付申请账单地址失败:" + reason +
-                    (code != null && code.matches("[a-z_]{1,50}") ? "(" + code + ")" : ""));
+            throw huifuSdkFailure("汇付申请账单地址失败", failure);
         } catch (Exception failure) {
             throw new BillHttp.Failure("汇付申请账单地址失败:" + BillHttp.reason(failure));
         }
@@ -138,6 +157,18 @@ final class ProviderBills {
         }
     }
 
+    private static BillHttp.Failure huifuSdkFailure(String operation, BaseAdaPayException failure) {
+        String code = failure.getCode();
+        String reason = "SDK 调用失败";
+        String message = failure.getMessage();
+        if ("Response sign check error. Please check your pubkey.".equals(message)) reason = "汇付响应验签失败";
+        else if ("Sign error. Please check your privateKey.".equals(message)) reason = "机构商户请求签名失败";
+        else if ("Request no response. Please check your network.".equals(message)) reason = "汇付未返回响应内容";
+        else if (message != null && message.startsWith("Parse response error.")) reason = "汇付响应格式异常";
+        return new BillHttp.Failure(operation + ":" + reason +
+                (code != null && code.matches("[a-z_]{1,50}") ? "(" + code + ")" : ""));
+    }
+
     private static byte[] huifuBody(BillHttp.Reply reply) throws BillHttp.Failure {
         if (reply.status == 200) return reply.data;
         String code = "";

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

@@ -84,6 +84,7 @@ public class ReceiptBillGatewayTest {
         originalApiBase = AdapayCore.apiBase;
         huifuServer = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
         huifuServer.createContext("/", this::handleHuifu);
+        huifuServer.createContext("/v1/settle_accounts/balance", this::handleBasicBalance);
         huifuServer.start();
         AdapayCore.apiBase = "http://127.0.0.1:" + huifuServer.getAddress().getPort();
         stored.setTenantId(101);
@@ -190,6 +191,38 @@ public class ReceiptBillGatewayTest {
         return new BillHttp.Reply(200, envelope.getBytes(UTF_8));
     }
 
+    private void handleBasicBalance(HttpExchange exchange) throws IOException {
+        try {
+            requests++;
+            assertEquals("GET", exchange.getRequestMethod());
+            assertEquals("offline-api", exchange.getRequestHeaders().getFirst("Authorization"));
+            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("prod_mode", true);
+            result.put("app_id", "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");
+            if ("invalidBalance".equals(mode)) result.put("avl_balance", "12.345");
+            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));
+            byte[] response = JSON.writeValueAsBytes(envelope);
+            exchange.sendResponseHeaders(200, response.length);
+            exchange.getResponseBody().write(response);
+        } catch (Throwable failure) {
+            handlerFailure = failure;
+            exchange.sendResponseHeaders(500, -1);
+        } finally {
+            exchange.close();
+        }
+    }
+
     private void handleHuifu(HttpExchange exchange) throws IOException {
         int status = 200;
         byte[] response;
@@ -269,10 +302,26 @@ public class ReceiptBillGatewayTest {
             assertEquals(bill.getMessage(), "READY", bill.getStatus()); assertEquals(1, bill.getEntries().size());
             assertEquals("order", bill.getEntries().get(0).getOrderNo()); assertEquals(channel, bill.getEntries().get(0).getChannel());
             assertEquals(DATE, bill.getEntries().get(0).getTime()); assertEquals(new BigDecimal("12.34"), bill.getEntries().get(0).getAmount());
-            if ("WECHAT".equals(channel)) { assertEquals(new BigDecimal("12.34"), bill.getAvailableBalance()); assertNotNull(bill.getBalanceTime()); }
+            if (!"ALIPAY".equals(channel)) { assertEquals(new BigDecimal("12.34"), bill.getAvailableBalance()); assertNotNull(bill.getBalanceTime()); }
             else { assertNull(bill.getAvailableBalance()); assertNull(bill.getBalanceTime()); assertTrue(bill.getMessage().contains("可提现")); }
         }
-        assertEquals(3, downloads); assertEquals(7, requests);
+        assertEquals(3, downloads); assertEquals(8, requests);
+    }
+
+    @Test public void huifuStoresZeroSnapshotAndKeepsReadyBillWhenBalanceIsUnavailable() throws Exception {
+        mode = "zeroBalance";
+        ReceiptBillDto bill = fetch("101", "HUIFU", DAY);
+        assertEquals(new BigDecimal("0.00"), bill.getAvailableBalance());
+        assertNotNull(bill.getBalanceTime());
+        for (String scenario : Arrays.asList("foreignBalance", "badBalanceSignature", "missingBalance", "invalidBalance")) {
+            mode = scenario;
+            bill = fetch("101", "HUIFU", DAY);
+            assertEquals(scenario, "READY", bill.getStatus());
+            assertEquals(1, bill.getEntries().size());
+            assertNull(scenario, bill.getAvailableBalance());
+            assertNull(scenario, bill.getBalanceTime());
+            assertTrue(bill.getMessage().contains("实时可提现余额不可用"));
+        }
     }
 
     @Test public void huifuUsesFinanceExportMerchantWithoutPaymentPlugin() throws Exception {
@@ -310,6 +359,7 @@ public class ReceiptBillGatewayTest {
         bill = fetch("101", "HUIFU", DAY);
         assertEquals("ERROR", bill.getStatus());
         assertTrue(bill.getMessage(), bill.getMessage().contains("下载账单文件失败:HTTP 401,下载地址已过期(AccessDenied)"));
+        assertEquals(new BigDecimal("12.34"), bill.getAvailableBalance());
         assertFalse(bill.getMessage().contains("private-file"));
         assertEquals(4, tickets);
         assertEquals(1, downloads);
@@ -322,7 +372,7 @@ public class ReceiptBillGatewayTest {
         assertEquals(1, downloads);
         assertEquals(1, bill.getEntries().size());
         assertEquals("order", bill.getEntries().get(0).getOrderNo());
-        assertNull(bill.getAvailableBalance());
+        assertEquals(new BigDecimal("12.34"), bill.getAvailableBalance());
     }
 
     @Test public void huifuIdentifiesUnconfirmedDownloadDomainWithoutExposingSignedUrl() throws Exception {