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

fix: 收款对账区分汇付取账失败阶段和机构直连账户状态

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

+ 11 - 2
mec-biz/src/main/java/com/ym/mec/biz/service/impl/receipt/gateway/BillHttp.java

@@ -61,8 +61,17 @@ class BillHttp implements Closeable {
         headers.forEach(request::setHeader);
         try (CloseableHttpResponse response = client.execute(request)) {
             int status = response.getStatusLine().getStatusCode();
-            if (response.getEntity() == null) throw new Failure("渠道未返回数据");
-            Reply reply = new Reply(status, read(response.getEntity().getContent(), status == 200 ? limit : API_LIMIT));
+            if (response.getEntity() == null && status == 200) throw new Failure("渠道未返回数据");
+            byte[] data = new byte[0];
+            if (response.getEntity() != null) {
+                if (status == 200) data = read(response.getEntity().getContent(), limit);
+                else {
+                    // Even if the error body is oversized or truncated, retain the HTTP status.
+                    try { data = read(response.getEntity().getContent(), API_LIMIT); }
+                    catch (IOException ignored) { }
+                }
+            }
+            Reply reply = new Reply(status, data);
             for (Header header : response.getAllHeaders()) reply.headers.put(header.getName(), header.getValue());
             return reply;
         }

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

@@ -4,6 +4,8 @@ import com.fasterxml.jackson.core.JsonParser;
 import com.fasterxml.jackson.core.JsonToken;
 import com.fasterxml.jackson.databind.JsonNode;
 import com.fasterxml.jackson.databind.ObjectMapper;
+import com.huifu.adapay.APIUrlEnum;
+import com.huifu.adapay.core.AdapayCore;
 import com.ym.mec.biz.dal.dto.ReceiptEntryDto;
 
 import java.math.BigDecimal;
@@ -21,7 +23,7 @@ final class ProviderBills {
         NotReady(String message) { super(message); }
     }
     private static final ObjectMapper JSON = new ObjectMapper().enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION);
-    private static final String WX = "api.mch.weixin.qq.com", ADA = "https://api.adapay.tech/v1/";
+    private static final String WX = "api.mch.weixin.qq.com";
     private final String channel;
     private final BillCredentials keys;
     private final BillHttp http;
