Skip to content

Commit 40ab5dd

Browse files
committed
🎨 修复重构后的代码
1 parent 39cea92 commit 40ab5dd

File tree

3 files changed

+89
-79
lines changed

3 files changed

+89
-79
lines changed

weixin-java-pay/pom.xml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,11 @@
8282
<groupId>org.projectlombok</groupId>
8383
<artifactId>lombok</artifactId>
8484
</dependency>
85+
<dependency>
86+
<groupId>com.fasterxml.jackson.core</groupId>
87+
<artifactId>jackson-databind</artifactId>
88+
<version>2.9.7</version>
89+
</dependency>
8590
<dependency>
8691
<groupId>com.google.code.gson</groupId>
8792
<artifactId>gson</artifactId>

weixin-java-pay/src/main/java/com/github/binarywang/wxpay/service/impl/WxPayServiceApacheHttpImpl.java

Lines changed: 22 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,9 @@
11
package com.github.binarywang.wxpay.service.impl;
22

3-
import java.net.URI;
4-
import java.nio.charset.StandardCharsets;
5-
import javax.net.ssl.SSLContext;
6-
7-
import com.alibaba.fastjson.JSONObject;
83
import com.github.binarywang.wxpay.bean.WxPayApiData;
94
import com.github.binarywang.wxpay.exception.WxPayException;
5+
import com.google.gson.JsonObject;
6+
import com.google.gson.JsonParser;
107
import jodd.util.Base64;
118
import org.apache.commons.lang3.StringUtils;
129
import org.apache.http.HttpHost;
@@ -28,6 +25,10 @@
2825
import org.apache.http.impl.client.HttpClients;
2926
import org.apache.http.util.EntityUtils;
3027

