Преглед изворни кода

fix: 汇付收款对账按机构商户调用官方账单接口

yonge пре 1 недеља
родитељ
комит
8f18d19139

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

@@ -21,6 +21,13 @@ final class BillCredentials {
         this.verifier = verifier;
     }
 
+    static BillCredentials huifu(String appId, String merchantKey) {
+        BillCredentials account = new BillCredentials(null, null);
+        account.fields.put("appId", appId);
+        account.fields.put("merchantKey", merchantKey);
+        return account;
+    }
+
     static ResponseVerifier rsa(PublicKey key) {
         return (serial, algorithm, message, encoded) -> {
             Signature signature = Signature.getInstance(algorithm);

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

@@ -4,8 +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.huifu.adapay.core.exception.BaseAdaPayException;
+import com.huifu.adapay.model.Bill;
 import com.ym.mec.biz.dal.dto.ReceiptEntryDto;
 
 import java.math.BigDecimal;
@@ -37,7 +37,7 @@ final class ProviderBills {
             keys.value("merchantSerial");
         } else {
             keys.value("appId");
-            if ("HUIFU".equals(channel)) keys.value("apiKey");
+            if ("HUIFU".equals(channel)) keys.value("merchantKey");
             else keys.value("userId");
         }
     }
@@ -101,10 +101,27 @@ final class ProviderBills {
     private byte[] huifuFile(LocalDate day) throws Exception {
         URI download;
         try {
-            JsonNode ticket = adaBill(Collections.singletonMap("bill_date", day.format(DateTimeFormatter.BASIC_ISO_DATE)));
+            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")));
+            String status = ticket.path("status").asText();
+            if (!"pending".equals(status) && !"succeeded".equals(status))
+                throw rejected(ticket, "error_code");
+            if (!"true".equals(ticket.path("prod_mode").asText())) throw new BillHttp.Failure("非生产账务响应");
+            if ("pending".equals(status)) throw new NotReady("汇付仍在处理请求");
             download = BillHttp.download(text(ticket, "bill_download_url"), "jarvisfile.oss-cn-shanghai.aliyuncs.com");
         } 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 + ")" : ""));
         } catch (Exception failure) {
             throw new BillHttp.Failure("汇付申请账单地址失败:" + BillHttp.reason(failure));
         }
@@ -154,28 +171,6 @@ final class ProviderBills {
         throw new BillHttp.Failure("HTTP " + reply.status + "," + detail + (code.isEmpty() ? "" : "(" + code + ")"));
     }
 