@@ -59,9 +61,8 @@ final class ProviderBills {
         }
         String owner;
         if ("HUIFU".equals(channel)) {
-            JsonNode ticket = adaBill(Collections.singletonMap("bill_date", day.format(DateTimeFormatter.BASIC_ISO_DATE)));
-            download = BillHttp.download(text(ticket, "bill_download_url"), "jarvisfile.oss-cn-shanghai.aliyuncs.com");
-            owner = keys.value("appId");
+            byte[] file = huifuFile(day);
+            return BillFiles.parse(channel, keys.value("appId"), day, file);
         } else {
             if (day.isBefore(now.toLocalDate().minusYears(6))) throw new BillHttp.Failure("超出支付宝近六年账单窗口");
             Map<String, String> biz = new TreeMap<>();
@@ -97,19 +98,75 @@ final class ProviderBills {
         throw new BillHttp.Failure("HUIFU".equals(channel) ? "汇付可用余额未证实等于当前可提现金额" : "支付宝余额账户未提供已确认的可提现金额");
     }
 
+    private byte[] huifuFile(LocalDate day) throws Exception {
+        URI download;
+        try {
+            JsonNode ticket = adaBill(Collections.singletonMap("bill_date", day.format(DateTimeFormatter.BASIC_ISO_DATE)));
+            download = BillHttp.download(text(ticket, "bill_download_url"), "jarvisfile.oss-cn-shanghai.aliyuncs.com");
+        } catch (NotReady pending) {
+            throw pending;
+        } catch (Exception failure) {
+            throw new BillHttp.Failure("汇付申请账单地址失败:" + BillHttp.reason(failure));
+        }
+        try {
+            return huifuBody(http.send(download, Collections.emptyMap(), null, BillHttp.FILE_LIMIT));
+        } catch (Exception failure) {
+            throw new BillHttp.Failure("汇付下载账单文件失败:" + BillHttp.reason(failure));
+        }
+    }
+
+    private static byte[] huifuBody(BillHttp.Reply reply) throws BillHttp.Failure {
+        if (reply.status == 200) return reply.data;
+        String code = "";
+        String body = new String(reply.data, StandardCharsets.UTF_8).trim();
+        String message = body;
+        if (body.startsWith("{")) {
+            try {
+                JsonNode error = JSON.readTree(body);
+                JsonNode data = error.path("data");
+                if (data.isTextual()) data = JSON.readTree(data.textValue());
+                if (!error.hasNonNull("error_code") && data != null && data.isObject()) error = data;
+                code = error.path("error_code").asText(error.path("code").asText());
+                message = error.path("error_msg").asText(error.path("message").asText());
+            } catch (java.io.IOException ignored) {
+                // Keep the HTTP status when an intermediary returns an invalid response.
+            }
+        } else if (body.startsWith("<")) {
+            java.util.regex.Matcher match = java.util.regex.Pattern.compile("<Code>([A-Za-z]{1,48})</Code>").matcher(body);
+            if (match.find()) code = match.group(1);
+        }
+        String detail;
+        switch (code) {
+            case "security_exception": case "SignatureDoesNotMatch": detail = "签名校验失败"; break;
+            case "invalid_api_key": case "InvalidAccessKeyId": detail = "访问密钥无效"; break;
+            case "ExpiredToken": case "RequestExpired": case "token_invalided": detail = "访问凭据已过期"; break;
+            case "AccessDenied": detail = body.contains("<Message>Request has expired</Message>") ? "下载地址已过期" : "访问被拒绝"; break;
+            case "RequestTimeTooSkewed": detail = "请求时间偏差过大"; break;
+            case "config_exception": detail = "渠道配置错误"; break;
+            case "mer_not_register": detail = "商户未入驻"; break;
+            case "request_parameter_error": case "request_param_error": detail = "账单请求参数错误"; break;
+            default:
+                if ("Invalid API key".equalsIgnoreCase(message)) detail = "API Key 无效";
+                else if ("Invalid signature".equalsIgnoreCase(message)) detail = "签名校验失败";
+                else detail = reply.status == 401 ? "认证未通过,渠道未提供可识别的具体原因" : "渠道未提供可识别的具体原因";
+                code = "";
+        }
+        throw new BillHttp.Failure("HTTP " + reply.status + "," + detail + (code.isEmpty() ? "" : "(" + code + ")"));
+    }
+
     private JsonNode adaBill(Map<String, String> params) throws Exception {
-        String path = "bill/download";
+        String path = APIUrlEnum.BILL_DOWNLOAD_V1.getCode();
         String body = JSON.writeValueAsString(params);
-        String url = ADA + path;
+        String url = AdapayCore.apiBase + path;
         Map<String, String> headers = new HashMap<>();
         headers.put("Authorization", keys.value("apiKey"));
         headers.put("Signature", keys.sign("SHA1withRSA", url + body));
         headers.put("Content-Type", "application/json;charset=UTF-8");
-        headers.put("sdk_version", "Java_v1.0.0");
+        headers.put("sdk_version", AdapayCore.sdkVersion);
         headers.put("api_name", path);
         headers.put("seq_id", UUID.randomUUID().toString());
         BillHttp.Reply reply = http.send(URI.create(url), headers, body, BillHttp.API_LIMIT);
-        JsonNode envelope = JSON.readTree(reply.ok());
+        JsonNode envelope = JSON.readTree(huifuBody(reply));
         String data = text(envelope, "data");
         keys.verify(null, "SHA1withRSA", data.getBytes(StandardCharsets.UTF_8), text(envelope, "signature"));
         JsonNode result = JSON.readTree(data);

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

@@ -43,9 +43,10 @@ class ReceiptPaymentAccounts {
         try {
             service = payments.getPaymentService(route);
         } catch (com.microsvc.toolkit.middleware.payment.common.exception.PaymentException missing) {
-            throw unknown();
+            throw missingRoute(vendor, route);
         }
-        if (service == null || !route.equals(service.venderName())) throw unknown();
+        if (service == null) throw missingRoute(vendor, route);
+        if (!route.equals(service.venderName())) throw unknown();
         BasePaymentConfig account = service.getPaymentConfig();
         if ("ADAPAY".equals(vendor) && account instanceof AdapayPayConfig) {
             String app = required(account.getAppId(), "汇付应用 ID");
@@ -110,6 +111,15 @@ class ReceiptPaymentAccounts {
         }
     }
 
+    private BillHttp.Failure missingRoute(String vendor, String route) {
+        if ("ADAPAY".equals(vendor)) return unknown();
+        boolean configuredHere = "WXPAY".equals(vendor) ? configured.getWxPayConfigs().containsKey(route)
+                : configured.getAliPayConfigs().containsKey(route);
+        String name = "WXPAY".equals(vendor) ? "微信" : "支付宝";
+        String cause = configuredHere ? "有直连账户配置,但支付服务未注册该实例" : "未找到该机构的直连支付实例";
+        return new BillHttp.Failure(name + cause + "(" + route + "),当日交易未确认");
+    }
+
     private static BillHttp.Failure unknown() { return new BillHttp.Failure("该机构的渠道账户未确认,不能判定为零笔"); }
     private static BillHttp.Failure duplicate() { return new BillHttp.Failure("同一渠道账户被多个机构绑定,已阻止查询"); }
     private static String required(String value, String field) throws BillHttp.Failure {

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

@@ -131,6 +131,8 @@ public class ReceiptBillGatewayTest {
         }
         if (limit == BillHttp.FILE_LIMIT) {
             downloads++;
+            if (mode.equals("file401")) return new BillHttp.Reply(401,
+                    "<Error><Code>AccessDenied</Code><Message>Request has expired</Message><Resource>private-file</Resource></Error>".getBytes(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));
             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")));
@@ -138,8 +140,13 @@ public class ReceiptBillGatewayTest {
         if (uri.getHost().equals("api.adapay.tech")) {
             tickets++; assertEquals("20261119", JSON.readTree(body).path("bill_date").asText());
             assertEquals("/v1/bill/download", uri.getPath());
+            assertEquals(uri.getPath(), headers.get("api_name"));
             assertEquals("offline-api", headers.get("Authorization"));
             verify("SHA1withRSA", "https://api.adapay.tech" + uri.getPath() + body, headers.get("Signature"));
+            if (mode.equals("ticket401")) return new BillHttp.Reply(401, JSON.writeValueAsBytes(Collections.singletonMap("data",
+                    "{\"error_code\":\"security_exception\",\"error_msg\":\"private-file\"}")));
+            if (mode.equals("empty401")) return new BillHttp.Reply(401, new byte[0]);
+            if (mode.equals("plain401")) return new BillHttp.Reply(401, "Invalid API key".getBytes(UTF_8));
             String result = "{\"status\":\"succeeded\",\"prod_mode\":true,\"bill_download_url\":\"https://jarvisfile.oss-cn-shanghai.aliyuncs.com/test\"}";
             Map<String,String> envelope = new HashMap<>();
             envelope.put("data", result);
@@ -205,6 +212,33 @@ public class ReceiptBillGatewayTest {
         assertEquals(3, downloads); assertEquals(7, requests);
     }
 
+    @Test public void huifuReportsActualHttpStageAndSafeReason() throws Exception {
+        mode = "ticket401";
+        ReceiptBillDto bill = fetch("101", "HUIFU", DAY);
+        assertEquals("ERROR", bill.getStatus());
+        assertTrue(bill.getMessage(), bill.getMessage().contains("申请账单地址失败:HTTP 401,签名校验失败(security_exception)"));
+        assertFalse(bill.getMessage().contains("private-file"));
+        mode = "empty401";
+        assertTrue(fetch("101", "HUIFU", DAY).getMessage().contains("申请账单地址失败:HTTP 401,认证未通过"));
+        mode = "plain401";
+        assertTrue(fetch("101", "HUIFU", DAY).getMessage().contains("申请账单地址失败:HTTP 401,API Key 无效"));
+        assertEquals(0, downloads);
+        mode = "file401";
+        bill = fetch("101", "HUIFU", DAY);
+        assertEquals("ERROR", bill.getStatus());
+        assertTrue(bill.getMessage(), bill.getMessage().contains("下载账单文件失败:HTTP 401,下载地址已过期(AccessDenied)"));
+        assertFalse(bill.getMessage().contains("private-file"));
+        assertEquals(4, tickets);
+        assertEquals(1, downloads);
+    }
+
+    @Test public void missingRegistrationIsDistinctFromMissingDirectAccount() throws Exception {
+        when(payments.getPaymentService("ALIPAY_101")).thenThrow(new com.microsvc.toolkit.middleware.payment.common.exception.PaymentException("missing"));
+        assertTrue(fetch("101", "ALIPAY", DAY).getMessage().contains("有直连账户配置,但支付服务未注册该实例(ALIPAY_101)"));
+        assertTrue(fetch("102", "WECHAT", DAY).getMessage().contains("未找到该机构的直连支付实例(WXPAY_102)"));
+        assertEquals(0, requests);
+    }
+
     @Test public void repeatedBindingsBlockRequests() throws Exception {
         shared.getWxPayConfigs().put("WXPAY_102", wx);
         assertTrue(fetch("101", "WECHAT", DAY).getMessage().contains("多个机构"));