Skip to content

Commit 2279105

Browse files
committed
:art: 优化微信支付请求代码,抽取合并重复代码
1 parent cbb3b24 commit 2279105

File tree

3 files changed

+65
-103
lines changed

3 files changed

+65
-103
lines changed

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

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -64,8 +64,6 @@ public abstract class BaseWxPayServiceImpl implements WxPayService {
6464

6565
private static final Gson GSON = new GsonBuilder().create();
6666

67-
final Logger log = LoggerFactory.getLogger(this.getClass());
68-
6967
static ThreadLocal<WxPayApiData> wxApiData = new ThreadLocal<>();
7068

7169

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

Lines changed: 57 additions & 95 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import com.github.binarywang.wxpay.v3.WxPayV3DownloadHttpGet;
77
import com.google.gson.JsonElement;
88
import com.google.gson.JsonObject;
9+
import lombok.extern.slf4j.Slf4j;
910
import me.chanjar.weixin.common.util.json.GsonParser;
1011
import org.apache.commons.lang3.StringUtils;
1112
import org.apache.http.*;
@@ -39,12 +40,13 @@
3940
*
4041
* @author <a href="https://github.com/binarywang">Binary Wang</a>
4142
*/
43+
@Slf4j
4244
public class WxPayServiceApacheHttpImpl extends BaseWxPayServiceImpl {
4345

4446
private static final String ACCEPT = "Accept";
4547
private static final String CONTENT_TYPE = "Content-Type";
4648
private static final String APPLICATION_JSON = "application/json";
47-
private static final String WECHATPAY_SERIAL = "Wechatpay-Serial";
49+
private static final String WECHAT_PAY_SERIAL = "Wechatpay-Serial";
4850

4951
@Override
5052
public byte[] postForBytes(String url, String requestStr, boolean useKey) throws WxPayException {
@@ -55,15 +57,15 @@ public byte[] postForBytes(String url, String requestStr, boolean useKey) throws
5557
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
5658
final byte[] bytes = EntityUtils.toByteArray(response.getEntity());
5759
final String responseData = Base64.getEncoder().encodeToString(bytes);
58-
this.log.info("\n【请求地址】:{}\n【请求数据】:{}\n【响应数据(Base64编码后)】:{}", url, requestStr, responseData);
60+
this.logRequestAndResponse(url, requestStr, responseData);
5961
wxApiData.set(new WxPayApiData(url, requestStr, responseData, null));
6062
return bytes;
6163
}
6264
} finally {
6365
httpPost.releaseConnection();
6466
}
6567
} catch (Exception e) {
66-
this.log.error("\n【请求地址】:{}\n【请求数据】:{}\n【异常信息】:{}", url, requestStr, e.getMessage());
68+
this.logError( url, requestStr, e);
6769
wxApiData.set(new WxPayApiData(url, requestStr, null, e.getMessage()));
6870
throw new WxPayException(e.getMessage(), e);
6971
}
@@ -77,7 +79,7 @@ public String post(String url, String requestStr, boolean useKey) throws WxPayEx
7779
try (CloseableHttpClient httpClient = httpClientBuilder.build()) {
7880
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
7981
String responseString = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
80-
this.log.info("\n【请求地址】:{}\n【请求数据】:{}\n【响应数据】:{}", url, requestStr, responseString);
82+
this.logRequestAndResponse(url, requestStr, responseString);
8183
if (this.getConfig().isIfSaveApiData()) {
8284
wxApiData.set(new WxPayApiData(url, requestStr, responseString, null));
8385
}
@@ -87,7 +89,7 @@ public String post(String url, String requestStr, boolean useKey) throws WxPayEx
8789
httpPost.releaseConnection();
8890
}
8991
} catch (Exception e) {
90-
this.log.error("\n【请求地址】:{}\n【请求数据】:{}\n【异常信息】:{}", url, requestStr, e.getMessage());
92+
this.logError(url, requestStr, e);
9193
if (this.getConfig().isIfSaveApiData()) {
9294
wxApiData.set(new WxPayApiData(url, requestStr, null, e.getMessage()));
9395
}
@@ -97,13 +99,14 @@ public String post(String url, String requestStr, boolean useKey) throws WxPayEx
9799

98100
@Override
99101
public String postV3(String url, String requestStr) throws WxPayException {
100-
CloseableHttpClient httpClient = this.createApiV3HttpClient();
101102
HttpPost httpPost = this.createHttpPost(url, requestStr);
102-
httpPost.addHeader(ACCEPT, APPLICATION_JSON);
103-
httpPost.addHeader(CONTENT_TYPE, APPLICATION_JSON);
104-
String serialNumber = getWechatpaySerial(getConfig());
105-
httpPost.addHeader(WECHATPAY_SERIAL, serialNumber);
106-
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
103+
this.configureRequest(httpPost);
104+
return this.requestV3(url, requestStr, httpPost);
105+
}
106+
107+
private String requestV3(String url, String requestStr, HttpRequestBase httpRequestBase) throws WxPayException {
108+
try (CloseableHttpClient httpClient = this.createApiV3HttpClient();
109+
CloseableHttpResponse response = httpClient.execute(httpRequestBase)) {
107110
//v3已经改为通过状态码判断200 204 成功
108111
int statusCode = response.getStatusLine().getStatusCode();
109112
//post方法有可能会没有返回值的情况
@@ -113,73 +116,34 @@ public String postV3(String url, String requestStr) throws WxPayException {
113116
}
114117

115118
if (HttpStatus.SC_OK == statusCode || HttpStatus.SC_NO_CONTENT == statusCode) {
116-
this.log.info("\n【请求地址】:{}\n【请求数据】:{}\n【响应数据】:{}", url, requestStr, responseString);
119+
this.logRequestAndResponse(url, requestStr, responseString);
117120
return responseString;
118121
}
119122

120123
//有错误提示信息返回
121124
JsonObject jsonObject = GsonParser.parse(responseString);
122125
throw convertException(jsonObject);
123126
} catch (Exception e) {
124-
this.log.error("\n【请求地址】:{}\n【请求数据】:{}\n【异常信息】:{}", url, requestStr, e.getMessage());
127+
this.logError(url, requestStr, e);
125128
throw (e instanceof WxPayException) ? (WxPayException) e : new WxPayException(e.getMessage(), e);
126129
} finally {
127-
httpPost.releaseConnection();
130+
httpRequestBase.releaseConnection();
128131
}
129-
130-
131132
}
132133

133134
@Override
134135
public String patchV3(String url, String requestStr) throws WxPayException {
135-
CloseableHttpClient httpClient = this.createApiV3HttpClient();
136136
HttpPatch httpPatch = new HttpPatch(url);
137-
String serialNumber = getWechatpaySerial(getConfig());
138-
httpPatch.addHeader(WECHATPAY_SERIAL, serialNumber);
139137
httpPatch.setEntity(this.createEntry(requestStr));
140-
141-
httpPatch.setConfig(RequestConfig.custom()
142-
.setConnectionRequestTimeout(this.getConfig().getHttpConnectionTimeout())
143-
.setConnectTimeout(this.getConfig().getHttpConnectionTimeout())
144-
.setSocketTimeout(this.getConfig().getHttpTimeout())
145-
.build());
146-
147-
httpPatch.addHeader(ACCEPT, APPLICATION_JSON);
148-
httpPatch.addHeader(CONTENT_TYPE, APPLICATION_JSON);
149-
try (CloseableHttpResponse response = httpClient.execute(httpPatch)) {
150-
//v3已经改为通过状态码判断200 204 成功
151-
int statusCode = response.getStatusLine().getStatusCode();
152-
//post方法有可能会没有返回值的情况
153-
String responseString = null;
154-
if (response.getEntity() != null) {
155-
responseString = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
156-
}
157-
158-
if (HttpStatus.SC_OK == statusCode || HttpStatus.SC_NO_CONTENT == statusCode) {
159-
this.log.info("\n【请求地址】:{}\n【请求数据】:{}\n【响应数据】:{}", url, requestStr, responseString);
160-
return responseString;
161-
}
162-
163-
//有错误提示信息返回
164-
JsonObject jsonObject = GsonParser.parse(responseString);
165-
throw convertException(jsonObject);
166-
} catch (Exception e) {
167-
this.log.error("\n【请求地址】:{}\n【请求数据】:{}\n【异常信息】:{}", url, requestStr, e.getMessage());
168-
throw (e instanceof WxPayException) ? (WxPayException) e : new WxPayException(e.getMessage(), e);
169-
} finally {
170-
httpPatch.releaseConnection();
171-
}
138+
return this.requestV3(url, requestStr, httpPatch);
172139
}
173140

174141
@Override
175142
public String postV3WithWechatpaySerial(String url, String requestStr) throws WxPayException {
176-
CloseableHttpClient httpClient = this.createApiV3HttpClient();
177143
HttpPost httpPost = this.createHttpPost(url, requestStr);
178-
httpPost.addHeader(ACCEPT, APPLICATION_JSON);
179-
httpPost.addHeader(CONTENT_TYPE, APPLICATION_JSON);
180-
String serialNumber = getWechatpaySerial(getConfig());
181-
httpPost.addHeader("Wechatpay-Serial", serialNumber);
182-
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
144+
this.configureRequest(httpPost);
145+
try (CloseableHttpClient httpClient = this.createApiV3HttpClient();
146+
CloseableHttpResponse response = httpClient.execute(httpPost)) {
183147
//v3已经改为通过状态码判断200 204 成功
184148
int statusCode = response.getStatusLine().getStatusCode();
185149
String responseString = "{}";
@@ -189,16 +153,15 @@ public String postV3WithWechatpaySerial(String url, String requestStr) throws Wx
189153
}
190154

191155
if (HttpStatus.SC_OK == statusCode || HttpStatus.SC_NO_CONTENT == statusCode) {
192-
this.log.info("\n【请求地址】:{}\n【请求数据】:{}\n【响应数据】:{}", url, requestStr, responseString);
156+
this.logRequestAndResponse(url, requestStr, responseString);
193157
return responseString;
194158
}
195159

196160
//有错误提示信息返回
197161
JsonObject jsonObject = GsonParser.parse(responseString);
198162
throw convertException(jsonObject);
199163
} catch (Exception e) {
200-
this.log.error("\n【请求地址】:{}\n【请求数据】:{}\n【异常信息】:{}", url, requestStr, e.getMessage());
201-
e.printStackTrace();
164+
this.logError(url, requestStr, e);
202165
throw (e instanceof WxPayException) ? (WxPayException) e : new WxPayException(e.getMessage(), e);
203166
} finally {
204167
httpPost.releaseConnection();
@@ -207,21 +170,17 @@ public String postV3WithWechatpaySerial(String url, String requestStr) throws Wx
207170

208171
@Override
209172
public String postV3(String url, HttpPost httpPost) throws WxPayException {
210-
String serialNumber = getWechatpaySerial(getConfig());
211-
httpPost.addHeader(WECHATPAY_SERIAL, serialNumber);
173+
String serialNumber = getWechatPaySerial(getConfig());
174+
httpPost.addHeader(WECHAT_PAY_SERIAL, serialNumber);
212175
return this.requestV3(url, httpPost);
213176
}
214177

215178
@Override
216179
public String requestV3(String url, HttpRequestBase httpRequest) throws WxPayException {
217-
httpRequest.setConfig(RequestConfig.custom()
218-
.setConnectionRequestTimeout(this.getConfig().getHttpConnectionTimeout())
219-
.setConnectTimeout(this.getConfig().getHttpConnectionTimeout())
220-
.setSocketTimeout(this.getConfig().getHttpTimeout())
221-
.build());
180+
this.configureRequest(httpRequest);
222181

223-
CloseableHttpClient httpClient = this.createApiV3HttpClient();
224-
try (CloseableHttpResponse response = httpClient.execute(httpRequest)) {
182+
try (CloseableHttpClient httpClient = this.createApiV3HttpClient();
183+
CloseableHttpResponse response = httpClient.execute(httpRequest)) {
225184
//v3已经改为通过状态码判断200 204 成功
226185
int statusCode = response.getStatusLine().getStatusCode();
227186
//post方法有可能会没有返回值的情况
@@ -252,38 +211,30 @@ public String getV3(String url) throws WxPayException {
252211
return getV3WithWechatPaySerial(url);
253212
}
254213
HttpGet httpGet = new HttpGet(url);
255-
httpGet.addHeader(ACCEPT, APPLICATION_JSON);
256-
httpGet.addHeader(CONTENT_TYPE, APPLICATION_JSON);
257-
String serialNumber = getWechatpaySerial(getConfig());
258-
httpGet.addHeader(WECHATPAY_SERIAL, serialNumber);
259214
return this.requestV3(url, httpGet);
260215
}
261216

262217
@Override
263218
public String getV3WithWechatPaySerial(String url) throws WxPayException {
264219
HttpGet httpGet = new HttpGet(url);
265-
httpGet.addHeader(ACCEPT, APPLICATION_JSON);
266-
httpGet.addHeader(CONTENT_TYPE, APPLICATION_JSON);
267-
String serialNumber = getWechatpaySerial(getConfig());
268-
httpGet.addHeader(WECHATPAY_SERIAL, serialNumber);
269220
return this.requestV3(url, httpGet);
270221
}
271222

272223
@Override
273224
public InputStream downloadV3(String url) throws WxPayException {
274-
CloseableHttpClient httpClient = this.createApiV3HttpClient();
275225
HttpGet httpGet = new WxPayV3DownloadHttpGet(url);
276226
httpGet.addHeader(ACCEPT, ContentType.WILDCARD.getMimeType());
277-
String serialNumber = getWechatpaySerial(getConfig());
278-
httpGet.addHeader(WECHATPAY_SERIAL, serialNumber);
279-
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
227+
String serialNumber = getWechatPaySerial(getConfig());
228+
httpGet.addHeader(WECHAT_PAY_SERIAL, serialNumber);
229+
try (CloseableHttpClient httpClient = this.createApiV3HttpClient();
230+
CloseableHttpResponse response = httpClient.execute(httpGet)) {
280231
//v3已经改为通过状态码判断200 204 成功
281232
int statusCode = response.getStatusLine().getStatusCode();
282233
Header contentType = response.getFirstHeader(HttpHeaders.CONTENT_TYPE);
283234
boolean isJsonContentType = Objects.nonNull(contentType) && ContentType.APPLICATION_JSON.getMimeType()
284235
.equals(ContentType.parse(String.valueOf(contentType.getValue())).getMimeType());
285236
if ((HttpStatus.SC_OK == statusCode || HttpStatus.SC_NO_CONTENT == statusCode) && !isJsonContentType) {
286-
this.log.info("\n【请求地址】:{}\n", url);
237+
log.info("\n【请求地址】:{}\n", url);
287238
return response.getEntity().getContent();
288239
}
289240

@@ -293,7 +244,7 @@ public InputStream downloadV3(String url) throws WxPayException {
293244
JsonObject jsonObject = GsonParser.parse(responseString);
294245
throw convertException(jsonObject);
295246
} catch (Exception e) {
296-
this.log.error("\n【请求地址】:{}\n【异常信息】:{}", url, e.getMessage());
247+
log.error("\n【请求地址】:{}\n【异常信息】:{}", url, e.getMessage());
297248
throw (e instanceof WxPayException) ? (WxPayException) e : new WxPayException(e.getMessage(), e);
298249
} finally {
299250
httpGet.releaseConnection();
@@ -305,23 +256,28 @@ public String putV3(String url, String requestStr) throws WxPayException {
305256
HttpPut httpPut = new HttpPut(url);
306257
StringEntity entity = this.createEntry(requestStr);
307258
httpPut.setEntity(entity);
308-
httpPut.addHeader(ACCEPT, APPLICATION_JSON);
309-
httpPut.addHeader(CONTENT_TYPE, APPLICATION_JSON);
310-
String serialNumber = getWechatpaySerial(getConfig());
311-
httpPut.addHeader(WECHATPAY_SERIAL, serialNumber);
312259
return requestV3(url, httpPut);
313260
}
314261

315262
@Override
316263
public String deleteV3(String url) throws WxPayException {
317264
HttpDelete httpDelete = new HttpDelete(url);
318-
httpDelete.addHeader(ACCEPT, APPLICATION_JSON);
319-
httpDelete.addHeader(CONTENT_TYPE, APPLICATION_JSON);
320-
String serialNumber = getWechatpaySerial(getConfig());
321-
httpDelete.addHeader(WECHATPAY_SERIAL, serialNumber);
322265
return requestV3(url, httpDelete);
323266
}
324267

268+
private void configureRequest(HttpRequestBase request) {
269+
String serialNumber = getWechatPaySerial(getConfig());
270+
request.addHeader(ACCEPT, APPLICATION_JSON);
271+
request.addHeader(CONTENT_TYPE, APPLICATION_JSON);
272+
request.addHeader(WECHAT_PAY_SERIAL, serialNumber);
273+
274+
request.setConfig(RequestConfig.custom()
275+
.setConnectionRequestTimeout(this.getConfig().getHttpConnectionTimeout())
276+
.setConnectTimeout(this.getConfig().getHttpConnectionTimeout())
277+
.setSocketTimeout(this.getConfig().getHttpTimeout())
278+
.build());
279+
}
280+
325281
private CloseableHttpClient createApiV3HttpClient() throws WxPayException {
326282
CloseableHttpClient apiV3HttpClient = this.getConfig().getApiV3HttpClient();
327283
if (null == apiV3HttpClient) {
@@ -387,7 +343,6 @@ private void initSSLContext(HttpClientBuilder httpClientBuilder) throws WxPayExc
387343
new DefaultHostnameVerifier()));
388344
}
389345

390-
391346
private WxPayException convertException(JsonObject jsonObject) {
392347
//todo 这里考虑使用新的适用于V3的异常
393348
JsonElement codeElement = jsonObject.get("code");
@@ -401,13 +356,20 @@ private WxPayException convertException(JsonObject jsonObject) {
401356

402357
/**
403358
* 兼容微信支付公钥模式
404-
* @param wxPayConfig
405-
* @return
406359
*/
407-
private String getWechatpaySerial(WxPayConfig wxPayConfig) {
360+
private String getWechatPaySerial(WxPayConfig wxPayConfig) {
408361
if (StringUtils.isNotBlank(wxPayConfig.getPublicKeyId())) {
409362
return wxPayConfig.getPublicKeyId();
410363
}
364+
411365
return wxPayConfig.getVerifier().getValidCertificate().getSerialNumber().toString(16).toUpperCase();
412366
}
367+
368+
private void logRequestAndResponse(String url, String requestStr, String responseStr) {
369+
log.info("\n【请求地址】:{}\n【请求数据】:{}\n【响应数据】:{}", url, requestStr, responseStr);
370+
}
371+
372+
private void logError(String url, String requestStr, Exception e) {
373+
log.error("\n【请求地址】:{}\n【请求数据】:{}\n【异常信息】:{}", url, requestStr, e.getMessage());
374+
}
413375
}

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

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import jodd.http.ProxyInfo.ProxyType;
1010
import jodd.http.net.SSLSocketHttpConnectionProvider;
1111
import jodd.http.net.SocketHttpConnectionProvider;
12+
import lombok.extern.slf4j.Slf4j;
1213
import org.apache.commons.lang3.StringUtils;
1314
import org.apache.http.client.methods.HttpPost;
1415
import org.apache.http.client.methods.HttpRequestBase;
@@ -24,20 +25,21 @@
2425
*
2526
* @author <a href="https://github.com/binarywang">Binary Wang</a>
2627
*/
28+
@Slf4j
2729
public class WxPayServiceJoddHttpImpl extends BaseWxPayServiceImpl {
2830
@Override
2931
public byte[] postForBytes(String url, String requestStr, boolean useKey) throws WxPayException {
3032
try {
3133
HttpRequest request = this.buildHttpRequest(url, requestStr, useKey);
3234
byte[] responseBytes = request.send().bodyBytes();
3335
final String responseString = Base64.getEncoder().encodeToString(responseBytes);
34-
this.log.info("\n【请求地址】:{}\n【请求数据】:{}\n【响应数据(Base64编码后)】:{}", url, requestStr, responseString);
36+
log.info("\n【请求地址】:{}\n【请求数据】:{}\n【响应数据(Base64编码后)】:{}", url, requestStr, responseString);
3537
if (this.getConfig().isIfSaveApiData()) {
3638
wxApiData.set(new WxPayApiData(url, requestStr, responseString, null));
3739
}
3840
return responseBytes;
3941
} catch (Exception e) {
40-
this.log.error("\n【请求地址】:{}\n【请求数据】:{}\n【异常信息】:{}", url, requestStr, e.getMessage());
42+
log.error("\n【请求地址】:{}\n【请求数据】:{}\n【异常信息】:{}", url, requestStr, e.getMessage());
4143
wxApiData.set(new WxPayApiData(url, requestStr, null, e.getMessage()));
4244
throw new WxPayException(e.getMessage(), e);
4345
}
@@ -49,13 +51,13 @@ public String post(String url, String requestStr, boolean useKey) throws WxPayEx
4951
HttpRequest request = this.buildHttpRequest(url, requestStr, useKey);
5052
String responseString = this.getResponseString(request.send());
5153

52-
this.log.info("\n【请求地址】:{}\n【请求数据】:{}\n【响应数据】:{}", url, requestStr, responseString);
54+
log.info("\n【请求地址】:{}\n【请求数据】:{}\n【响应数据】:{}", url, requestStr, responseString);
5355
if (this.getConfig().isIfSaveApiData()) {
5456
wxApiData.set(new WxPayApiData(url, requestStr, responseString, null));
5557
}
5658
return responseString;
5759
} catch (Exception e) {
58-
this.log.error("\n【请求地址】:{}\n【请求数据】:{}\n【异常信息】:{}", url, requestStr, e.getMessage());
60+
log.error("\n【请求地址】:{}\n【请求数据】:{}\n【异常信息】:{}", url, requestStr, e.getMessage());
5961
wxApiData.set(new WxPayApiData(url, requestStr, null, e.getMessage()));
6062
throw new WxPayException(e.getMessage(), e);
6163
}
@@ -146,9 +148,9 @@ private HttpRequest buildHttpRequest(String url, String requestStr, boolean useK
146148

147149
private String getResponseString(HttpResponse response) throws WxPayException {
148150
try {
149-
this.log.debug("【微信服务器响应头信息】:\n{}", response.toString(false));
151+
log.debug("【微信服务器响应头信息】:\n{}", response.toString(false));
150152
} catch (NullPointerException e) {
151-
this.log.warn("HttpResponse.toString() 居然抛出空指针异常了", e);
153+
log.warn("HttpResponse.toString() 居然抛出空指针异常了", e);
152154
}
153155

154156
String responseString = response.bodyText();

0 commit comments

Comments
 (0)