🎨 优化部分代码,清理无用代码

This commit is contained in:
Binary Wang 2022-10-31 15:25:40 +08:00
parent ae08833323
commit 9522585074
3 changed files with 52 additions and 51 deletions

View File

@ -6,33 +6,32 @@ import com.github.binarywang.wxpay.util.ResourcesUtils;
import com.github.binarywang.wxpay.v3.WxPayV3HttpClientBuilder; import com.github.binarywang.wxpay.v3.WxPayV3HttpClientBuilder;
import com.github.binarywang.wxpay.v3.auth.*; import com.github.binarywang.wxpay.v3.auth.*;
import com.github.binarywang.wxpay.v3.util.PemUtils; import com.github.binarywang.wxpay.v3.util.PemUtils;
import lombok.*; import lombok.Data;
import org.apache.commons.io.IOUtils; import lombok.EqualsAndHashCode;
import lombok.SneakyThrows;
import lombok.ToString;
import org.apache.commons.lang3.RegExUtils; import org.apache.commons.lang3.RegExUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.ssl.SSLContexts; import org.apache.http.ssl.SSLContexts;
import javax.net.ssl.SSLContext; import javax.net.ssl.SSLContext;
import java.io.*; import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL; import java.net.URL;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.security.KeyStore; import java.security.KeyStore;
import java.security.PrivateKey; import java.security.PrivateKey;
import java.security.cert.X509Certificate; import java.security.cert.X509Certificate;
import java.util.Base64; import java.util.Base64;
import java.util.Collections;
/** /**
* 微信支付配置 * 微信支付配置
* *
* @author Binary Wang (https://github.com/binarywang) * @author Binary Wang (<a href="https://github.com/binarywang">...</a>)
*/ */
@Data @Data
@ToString(exclude = "verifier") @ToString(exclude = "verifier")
@ -199,7 +198,7 @@ public class WxPayConfig {
/** /**
* v3接口下证书检验对象通过改对象可以获取到X509Certificate进一步对敏感信息加密 * v3接口下证书检验对象通过改对象可以获取到X509Certificate进一步对敏感信息加密
* 文档见 https://wechatpay-api.gitbook.io/wechatpay-api-v3/qian-ming-zhi-nan-1/min-gan-xin-xi-jia-mi * <a href="https://wechatpay-api.gitbook.io/wechatpay-api-v3/qian-ming-zhi-nan-1/min-gan-xin-xi-jia-mi">文档</a>
*/ */
private Verifier verifier; private Verifier verifier;
@ -236,9 +235,8 @@ public class WxPayConfig {
throw new WxPayException("请确保商户号mchId已设置"); throw new WxPayException("请确保商户号mchId已设置");
} }
InputStream inputStream = this.loadConfigInputStream(this.keyString, this.getKeyPath(), this.keyContent, "p12证书"); try (InputStream inputStream = this.loadConfigInputStream(this.keyString, this.getKeyPath(),
this.keyContent, "p12证书");) {
try {
KeyStore keystore = KeyStore.getInstance("PKCS12"); KeyStore keystore = KeyStore.getInstance("PKCS12");
char[] partnerId2charArray = this.getMchId().toCharArray(); char[] partnerId2charArray = this.getMchId().toCharArray();
keystore.load(inputStream, partnerId2charArray); keystore.load(inputStream, partnerId2charArray);
@ -246,9 +244,8 @@ public class WxPayConfig {
return this.sslContext; return this.sslContext;
} catch (Exception e) { } catch (Exception e) {
throw new WxPayException("证书文件有问题,请核实!", e); throw new WxPayException("证书文件有问题,请核实!", e);
} finally {
IOUtils.closeQuietly(inputStream);
} }
} }
/** /**
@ -259,42 +256,37 @@ public class WxPayConfig {
* @author doger.wang * @author doger.wang
**/ **/
public CloseableHttpClient initApiV3HttpClient() throws WxPayException { public CloseableHttpClient initApiV3HttpClient() throws WxPayException {
val privateKeyString = this.getPrivateKeyString(); if (StringUtils.isBlank(this.getApiV3Key())) {
val privateKeyPath = this.getPrivateKeyPath();
val privateCertString = this.getPrivateCertString();
val privateCertPath = this.getPrivateCertPath();
val serialNo = this.getCertSerialNo();
val apiV3Key = this.getApiV3Key();
if (StringUtils.isBlank(apiV3Key)) {
throw new WxPayException("请确保apiV3Key值已设置"); throw new WxPayException("请确保apiV3Key值已设置");
} }
InputStream keyInputStream = this.loadConfigInputStream(privateKeyString, privateKeyPath, this.privateKeyContent, "privateKeyPath"); InputStream keyInputStream = this.loadConfigInputStream(this.getPrivateKeyString(), this.getPrivateKeyPath(),
InputStream certInputStream = this.loadConfigInputStream(privateCertString, privateCertPath, this.privateCertContent, "privateCertPath"); this.privateKeyContent, "privateKeyPath");
InputStream certInputStream = this.loadConfigInputStream(this.getPrivateCertString(), this.getPrivateCertPath(),
this.privateCertContent, "privateCertPath");
try { try {
PrivateKey merchantPrivateKey = PemUtils.loadPrivateKey(keyInputStream); PrivateKey merchantPrivateKey = PemUtils.loadPrivateKey(keyInputStream);
X509Certificate certificate = PemUtils.loadCertificate(certInputStream); X509Certificate certificate = PemUtils.loadCertificate(certInputStream);
if(StringUtils.isBlank(serialNo)){ if (StringUtils.isBlank(this.getCertSerialNo())) {
this.certSerialNo = certificate.getSerialNumber().toString(16).toUpperCase(); this.certSerialNo = certificate.getSerialNumber().toString(16).toUpperCase();
} }
//构造Http Proxy正向代理 //构造Http Proxy正向代理
WxPayHttpProxy wxPayHttpProxy = getWxPayHttpProxy(); WxPayHttpProxy wxPayHttpProxy = getWxPayHttpProxy();
AutoUpdateCertificatesVerifier verifier = new AutoUpdateCertificatesVerifier( AutoUpdateCertificatesVerifier certificatesVerifier = new AutoUpdateCertificatesVerifier(
new WxPayCredentials(mchId, new PrivateKeySigner(certSerialNo, merchantPrivateKey)), new WxPayCredentials(mchId, new PrivateKeySigner(certSerialNo, merchantPrivateKey)),
apiV3Key.getBytes(StandardCharsets.UTF_8), this.getCertAutoUpdateTime(),wxPayHttpProxy); this.getApiV3Key().getBytes(StandardCharsets.UTF_8), this.getCertAutoUpdateTime(), wxPayHttpProxy);
WxPayV3HttpClientBuilder wxPayV3HttpClientBuilder = WxPayV3HttpClientBuilder.create() WxPayV3HttpClientBuilder wxPayV3HttpClientBuilder = WxPayV3HttpClientBuilder.create()
.withMerchant(mchId, certSerialNo, merchantPrivateKey) .withMerchant(mchId, certSerialNo, merchantPrivateKey)
.withWechatpay(Collections.singletonList(certificate)) .withValidator(new WxPayValidator(certificatesVerifier));
.withValidator(new WxPayValidator(verifier));
//初始化V3接口正向代理设置 //初始化V3接口正向代理设置
HttpProxyUtils.initHttpProxy(wxPayV3HttpClientBuilder, wxPayHttpProxy); HttpProxyUtils.initHttpProxy(wxPayV3HttpClientBuilder, wxPayHttpProxy);
CloseableHttpClient httpClient = wxPayV3HttpClientBuilder.build(); CloseableHttpClient httpClient = wxPayV3HttpClientBuilder.build();
this.apiV3HttpClient = httpClient; this.apiV3HttpClient = httpClient;
this.verifier=verifier; this.verifier = certificatesVerifier;
this.privateKey = merchantPrivateKey; this.privateKey = merchantPrivateKey;
return httpClient; return httpClient;
@ -305,6 +297,7 @@ public class WxPayConfig {
/** /**
* 初始化一个WxPayHttpProxy对象 * 初始化一个WxPayHttpProxy对象
*
* @return 返回封装的WxPayHttpProxy对象如未指定代理主机和端口则默认返回null * @return 返回封装的WxPayHttpProxy对象如未指定代理主机和端口则默认返回null
*/ */
private WxPayHttpProxy getWxPayHttpProxy() { private WxPayHttpProxy getWxPayHttpProxy() {
@ -314,7 +307,8 @@ public class WxPayConfig {
return null; return null;
} }
private InputStream loadConfigInputStream(String configString, String configPath, byte[] configContent, String fileName) throws WxPayException { private InputStream loadConfigInputStream(String configString, String configPath, byte[] configContent,
String fileName) throws WxPayException {
InputStream inputStream; InputStream inputStream;
if (configContent != null) { if (configContent != null) {
inputStream = new ByteArrayInputStream(configContent); inputStream = new ByteArrayInputStream(configContent);
@ -333,34 +327,42 @@ public class WxPayConfig {
/** /**
* 从配置路径 加载配置 信息支持 classpath本地路径网络url * 从配置路径 加载配置 信息支持 classpath本地路径网络url
*
* @param configPath 配置路径 * @param configPath 配置路径
* @return * @return .
* @throws WxPayException * @throws WxPayException .
*/ */
private InputStream loadConfigInputStream(String configPath) throws WxPayException { private InputStream loadConfigInputStream(String configPath) throws WxPayException {
InputStream inputStream;
final String prefix = "classpath:";
String fileHasProblemMsg = String.format(PROBLEM_MSG, configPath); String fileHasProblemMsg = String.format(PROBLEM_MSG, configPath);
String fileNotFoundMsg = String.format(NOT_FOUND_MSG, configPath); String fileNotFoundMsg = String.format(NOT_FOUND_MSG, configPath);
final String prefix = "classpath:";
InputStream inputStream;
if (configPath.startsWith(prefix)) { if (configPath.startsWith(prefix)) {
String path = RegExUtils.removeFirst(configPath, prefix); String path = RegExUtils.removeFirst(configPath, prefix);
if (!path.startsWith("/")) { if (!path.startsWith("/")) {
path = "/" + path; path = "/" + path;
} }
try { try {
inputStream = ResourcesUtils.getResourceAsStream(path); inputStream = ResourcesUtils.getResourceAsStream(path);
if (inputStream == null) { if (inputStream == null) {
throw new WxPayException(fileNotFoundMsg); throw new WxPayException(fileNotFoundMsg);
} }
return inputStream;
} catch (Exception e) { } catch (Exception e) {
throw new WxPayException(fileNotFoundMsg, e); throw new WxPayException(fileNotFoundMsg, e);
} }
} else if (configPath.startsWith("http://") || configPath.startsWith("https://")) { }
if (configPath.startsWith("http://") || configPath.startsWith("https://")) {
try { try {
inputStream = new URL(configPath).openStream(); inputStream = new URL(configPath).openStream();
if (inputStream == null) { if (inputStream == null) {
throw new WxPayException(fileNotFoundMsg); throw new WxPayException(fileNotFoundMsg);
} }
return inputStream;
} catch (IOException e) { } catch (IOException e) {
throw new WxPayException(fileNotFoundMsg, e); throw new WxPayException(fileNotFoundMsg, e);
} }
@ -371,11 +373,11 @@ public class WxPayConfig {
throw new WxPayException(fileNotFoundMsg); throw new WxPayException(fileNotFoundMsg);
} }
inputStream = new FileInputStream(file); return Files.newInputStream(file.toPath());
} catch (IOException e) { } catch (IOException e) {
throw new WxPayException(fileHasProblemMsg, e); throw new WxPayException(fileHasProblemMsg, e);
} }
} }
return inputStream;
} }
} }

View File

@ -46,11 +46,6 @@ public class WxPayV3HttpClientBuilder extends HttpClientBuilder {
return this; return this;
} }
public WxPayV3HttpClientBuilder withWechatpay(List<X509Certificate> certificates) {
this.validator = new WxPayValidator(new CertificatesVerifier(certificates));
return this;
}
public WxPayV3HttpClientBuilder withValidator(Validator validator) { public WxPayV3HttpClientBuilder withValidator(Validator validator) {
this.validator = validator; this.validator = validator;
return this; return this;

View File

@ -11,9 +11,12 @@ import org.apache.http.util.EntityUtils;
import java.io.IOException; import java.io.IOException;
/**
* @author spvycf & F00lish
*/
@Slf4j @Slf4j
public class WxPayValidator implements Validator { public class WxPayValidator implements Validator {
private Verifier verifier; private final Verifier verifier;
public WxPayValidator(Verifier verifier) { public WxPayValidator(Verifier verifier) {
this.verifier = verifier; this.verifier = verifier;
@ -21,7 +24,8 @@ public class WxPayValidator implements Validator {
@Override @Override
public final boolean validate(CloseableHttpResponse response) throws IOException { public final boolean validate(CloseableHttpResponse response) throws IOException {
if (!ContentType.APPLICATION_JSON.getMimeType().equals(ContentType.parse(String.valueOf(response.getFirstHeader("Content-Type").getValue())).getMimeType())) { if (!ContentType.APPLICATION_JSON.getMimeType().equals(ContentType.parse(String.valueOf(response.getFirstHeader(
"Content-Type").getValue())).getMimeType())) {
return true; return true;
} }
Header serialNo = response.getFirstHeader("Wechatpay-Serial"); Header serialNo = response.getFirstHeader("Wechatpay-Serial");