28+
import javax.net.ssl.SSLContext;
29+
import java.net.URI;
30+
import java.nio.charset.StandardCharsets;
31+
3132
/**
3233
* <pre>
3334
* 微信支付请求实现类,apache httpclient实现.
@@ -37,6 +38,8 @@
3738
* @author <a href="https://github.com/binarywang">Binary Wang</a>
3839
*/
3940
public class WxPayServiceApacheHttpImpl extends BaseWxPayServiceImpl {
41+
private final static JsonParser JSON_PARSER = new JsonParser();
42+
4043
@Override
4144
public byte[] postForBytes(String url, String requestStr, boolean useKey) throws WxPayException {
4245
try {
@@ -92,18 +95,17 @@ public String postV3(String url, String requestStr) throws WxPayException {
9295
HttpPost httpPost = this.createHttpPost(url, requestStr);
9396
httpPost.addHeader("Accept", "application/json");
9497
httpPost.addHeader("Content-Type", "application/json");
95-
try (CloseableHttpResponse response = httpClient.execute(httpPost)){
98+
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
9699
//v3已经改为通过状态码判断200 204 成功
97100
int statusCode = response.getStatusLine().getStatusCode();
98101
String responseString = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
99-
if (HttpStatus.SC_OK==statusCode || HttpStatus.SC_NO_CONTENT==statusCode){
102+
if (HttpStatus.SC_OK == statusCode || HttpStatus.SC_NO_CONTENT == statusCode) {
100103
this.log.info("\n【请求地址】:{}\n【请求数据】:{}\n【响应数据】:{}", url, requestStr, responseString);
101104
return responseString;
102-
}else {
105+
} else {
103106
//有错误提示信息返回
104-
JSONObject jsonObject = JSONObject.parseObject(responseString);
105-
String message = jsonObject.getString("message");
106-
throw new WxPayException(message);
107+
JsonObject jsonObject = JSON_PARSER.parse(responseString).getAsJsonObject();
108+
throw new WxPayException(jsonObject.get("message").getAsString());
107109
}
108110
} catch (Exception e) {
109111
this.log.error("\n【请求地址】:{}\n【请求数据】:{}\n【异常信息】:{}", url, requestStr, e.getMessage());
@@ -113,8 +115,6 @@ public String postV3(String url, String requestStr) throws WxPayException {
113115
}
114116

115117

116-
117-
118118
}
119119

120120
@Override
@@ -123,44 +123,37 @@ public String getV3(URI url) throws WxPayException {
123123
HttpGet httpGet = new HttpGet(url);
124124
httpGet.addHeader("Accept", "application/json");
125125
httpGet.addHeader("Content-Type", "application/json");
126-
try (CloseableHttpResponse response = httpClient.execute(httpGet)){
126+
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
127127
//v3已经改为通过状态码判断200 204 成功
128128
int statusCode = response.getStatusLine().getStatusCode();
129129
String responseString = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
130-
if (HttpStatus.SC_OK==statusCode || HttpStatus.SC_NO_CONTENT==statusCode){
131-
this.log.info("\n【请求地址】:{}\n【响应数据】:{}", url , responseString);
130+
if (HttpStatus.SC_OK == statusCode || HttpStatus.SC_NO_CONTENT == statusCode) {
131+
this.log.info("\n【请求地址】:{}\n【响应数据】:{}", url, responseString);
132132
return responseString;
133-
}else {
133+
} else {
134134
//有错误提示信息返回
135-
JSONObject jsonObject = JSONObject.parseObject(responseString);
136-
String message = jsonObject.getString("message");
137-
throw new WxPayException(message);
135+
JsonObject jsonObject = JSON_PARSER.parse(responseString).getAsJsonObject();
136+
throw new WxPayException(jsonObject.get("message").getAsString());
138137
}
139138
} catch (Exception e) {
140139
this.log.error("\n【请求地址】:{}\n【异常信息】:{}", url, e.getMessage());
141140
throw new WxPayException(e.getMessage(), e);
142141
} finally {
143142
httpGet.releaseConnection();
144143
}
145-
146-
147144
}
148145

149146
private CloseableHttpClient createApiV3HttpClient() throws WxPayException {
150147
CloseableHttpClient apiv3HttpClient = this.getConfig().getApiV3HttpClient();
151-
if (null==apiv3HttpClient){
148+
if (null == apiv3HttpClient) {
152149
return this.getConfig().initApiV3HttpClient();
153150
}
154151
return apiv3HttpClient;
155152
}
156153

157-
158154
private StringEntity createEntry(String requestStr) {
159-
160-
return new StringEntity(requestStr, ContentType.create("application/json", "utf-8"));
161-
//return new StringEntity(new String(requestStr.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
162-
163-
155+
return new StringEntity(requestStr, ContentType.create("application/json", "utf-8"));
156+
//return new StringEntity(new String(requestStr.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
164157
}
165158

166159
private HttpClientBuilder createHttpClientBuilder(boolean useKey) throws WxPayException {
Lines changed: 62 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,22 @@
11
package com.github.binarywang.wxpay.v3.auth;
22

3+
import com.fasterxml.jackson.databind.JsonNode;
4+
import com.fasterxml.jackson.databind.ObjectMapper;
5+
import com.github.binarywang.wxpay.v3.Credentials;
6+
import com.github.binarywang.wxpay.v3.WechatPayHttpClientBuilder;
7+
import com.github.binarywang.wxpay.v3.util.AesUtils;
8+
import com.github.binarywang.wxpay.v3.util.PemUtils;
9+
import lombok.Getter;
10+
import lombok.RequiredArgsConstructor;
11+
import lombok.extern.slf4j.Slf4j;
12+
import org.apache.http.client.methods.CloseableHttpResponse;
13+
import org.apache.http.client.methods.HttpGet;
14+
import org.apache.http.impl.client.CloseableHttpClient;
15+
import org.apache.http.util.EntityUtils;
316

417
import java.io.ByteArrayInputStream;
518
import java.io.IOException;
19+
import java.nio.charset.StandardCharsets;
620
import java.security.GeneralSecurityException;
721
import java.security.cert.CertificateExpiredException;
822
import java.security.cert.CertificateNotYetValidException;
@@ -13,57 +27,56 @@
1327
import java.util.List;
1428
import java.util.concurrent.locks.ReentrantLock;
1529

16-
import com.fasterxml.jackson.databind.JsonNode;
17-
import com.fasterxml.jackson.databind.ObjectMapper;
18-
import com.github.binarywang.wxpay.v3.Credentials;
19-
import com.github.binarywang.wxpay.v3.WechatPayHttpClientBuilder;
20-
import com.github.binarywang.wxpay.v3.util.AesUtils;
21-
import com.github.binarywang.wxpay.v3.util.PemUtils;
22-
import org.apache.http.client.methods.CloseableHttpResponse;
23-
import org.apache.http.client.methods.HttpGet;
24-
import org.apache.http.impl.client.CloseableHttpClient;
25-
import org.apache.http.util.EntityUtils;
26-
27-
import org.slf4j.Logger;
28-
import org.slf4j.LoggerFactory;
29-
3030
/**
3131
* 在原有CertificatesVerifier基础上,增加自动更新证书功能
32+
*
33+
* @author doger.wang
3234
*/
35+
@Slf4j
3336
public class AutoUpdateCertificatesVerifier implements Verifier {
37+
/**
38+
* 证书下载地址
39+
*/
40+
private static final String CERT_DOWNLOAD_PATH = "https://api.mch.weixin.qq.com/v3/certificates";
3441

35-
private static final Logger log = LoggerFactory.getLogger(AutoUpdateCertificatesVerifier.class);
36-
37-
//证书下载地址
38-
private static final String CertDownloadPath = "https://api.mch.weixin.qq.com/v3/certificates";
39-
40-
//上次更新时间
42+
/**
43+
* 上次更新时间
44+
*/
4145
private volatile Instant instant;
4246

43-
//证书更新间隔时间,单位为分钟
44-
private int minutesInterval;
47+
/**
48+
* 证书更新间隔时间,单位为分钟
49+
*/
50+
private final int minutesInterval;
4551

4652
private CertificatesVerifier verifier;
4753

48-
private Credentials credentials;
54+
private final Credentials credentials;
4955

50-
private byte[] apiV3Key;
56+
private final byte[] apiV3Key;
5157

52-
private ReentrantLock lock = new ReentrantLock();
58+
private final ReentrantLock lock = new ReentrantLock();
5359

54-
//时间间隔枚举,支持一小时、六小时以及十二小时
60+
/**
61+
* 时间间隔枚举,支持一小时、六小时以及十二小时
62+
*/
63+
@Getter
64+
@RequiredArgsConstructor
5565
public enum TimeInterval {
56-
OneHour(60), SixHours(60 * 6), TwelveHours(60 * 12);
57-
58-
private int minutes;
59-
60-
TimeInterval(int minutes) {
61-
this.minutes = minutes;
62-
}
63-
64-
public int getMinutes() {
65-
return minutes;
66-
}
66+
/**
67+
* 一小时
68+
*/
69+
OneHour(60),
70+
/**
71+
* 六小时
72+
*/
73+
SixHours(60 * 6),
74+
/**
75+
* 十二小时
76+
*/
77+
TwelveHours(60 * 12);
78+
79+
private final int minutes;
6780
}
6881

6982
public AutoUpdateCertificatesVerifier(Credentials credentials, byte[] apiV3Key) {
@@ -103,11 +116,11 @@ public boolean verify(String serialNumber, byte[] message, String signature) {
103116

104117
private void autoUpdateCert() throws IOException, GeneralSecurityException {
105118
CloseableHttpClient httpClient = WechatPayHttpClientBuilder.create()
106-
.withCredentials(credentials)
107-
.withValidator(verifier == null ? (response) -> true : new WechatPay2Validator(verifier))
108-
.build();
119+
.withCredentials(credentials)
120+
.withValidator(verifier == null ? (response) -> true : new WechatPay2Validator(verifier))
121+
.build();
109122

110-
HttpGet httpGet = new HttpGet(CertDownloadPath);
123+
HttpGet httpGet = new HttpGet(CERT_DOWNLOAD_PATH);
111124
httpGet.addHeader("Accept", "application/json");
112125

113126
CloseableHttpResponse response = httpClient.execute(httpGet);
@@ -125,12 +138,10 @@ private void autoUpdateCert() throws IOException, GeneralSecurityException {
125138
}
126139
}
127140

128-
129141
/**
130142
* 反序列化证书并解密
131143
*/
132-
private List<X509Certificate> deserializeToCerts(byte[] apiV3Key, String body)
133-
throws GeneralSecurityException, IOException {
144+
private List<X509Certificate> deserializeToCerts(byte[] apiV3Key, String body) throws GeneralSecurityException, IOException {
134145
AesUtils decryptor = new AesUtils(apiV3Key);
135146
ObjectMapper mapper = new ObjectMapper();
136147
JsonNode dataNode = mapper.readTree(body).get("data");
@@ -140,14 +151,14 @@ private List<X509Certificate> deserializeToCerts(byte[] apiV3Key, String body)
140151
JsonNode encryptCertificateNode = dataNode.get(i).get("encrypt_certificate");
141152
//解密
142153
String cert = decryptor.decryptToString(
143-
encryptCertificateNode.get("associated_data").toString().replaceAll("\"", "")
144-
.getBytes("utf-8"),
145-
encryptCertificateNode.get("nonce").toString().replaceAll("\"", "")
146-
.getBytes("utf-8"),
147-
encryptCertificateNode.get("ciphertext").toString().replaceAll("\"", ""));
154+
encryptCertificateNode.get("associated_data").toString().replaceAll("\"", "")
155+
.getBytes(StandardCharsets.UTF_8),
156+
encryptCertificateNode.get("nonce").toString().replaceAll("\"", "")
157+
.getBytes(StandardCharsets.UTF_8),
158+
encryptCertificateNode.get("ciphertext").toString().replaceAll("\"", ""));
148159

149160
X509Certificate x509Cert = PemUtils
150-
.loadCertificate(new ByteArrayInputStream(cert.getBytes("utf-8")));
161+
.loadCertificate(new ByteArrayInputStream(cert.getBytes(StandardCharsets.UTF_8)));
151162
try {
152163
x509Cert.checkValidity();
153164
} catch (CertificateExpiredException | CertificateNotYetValidException e) {
@@ -156,6 +167,7 @@ private List<X509Certificate> deserializeToCerts(byte[] apiV3Key, String body)
156167
newCertList.add(x509Cert);
157168
}
158169
}
170+
159171
return newCertList;
160172
}
161173
}

0 commit comments

Comments
 (0)