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

fix: 汇付取账使用原支付 SDK 当前商户签名密钥

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

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

@@ -2,12 +2,15 @@ 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.service.HfMerchantConfigService;
+import com.ym.mec.thirdparty.adapay.entity.HfMerchantConfig;
 import org.springframework.boot.context.properties.bind.Bindable;
 import org.springframework.boot.context.properties.bind.Binder;
 import org.springframework.core.env.Environment;
@@ -56,10 +59,7 @@ class ReceiptPaymentAccounts {
                     if (!item.getValue().equals(Collections.singleton(app))) throw unknown();
                 } else if (item.getValue().contains(app)) throw duplicate();
             }
-            BillCredentials keys = rsaKeys(account.getKeyPrivate(), AdapayCore.PUBLIC_KEY);
-            keys.fields.put("appId", app);
-            keys.fields.put("apiKey", required(account.getMerchantId(), "汇付 API Key"));
-            return keys;
+            return huifuCredentials(tenant, route, app, (AdapayPayConfig) account);
         }
         if ("ALIPAY".equals(vendor) && account instanceof AliPayConfig) {
             AliPayConfig ali = (AliPayConfig)account;
@@ -101,6 +101,27 @@ 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);
+        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;
+    }
+
     private static <T> void checkOthers(String route, String vendor, String owner, Map<String,T> accounts, Function<T,String> identity) throws BillHttp.Failure {
         for (Map.Entry<String,T> item : accounts.entrySet()) {
             if (!item.getKey().matches(vendor + "_[1-9][0-9]*") || item.getValue() == null) continue;

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

@@ -3,7 +3,10 @@ package com.ym.mec.biz.service.impl.receipt.gateway;
 import com.fasterxml.jackson.databind.ObjectMapper;
 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.huifu.adapay.model.MerConfig;
 import com.microsvc.toolkit.middleware.payment.common.api.*;
 import com.microsvc.toolkit.middleware.payment.impl.WxPaymentServicePlugin;
 import com.microsvc.toolkit.middleware.payment.properties.PayConfigProperties;
@@ -12,6 +15,7 @@ import com.ym.mec.biz.dal.dto.ReceiptBillDto;
 import com.ym.mec.biz.dal.vo.ReceiptChannelVo;
 import com.ym.mec.biz.dal.vo.ReceiptReconcileResultVo;
 import com.ym.mec.biz.service.HfMerchantConfigService;
+import com.ym.mec.thirdparty.adapay.entity.HfMerchantConfig;
 import com.ym.mec.biz.service.impl.receipt.ReceiptLedger;
 import org.junit.*;
 import static org.mockito.Mockito.*;
@@ -52,6 +56,8 @@ public class ReceiptBillGatewayTest {
     private final AliPayConfig ali = new AliPayConfig();
     private final PayConfigProperties.WxPayConfig wx = new PayConfigProperties.WxPayConfig();
     private String mode = "ok", originalPlatformKey;
+    private static final String MERCHANT_KEY = "receipt-test-merchant";
+    private MerConfig originalAccount;
     private int requests, downloads, tickets;
     private LocalDateTime clock = DAY.plusDays(1).atTime(10, 0);
 
@@ -72,6 +78,12 @@ public class ReceiptBillGatewayTest {
         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);
+        originalAccount = Adapay.getConfig(MERCHANT_KEY);
+        MerConfig runtimeAccount = new MerConfig();
+        runtimeAccount.setApiKey(ada.getMerchantId());
+        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));
@@ -95,7 +107,10 @@ public class ReceiptBillGatewayTest {
         accounts = new ReceiptPaymentAccounts(payments, shared, huifu, environment);
     }
 
-    @After public void restorePlatformKey() { AdapayCore.PUBLIC_KEY = originalPlatformKey; }
+    @After public void restoreAccounts() throws Exception {
+        AdapayCore.PUBLIC_KEY = originalPlatformKey;
+        Adapay.addMerConfig(originalAccount, MERCHANT_KEY);
+    }
 
     private ReceiptBillDto fetch(String tenant, String channel, LocalDate day) throws Exception {
         return new ReceiptBillGateway(accounts) {
@@ -143,6 +158,7 @@ public class ReceiptBillGatewayTest {
             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]);
@@ -212,6 +228,32 @@ 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()));
+        assertEquals("READY", fetch("101", "HUIFU", DAY).getStatus());
+        assertEquals(1, tickets);
+
+        updated.setAppId("another-app");
+        ReceiptBillDto rejected = fetch("101", "HUIFU", DAY);
+        assertEquals("ERROR", rejected.getStatus());
+        assertTrue(rejected.getMessage().contains("与本机构商户记录不一致"));
+        assertEquals(1, tickets);
+    }
+
+    @Test public void huifuDoesNotFallBackToStartupKeysForMissingSdkAccount() throws Exception {
+        ada.setMerchantKey("receipt-test-unregistered");
+        assertTrue(fetch("101", "HUIFU", DAY).getMessage().contains("未注册该机构"));
+        assertEquals(0, requests);
+    }
+
     @Test public void huifuReportsActualHttpStageAndSafeReason() throws Exception {
         mode = "ticket401";
         ReceiptBillDto bill = fetch("101", "HUIFU", DAY);