-    private JsonNode adaBill(Map<String, String> params) throws Exception {
-        String path = APIUrlEnum.BILL_DOWNLOAD_V1.getCode();
-        String body = JSON.writeValueAsString(params);
-        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", 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(huifuBody(reply));
-        String data = text(envelope, "data");
-        keys.verify(null, "SHA1withRSA", data.getBytes(StandardCharsets.UTF_8), text(envelope, "signature"));
-        JsonNode result = JSON.readTree(data);
-        if (!"true".equals(result.path("prod_mode").asText())) throw new BillHttp.Failure("非生产账务响应");
-        if ("pending".equals(result.path("status").asText())) throw new NotReady("汇付仍在处理请求");
-        if (!"succeeded".equals(result.path("status").asText())) throw rejected(result, "error_code");
-        return result;
-    }
-
     private JsonNode ali(String method, Map<String, String> biz) throws Exception {
         Map<String, String> fields = new TreeMap<>();
         fields.put("app_id", keys.value("appId"));

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

@@ -3,12 +3,12 @@ package com.ym.mec.biz.service.impl.receipt.gateway;
 import com.github.binarywang.wxpay.config.WxPayConfig;
 import com.github.binarywang.wxpay.v3.auth.Verifier;
 import com.huifu.adapay.Adapay;
-import com.huifu.adapay.core.AdapayCore;
 import com.huifu.adapay.model.MerConfig;
 import com.microsvc.toolkit.middleware.payment.common.api.*;
 import com.microsvc.toolkit.middleware.payment.properties.PayConfigProperties;
 import com.microsvc.toolkit.middleware.payment.properties.PayConfigProperties.*;
 import com.microsvc.toolkit.middleware.payment.wxpay.WxPayBaseService;
+import com.ym.mec.biz.dal.enums.PaymentChannelEnum;
 import com.ym.mec.biz.service.HfMerchantConfigService;
 import com.ym.mec.thirdparty.adapay.entity.HfMerchantConfig;
 import org.springframework.boot.context.properties.bind.Bindable;
@@ -40,7 +40,8 @@ class ReceiptPaymentAccounts {
     }
 
     BillCredentials resolve(String tenant, String channel) throws Exception {
-        String vendor = "HUIFU".equals(channel) ? "ADAPAY" : "WECHAT".equals(channel) ? "WXPAY" : "ALIPAY";
+        if ("HUIFU".equals(channel)) return huifuCredentials(tenant);
+        String vendor = "WECHAT".equals(channel) ? "WXPAY" : "ALIPAY";
         String route = vendor + "_" + tenant;
         BasePaymentService service;
         try {
@@ -51,16 +52,6 @@ class ReceiptPaymentAccounts {
         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");
-            checkOthers(route, vendor, app, configured.getAdapayPayConfigs(), BasePaymentConfig::getAppId);
-            for (Map.Entry<String, Set<String>> item : huifu.adapayAccountOwners().entrySet()) {
-                if (route.equals(item.getKey())) {
-                    if (!item.getValue().equals(Collections.singleton(app))) throw unknown();
-                } else if (item.getValue().contains(app)) throw duplicate();
-            }
-            return huifuCredentials(tenant, route, app, (AdapayPayConfig) account);
-        }
         if ("ALIPAY".equals(vendor) && account instanceof AliPayConfig) {
             AliPayConfig ali = (AliPayConfig)account;
             String app = required(ali.getAppId(), "支付宝应用 ID");
@@ -101,25 +92,32 @@ class ReceiptPaymentAccounts {
         throw unknown();
     }
 
-    private BillCredentials huifuCredentials(String tenant, String route, String app, AdapayPayConfig account) throws Exception {
-        String merchantKey = Optional.ofNullable(account.getMerchantKey()).orElse(route);
+    private BillCredentials huifuCredentials(String tenant) throws BillHttp.Failure {
+        int tenantId;
+        try {
+            tenantId = Integer.parseInt(tenant);
+        } catch (NumberFormatException invalidTenant) {
+            throw unknown();
+        }
+        String vendor = PaymentChannelEnum.ADAPAY.getCode();
+        HfMerchantConfig stored = huifu.queryByTenantId(tenantId, vendor);
+        if (stored == null || !tenant.equals(String.valueOf(stored.getTenantId()))) throw unknown();
+        String app = required(stored.getAppId(), "汇付应用 ID");
+        String merchantKey = required(stored.getMerKey(), "汇付商户标识");
+        String route = vendor + "_" + tenant;
+        checkOthers(route, vendor, app, configured.getAdapayPayConfigs(), BasePaymentConfig::getAppId);
+        for (Map.Entry<String, Set<String>> item : huifu.adapayAccountOwners().entrySet()) {
+            if (route.equals(item.getKey())) {
+                if (!item.getValue().equals(Collections.singleton(app))) throw unknown();
+            } else if (item.getValue().contains(app)) throw duplicate();
+        }
         MerConfig current = Adapay.getConfig(merchantKey);
         if (current == null) throw new BillHttp.Failure("原支付 SDK 未注册该机构的汇付商户");
         if (!Adapay.prodMode) throw new BillHttp.Failure("原支付 SDK 当前为模拟模式,无法核对实际收款");
-        String apiKey = required(current.getApiKey(), "汇付 API Key");
-        String signingKey = required(current.getRSAPrivateKey(), "汇付签名私钥");
-        // 商户配置更新会替换 SDK 中的凭据,插件本身仍保留启动时的配置。
-        if (!apiKey.equals(account.getMerchantId()) || !signingKey.equals(account.getKeyPrivate())) {
-            HfMerchantConfig stored = huifu.queryByTenantId(Integer.valueOf(tenant), "ADAPAY");
-            if (stored == null || !tenant.equals(String.valueOf(stored.getTenantId()))
-                    || !app.equals(stored.getAppId()) || !merchantKey.equals(Optional.ofNullable(stored.getMerKey()).orElse(route))
-                    || !apiKey.equals(stored.getApiKey()) || !signingKey.equals(stored.getRsaPrivateKey()))
-                throw new BillHttp.Failure("汇付 SDK 的当前签名账户与本机构商户记录不一致,已停止取账");
-        }
-        BillCredentials keys = rsaKeys(signingKey, AdapayCore.PUBLIC_KEY);
-        keys.fields.put("appId", app);
-        keys.fields.put("apiKey", apiKey);
-        return keys;
+        if (!required(stored.getApiKey(), "汇付 API Key").equals(current.getApiKey())
+                || !required(stored.getRsaPrivateKey(), "汇付签名私钥").equals(current.getRSAPrivateKey()))
+            throw new BillHttp.Failure("汇付 SDK 的当前签名账户与本机构商户记录不一致,已停止取账");
+        return BillCredentials.huifu(app, merchantKey);
     }
 
     private static <T> void checkOthers(String route, String vendor, String owner, Map<String,T> accounts, Function<T,String> identity) throws BillHttp.Failure {
@@ -133,7 +131,6 @@ 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) ? "微信" : "支付宝";

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

@@ -5,7 +5,8 @@ import com.github.binarywang.wxpay.service.WxPayService;
 import com.github.binarywang.wxpay.v3.auth.Verifier;
 import com.huifu.adapay.Adapay;
 import com.huifu.adapay.core.AdapayCore;
-import com.huifu.adapay.core.util.AdapaySign;
+import com.sun.net.httpserver.HttpExchange;
+import com.sun.net.httpserver.HttpServer;
 import com.huifu.adapay.model.MerConfig;
 import com.microsvc.toolkit.middleware.payment.common.api.*;
 import com.microsvc.toolkit.middleware.payment.impl.WxPaymentServicePlugin;
@@ -52,7 +53,10 @@ public class ReceiptBillGatewayTest {
     private final HfMerchantConfigService huifu = mock(HfMerchantConfigService.class);
     private final StandardEnvironment environment = new StandardEnvironment();
     private final Map<String,Object> supplements = new HashMap<>();
-    private final AdapayPayConfig ada = new AdapayPayConfig();
+    private final HfMerchantConfig stored = new HfMerchantConfig();
+    private HttpServer huifuServer;
+    private String originalApiBase;
+    private volatile Throwable handlerFailure;
     private final AliPayConfig ali = new AliPayConfig();
     private final PayConfigProperties.WxPayConfig wx = new PayConfigProperties.WxPayConfig();
     private String mode = "ok", originalPlatformKey;
@@ -77,16 +81,24 @@ public class ReceiptBillGatewayTest {
         String key = Base64.getEncoder().encodeToString(merchant.getPrivate().getEncoded());
         String pub = Base64.getEncoder().encodeToString(platform.getPublic().getEncoded());
         originalPlatformKey = AdapayCore.PUBLIC_KEY; AdapayCore.PUBLIC_KEY = pub;
-        ada.setKeyPrivate(key); ada.setMerchantId("offline-api"); ada.setAppId("ada");
-        ada.setMerchantKey(MERCHANT_KEY);
+        originalApiBase = AdapayCore.apiBase;
+        huifuServer = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+        huifuServer.createContext("/", this::handleHuifu);
+        huifuServer.start();
+        AdapayCore.apiBase = "http://127.0.0.1:" + huifuServer.getAddress().getPort();
+        stored.setTenantId(101);
+        stored.setMerKey(MERCHANT_KEY);
+        stored.setAppId("ada");
+        stored.setApiKey("offline-api");
+        stored.setRsaPrivateKey(key);
+        when(huifu.queryByTenantId(101, "ADAPAY")).thenReturn(stored);
         originalAccount = Adapay.getConfig(MERCHANT_KEY);
         MerConfig runtimeAccount = new MerConfig();
-        runtimeAccount.setApiKey(ada.getMerchantId());
+        runtimeAccount.setApiKey(stored.getApiKey());
         runtimeAccount.setRSAPrivateKey(key);
         Adapay.addMerConfig(runtimeAccount, MERCHANT_KEY);
         ali.setPrivateKey(key); ali.setPublicKey(pub); ali.setAppId("ali-app"); ali.setEnable(false);
         wx.setMerchantId("10001"); wx.setEnable(false);
-        register("ADAPAY_101", ada, mock(BasePaymentService.class));
         register("ALIPAY_101", ali, mock(BasePaymentService.class));
         WxPaymentServicePlugin plugin = mock(WxPaymentServicePlugin.class);
         register("WXPAY_101", wx, plugin);
@@ -108,8 +120,11 @@ public class ReceiptBillGatewayTest {
     }
 
     @After public void restoreAccounts() throws Exception {
+        if (huifuServer != null) huifuServer.stop(0);
+        AdapayCore.apiBase = originalApiBase;
         AdapayCore.PUBLIC_KEY = originalPlatformKey;
         Adapay.addMerConfig(originalAccount, MERCHANT_KEY);
+        if (handlerFailure != null) throw new AssertionError(handlerFailure);
     }
 
     private ReceiptBillDto fetch(String tenant, String channel, LocalDate day) throws Exception {
@@ -152,23 +167,6 @@ public class ReceiptBillGatewayTest {
             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")));
         }
-        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"));
-            assertEquals(AdapaySign.sign(uri.toString() + body, Adapay.getConfig(MERCHANT_KEY).getRSAPrivateKey()), 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);
-            envelope.put("signature", sign("SHA1withRSA", result));
-            return new BillHttp.Reply(200, JSON.writeValueAsBytes(envelope));
-        }
         assertEquals("openapi.alipay.com", uri.getHost());
         Map<String,String> fields = new TreeMap<>();
         for (String pair : body.split("&")) { String[] split = pair.split("=", 2); fields.put(split[0], URLDecoder.decode(split[1], "UTF-8")); }
@@ -188,6 +186,47 @@ public class ReceiptBillGatewayTest {
         return new BillHttp.Reply(200, envelope.getBytes(UTF_8));
     }
 
+    private void handleHuifu(HttpExchange exchange) throws IOException {
+        int status = 200;
+        byte[] response;
+        try {
+            tickets++;
+            requests++;
+            assertEquals("POST", exchange.getRequestMethod());
+            assertEquals("/v1/bill/download", exchange.getRequestURI().toString());
+            assertEquals("/v1/bill/download", exchange.getRequestHeaders().getFirst("API_Name"));
+            assertEquals("offline-api", exchange.getRequestHeaders().getFirst("Authorization"));
+            String body = new String(BillHttp.read(exchange.getRequestBody(), BillHttp.API_LIMIT), UTF_8);
+            assertEquals("20261119", JSON.readTree(body).path("bill_date").asText());
+            verify("SHA1withRSA", AdapayCore.apiBase + exchange.getRequestURI() + body,
+                    exchange.getRequestHeaders().getFirst("Signature"));
+            String data = "{\"status\":\"succeeded\",\"prod_mode\":true,\"bill_download_url\":\"https://jarvisfile.oss-cn-shanghai.aliyuncs.com/test\"}";
+            if ("pending".equals(mode)) data = "{\"status\":\"pending\",\"prod_mode\":true}";
+            if ("ticket401".equals(mode)) {
+                status = 401;
+                data = "{\"status\":\"failed\",\"error_code\":\"security_exception\",\"error_msg\":\"private-file\"}";
+            }
+            Map<String,String> envelope = new HashMap<>();
+            envelope.put("data", data);
+            envelope.put("signature", sign("SHA1withRSA", "badTicketSignature".equals(mode) ? "changed" : data));
+            response = JSON.writeValueAsBytes(envelope);
+            if ("empty401".equals(mode) || "plain401".equals(mode)) {
+                status = 401;
+                response = "empty401".equals(mode) ? new byte[0] : "Invalid API key".getBytes(UTF_8);
+            }
+        } catch (Throwable failure) {
+            handlerFailure = failure;
+            status = 500;
+            response = new byte[0];
+        }
+        try {
+            exchange.sendResponseHeaders(status, response.length);
+            exchange.getResponseBody().write(response);
+        } finally {
+            exchange.close();
+        }
+    }
+
     private BillHttp.Reply wx(int status, String body) throws Exception {
         String timestamp = Long.toString(Instant.now().getEpochSecond());
         BillHttp.Reply reply = new BillHttp.Reply(status, body.getBytes(UTF_8));
@@ -228,20 +267,12 @@ public class ReceiptBillGatewayTest {
         assertEquals(3, downloads); assertEquals(7, requests);
     }
 
-    @Test public void huifuUsesCurrentPaymentCredentialsAfterRotation() throws Exception {
-        HfMerchantConfig updated = new HfMerchantConfig();
-        updated.setTenantId(101);
-        updated.setAppId(ada.getAppId());
-        updated.setMerKey(MERCHANT_KEY);
-        updated.setApiKey(ada.getMerchantId());
-        updated.setRsaPrivateKey(ada.getKeyPrivate());
-        when(huifu.queryByTenantId(101, "ADAPAY")).thenReturn(updated);
-        ada.setMerchantId("previous-api");
-        ada.setKeyPrivate(Base64.getEncoder().encodeToString(platform.getPrivate().getEncoded()));
+    @Test public void huifuUsesFinanceExportMerchantWithoutPaymentPlugin() throws Exception {
         assertEquals("READY", fetch("101", "HUIFU", DAY).getStatus());
+        org.mockito.Mockito.verify(payments, never()).getPaymentService("ADAPAY_101");
         assertEquals(1, tickets);
 
-        updated.setAppId("another-app");
+        stored.setApiKey("different-account");
         ReceiptBillDto rejected = fetch("101", "HUIFU", DAY);
         assertEquals("ERROR", rejected.getStatus());
         assertTrue(rejected.getMessage().contains("与本机构商户记录不一致"));
@@ -249,7 +280,7 @@ public class ReceiptBillGatewayTest {
     }
 
     @Test public void huifuDoesNotFallBackToStartupKeysForMissingSdkAccount() throws Exception {
-        ada.setMerchantKey("receipt-test-unregistered");
+        stored.setMerKey("receipt-test-unregistered");
         assertTrue(fetch("101", "HUIFU", DAY).getMessage().contains("未注册该机构"));
         assertEquals(0, requests);
     }
@@ -258,12 +289,14 @@ public class ReceiptBillGatewayTest {
         mode = "ticket401";
         ReceiptBillDto bill = fetch("101", "HUIFU", DAY);
         assertEquals("ERROR", bill.getStatus());
-        assertTrue(bill.getMessage(), bill.getMessage().contains("申请账单地址失败:HTTP 401,签名校验失败(security_exception)"));
+        assertTrue(bill.getMessage(), bill.getMessage().contains("申请账单地址失败:渠道拒绝请求: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 无效"));
+        mode = "badTicketSignature";
+        bill = fetch("101", "HUIFU", DAY);
+        assertEquals("ERROR", bill.getStatus());
+        assertTrue(bill.getMessage(), bill.getMessage().contains("申请账单地址失败:汇付响应验签失败"));
+        mode = "pending";
+        assertEquals("NOT_READY", fetch("101", "HUIFU", DAY).getStatus());
         assertEquals(0, downloads);
         mode = "file401";
         bill = fetch("101", "HUIFU", DAY);
@@ -274,6 +307,18 @@ public class ReceiptBillGatewayTest {
         assertEquals(1, downloads);
     }
 
+    @Test public void huifuUnsignedOrEmptyRejectionsStayAtTicketStage() throws Exception {
+        for (String scenario : Arrays.asList("empty401", "plain401")) {
+            mode = scenario;
+            ReceiptBillDto bill = fetch("101", "HUIFU", DAY);
+            assertEquals("ERROR", bill.getStatus());
+            assertTrue(bill.getMessage(), bill.getMessage().contains("汇付申请账单地址失败"));
+            assertFalse(bill.getMessage().contains("Invalid API key"));
+        }
+        assertEquals(2, tickets);
+        assertEquals(0, 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)"));
@@ -296,7 +341,7 @@ public class ReceiptBillGatewayTest {
 
     @Test public void missingConfigOrSecretsNotTreatedAsPendingEvenToday() throws Exception {
         assertEquals("ERROR", fetch("unconfigured", "WECHAT", DAY.plusDays(1)).getStatus());
-        ada.setMerchantId(null);
+        stored.setApiKey(null);
         ReceiptBillDto bill = fetch("101", "HUIFU", DAY.plusDays(1));
         assertEquals("ERROR", bill.getStatus()); assertNull(bill.getAvailableBalance()); assertEquals(0, requests);
     }