支付客户端现在支持独立信任 nginx 的 TLS 证书,保留域名校验,不修改全局信任库

This commit is contained in:
lu7213 committed 2026-10-29 05:12:09 -04:00
1 parent d88ad8996a
commit 36e3b046a0
6 files changed
+191 -10

No files matched your search

@@ -1,33 +1,39 @@
package com.ruoyi.system.rental;
import static com.ruoyi.system.rental.RentalValues.*;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.system.security.RsaKeyUtil;
import com.ruoyi.system.security.SecureClient;
import com.ruoyi.system.service.PaymentSignatureService;
import okhttp3.*;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.Signature;
import java.util.Base64;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import com.ruoyi.system.service.PaymentSignatureService;
/** 支付HTTP适配器:复用项目混合加密SDK;不允许重定向携带支付认证材料。 */
import static com.ruoyi.system.rental.RentalValues.*;
/**
* 支付HTTP适配器:复用项目混合加密SDK;不允许重定向携带支付认证材料。
*/
@Component
public class RentalPaymentClient {
private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(RentalPaymentClient.class);
private final ObjectMapper json;
private final RentalPaymentProperties properties;
private final ResourceLoader resources;
public RentalPaymentClient(ObjectMapper json, RentalPaymentProperties properties, ResourceLoader resources) {
this.json = json.copy().enable(com.fasterxml.jackson.databind.DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);
this.properties = properties;
this.resources = resources;
}
public String publicKey(RentalPaymentProperties.Channel channel) throws Exception {
// 不打印资源路径;配置误填密钥正文或含口令URL时同样不会泄露。
String location = channel.getRsaPublicKeyLocation();
@@ -47,6 +53,7 @@ public class RentalPaymentClient {
return pem;
}
}
public Map<String, Object> call(Map<String, Object> order, String operation) throws Exception {
RentalPaymentProperties.Channel channel = properties.channel(text(order, "network"));
require(properties.isEnabled() && channel.isEnabled(), "支付充值尚未启用");
@@ -60,26 +67,35 @@ public class RentalPaymentClient {
}
Object encrypted = SecureClient.encrypt(text(order, "payment_api_key"), channel.getApiSecret(),
RsaKeyUtil.loadPublicKey(text(order, "payment_public_key")), parameters);
OkHttpClient client = new OkHttpClient.Builder()
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.connectTimeout(properties.getConnectTimeoutMs(), TimeUnit.MILLISECONDS)
.readTimeout(properties.getReadTimeoutMs(), TimeUnit.MILLISECONDS)
.callTimeout(30, TimeUnit.SECONDS).followRedirects(false).followSslRedirects(false)
.retryOnConnectionFailure(false).build();
Request request = new Request.Builder().url(text(order, "payment_base_url") + "/api/v1/order/" + operation)
.retryOnConnectionFailure(false);
RentalPaymentTls.configure(builder, channel.getTlsCertificateLocation(), resources);
LOG.info("支付TLS配置 network={} additionalCertificateConfigured={} hostnameVerification=enabled",
text(order, "network"), channel.getTlsCertificateLocation() != null && !channel.getTlsCertificateLocation().trim().isEmpty());
OkHttpClient client = builder.build();
String url = text(order, "payment_base_url") + "/api/v1/order/" + operation;
Request request = new Request.Builder().url(url)
.post(RequestBody.create(MediaType.parse("application/json"), json.writeValueAsString(encrypted))).build();
long started = System.nanoTime();
LOG.info("充值支付请求开始 topupNo={} network={} operation={}", text(order, "topup_no"), text(order, "network"), operation);
LOG.info("充值支付请求开始 url {} topupNo={} network={} operation={}",url, text(order, "topup_no"), text(order, "network"), operation);
try (Response response = client.newCall(request).execute()) {
LOG.info("充值支付HTTP响应 topupNo={} operation={} httpStatus={} elapsedMs={}",
text(order, "topup_no"), operation, response.code(), TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started));
Map<String, Object> result = json.readValue(RentalHttp.body(response), new TypeReference<Map<String, Object>>() { });
Map<String, Object> result = json.readValue(RentalHttp.body(response), new TypeReference<Map<String, Object>>() {
});
LOG.info("充值支付业务响应 topupNo={} operation={} businessCode={} dataObject={}",
text(order, "topup_no"), operation, number(result, "code"), result.get("data") instanceof Map);
require(number(result, "code") == 200 && result.get("data") instanceof Map, "支付请求未成功,请稍后核对");
return (Map<String, Object>) result.get("data");
}
}
/** RSA验签使用项目既有参数规范化规则,不使用租赁HMAC或浏览器跳转结果。 */
/**
* RSA验签使用项目既有参数规范化规则,不使用租赁HMAC或浏览器跳转结果。
*/
public boolean verify(Map<String, Object> order, Map<String, Object> payload, String key, String signature) {
try {
if (!text(order, "payment_api_key").equals(key) || signature == null) return false;
@@ -87,6 +103,8 @@ public class RentalPaymentClient {
verifier.initVerify(RsaKeyUtil.loadPublicKey(text(order, "payment_public_key")));
verifier.update(PaymentSignatureService.canonicalText(payload).getBytes(StandardCharsets.UTF_8));
return verifier.verify(Base64.getDecoder().decode(signature));
} catch (Exception exception) { return false; }
} catch (Exception exception) {
return false;
}
}
}
@@ -84,6 +84,10 @@ public class RentalPaymentProperties {
private String apiKey = "";
private String apiSecret = "";
private String rsaPublicKeyLocation = "";
/** 支付服务TLS信任证书(PEM/DER),不是支付应用RSA公钥;空值使用JVM默认信任。 */
private String tlsCertificateLocation = "";
public String getTlsCertificateLocation() { return tlsCertificateLocation; }
public void setTlsCertificateLocation(String value) { tlsCertificateLocation = value; }
private String notifyUrl = "";
private BigDecimal minAmount = new BigDecimal("1.00");
private BigDecimal maxAmount = new BigDecimal("10000.00");
@@ -0,0 +1,67 @@
package com.ruoyi.system.rental;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Collection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import okhttp3.OkHttpClient;
import org.springframework.core.io.ResourceLoader;
/** 支付专用TLS上下文。只追加管理员指定的信任证书,不修改全局SSLContext或域名校验。 */
final class RentalPaymentTls {
private RentalPaymentTls() { }
static void configure(OkHttpClient.Builder builder, String location, ResourceLoader resources) throws Exception {
if (location == null || location.trim().isEmpty()) { return; }
// 只允许本地或类路径证书,避免为建立信任而先请求不可信远端。
RentalValues.require(location.startsWith("file:") || location.startsWith("classpath:"),
"支付TLS证书必须配置file:或classpath:资源路径");
Collection<? extends Certificate> certificates;
try (InputStream input = resources.getResource(location).getInputStream()) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int count;
while ((count = input.read(buffer)) != -1) {
RentalValues.require(bytes.size() + count <= 262144, "支付TLS证书文件超过256KiB");
bytes.write(buffer, 0, count);
}
certificates = CertificateFactory.getInstance("X.509")
.generateCertificates(new ByteArrayInputStream(bytes.toByteArray()));
}
RentalValues.require(!certificates.isEmpty(), "支付TLS证书文件不包含X.509证书");
TrustManagerFactory defaults = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
defaults.init((KeyStore) null);
KeyStore combined = KeyStore.getInstance(KeyStore.getDefaultType());
combined.load(null, null);
int index = 0;
for (X509Certificate certificate : manager(defaults).getAcceptedIssuers()) {
combined.setCertificateEntry("default-" + index++, certificate);
}
for (Certificate certificate : certificates) {
((X509Certificate) certificate).checkValidity();
combined.setCertificateEntry("payment-" + index++, certificate);
}
TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
factory.init(combined);
X509TrustManager trust = manager(factory);
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, new TrustManager[]{trust}, null);
// OkHttp仍执行默认HostnameVerifier,证书SAN必须匹配请求域名/IP。
builder.sslSocketFactory(context.getSocketFactory(), trust);
}
private static X509TrustManager manager(TrustManagerFactory factory) {
for (TrustManager manager : factory.getTrustManagers()) {
if (manager instanceof X509TrustManager) { return (X509TrustManager) manager; }
}
throw new IllegalStateException("JVM未提供X509信任管理器");
}
}