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

:art: 微信支付v3代码优化重构

Binary Wang 4 лет назад
Родитель
Сommit
45a422f0f7

+ 2 - 1
weixin-java-pay/src/main/java/com/github/binarywang/wxpay/service/Applyment4SubService.java

@@ -67,7 +67,8 @@ public interface Applyment4SubService {
    * @param subMchid 特约商户号
    * @param request  修改结算账户请求对象信息
    * @throws WxPayException the wx pay exception
+   * @return
    */
-  void modifySettlement(String subMchid, ModifySettlementRequest request) throws WxPayException;
+  String modifySettlement(String subMchid, ModifySettlementRequest request) throws WxPayException;
 
 }

+ 2 - 1
weixin-java-pay/src/main/java/com/github/binarywang/wxpay/service/EcommerceService.java

@@ -174,8 +174,9 @@ public interface EcommerceService {
    *
    * @param request 关闭普通订单请求
    * @throws WxPayException the wx pay exception
+   * @return
    */
-  void closePartnerTransactions(PartnerTransactionsCloseRequest request) throws WxPayException;
+  String closePartnerTransactions(PartnerTransactionsCloseRequest request) throws WxPayException;
 
   /**
    * <pre>

+ 13 - 2
weixin-java-pay/src/main/java/com/github/binarywang/wxpay/service/WxPayService.java

@@ -11,6 +11,7 @@ import com.github.binarywang.wxpay.config.WxPayConfig;
 import com.github.binarywang.wxpay.constant.WxPayConstants;
 import com.github.binarywang.wxpay.exception.WxPayException;
 import org.apache.http.client.methods.HttpPost;
+import org.apache.http.client.methods.HttpRequestBase;
 
 import java.io.File;
 import java.io.InputStream;
@@ -90,13 +91,23 @@ public interface WxPayService {
   String postV3(String url, HttpPost httpPost) throws WxPayException;
 
   /**
+   * 发送http请求,得到响应字符串.
+   *
+   * @param url      请求地址
+   * @param httpRequest 请求信息,可以是put,post,get,delete等请求
+   * @return 返回请求结果字符串 string
+   * @throws WxPayException the wx pay exception
+   */
+  String requestV3(String url, HttpRequestBase httpRequest) throws WxPayException;
+
+  /**
    * 发送get V3请求,得到响应字符串.
    *
    * @param url 请求地址
    * @return 返回请求结果字符串 string
    * @throws WxPayException the wx pay exception
    */
-  String getV3(URI url) throws WxPayException;
+  String getV3(String url) throws WxPayException;
 
   /**
    * 发送下载 V3请求,得到响应流.
@@ -105,7 +116,7 @@ public interface WxPayService {
    * @return 返回请求响应流 input stream
    * @throws WxPayException the wx pay exception
    */
-  InputStream downloadV3(URI url) throws WxPayException;
+  InputStream downloadV3(String url) throws WxPayException;
 
   /**
    * 获取企业付款服务类.

+ 5 - 7
weixin-java-pay/src/main/java/com/github/binarywang/wxpay/service/impl/Applyment4SubServiceImpl.java

@@ -10,13 +10,11 @@ import com.google.gson.GsonBuilder;
 import lombok.RequiredArgsConstructor;
 import lombok.extern.slf4j.Slf4j;
 
-import java.net.URI;
 import java.security.cert.X509Certificate;
 
 @Slf4j
 @RequiredArgsConstructor
 public class Applyment4SubServiceImpl implements Applyment4SubService {
-
   private static final Gson GSON = new GsonBuilder().create();
   private final WxPayService payService;
 
@@ -41,28 +39,28 @@ public class Applyment4SubServiceImpl implements Applyment4SubService {
   @Override
   public ApplymentStateQueryResult queryApplyStatusByBusinessCode(String businessCode) throws WxPayException {
     String url = String.format("%s/v3/applyment4sub/applyment/business_code/%s", this.payService.getPayBaseUrl(), businessCode);
-    String result = payService.getV3(URI.create(url));
+    String result = payService.getV3(url);
     return GSON.fromJson(result, ApplymentStateQueryResult.class);
   }
 
   @Override
   public ApplymentStateQueryResult queryApplyStatusByApplymentId(String applymentId) throws WxPayException {
     String url = String.format("%s/v3/applyment4sub/applyment/applyment_id/%s", this.payService.getPayBaseUrl(), applymentId);
-    String result = payService.getV3(URI.create(url));
+    String result = payService.getV3(url);
     return GSON.fromJson(result, ApplymentStateQueryResult.class);
   }
 
   @Override
   public SettlementInfoResult querySettlementBySubMchid(String subMchid) throws WxPayException {
     String url = String.format("%s/v3/apply4sub/sub_merchants/%s/settlement", this.payService.getPayBaseUrl(), subMchid);
-    String result = payService.getV3(URI.create(url));
+    String result = payService.getV3(url);
     return GSON.fromJson(result, SettlementInfoResult.class);
   }
 
   @Override
-  public void modifySettlement(String subMchid,ModifySettlementRequest request) throws WxPayException {
+  public String modifySettlement(String subMchid, ModifySettlementRequest request) throws WxPayException {
     String url = String.format("%s/v3/apply4sub/sub_merchants/%s/modify-settlement", this.payService.getPayBaseUrl(), subMchid);
     encryptFiled(request);
-    String result = payService.postV3WithWechatpaySerial(url, GSON.toJson(request));
+    return payService.postV3WithWechatpaySerial(url, GSON.toJson(request));
   }
 }

+ 24 - 27
weixin-java-pay/src/main/java/com/github/binarywang/wxpay/service/impl/EcommerceServiceImpl.java

@@ -44,14 +44,14 @@ public class EcommerceServiceImpl implements EcommerceService {
   @Override
   public ApplymentsStatusResult queryApplyStatusByApplymentId(String applymentId) throws WxPayException {
     String url = String.format("%s/v3/ecommerce/applyments/%s", this.payService.getPayBaseUrl(), applymentId);
-    String result = this.payService.getV3(URI.create(url));
+    String result = this.payService.getV3(url);
     return GSON.fromJson(result, ApplymentsStatusResult.class);
   }
 
   @Override
   public ApplymentsStatusResult queryApplyStatusByOutRequestNo(String outRequestNo) throws WxPayException {
     String url = String.format("%s/v3/ecommerce/applyments/out-request-no/%s", this.payService.getPayBaseUrl(), outRequestNo);
-    String result = this.payService.getV3(URI.create(url));
+    String result = this.payService.getV3(url);
     return GSON.fromJson(result, ApplymentsStatusResult.class);
   }
 
@@ -96,7 +96,7 @@ public class EcommerceServiceImpl implements EcommerceService {
   @Override
   public CombineTransactionsResult queryCombineTransactions(String outTradeNo) throws WxPayException {
     String url = String.format("%s/v3/combine-transactions/out-trade-no/%s", this.payService.getPayBaseUrl(), outTradeNo);
-    String response = this.payService.getV3(URI.create(url));
+    String response = this.payService.getV3(url);
     return GSON.fromJson(response, CombineTransactionsResult.class);
   }
 
@@ -145,46 +145,41 @@ public class EcommerceServiceImpl implements EcommerceService {
       url = String.format("%s/v3/pay/partner/transactions/id/%s", this.payService.getPayBaseUrl(), request.getTransactionId());
     }
     String query = String.format("?sp_mchid=%s&sub_mchid=%s", request.getSpMchid(), request.getSubMchid());
-    URI uri = URI.create(url + query);
-    String response = this.payService.getV3(uri);
+    String response = this.payService.getV3(url + query);
     return GSON.fromJson(response, PartnerTransactionsResult.class);
   }
 
   @Override
-  public void closePartnerTransactions(PartnerTransactionsCloseRequest request) throws WxPayException {
+  public String closePartnerTransactions(PartnerTransactionsCloseRequest request) throws WxPayException {
     String url = String.format("%s/v3/pay/partner/transactions/out-trade-no/%s/close", this.payService.getPayBaseUrl(), request.getOutTradeNo());
-    String response = this.payService.postV3(url, GSON.toJson(request));
+    return this.payService.postV3(url, GSON.toJson(request));
   }
 
   @Override
   public FundBalanceResult spNowBalance(SpAccountTypeEnum accountType) throws WxPayException {
     String url = String.format("%s/v3/merchant/fund/balance/%s", this.payService.getPayBaseUrl(), accountType);
-    URI uri = URI.create(url);
-    String response = this.payService.getV3(uri);
+    String response = this.payService.getV3(url);
     return GSON.fromJson(response, FundBalanceResult.class);
   }
 
   @Override
   public FundBalanceResult spDayEndBalance(SpAccountTypeEnum accountType, String date) throws WxPayException {
     String url = String.format("%s/v3/merchant/fund/dayendbalance/%s?date=%s", this.payService.getPayBaseUrl(), accountType, date);
-    URI uri = URI.create(url);
-    String response = this.payService.getV3(uri);
+    String response = this.payService.getV3(url);
     return GSON.fromJson(response, FundBalanceResult.class);
   }
 
   @Override
   public FundBalanceResult subNowBalance(String subMchid) throws WxPayException {
     String url = String.format("%s/v3/ecommerce/fund/balance/%s", this.payService.getPayBaseUrl(), subMchid);
-    URI uri = URI.create(url);
-    String response = this.payService.getV3(uri);
+    String response = this.payService.getV3(url);
     return GSON.fromJson(response, FundBalanceResult.class);
   }
 
   @Override
   public FundBalanceResult subDayEndBalance(String subMchid, String date) throws WxPayException {
     String url = String.format("%s/v3/ecommerce/fund/enddaybalance/%s?date=%s", this.payService.getPayBaseUrl(), subMchid, date);
-    URI uri = URI.create(url);
-    String response = this.payService.getV3(uri);
+    String response = this.payService.getV3(url);
     return GSON.fromJson(response, FundBalanceResult.class);
   }
 
@@ -200,7 +195,7 @@ public class EcommerceServiceImpl implements EcommerceService {
   public ProfitSharingResult queryProfitSharing(ProfitSharingQueryRequest request) throws WxPayException {
     String url = String.format("%s/v3/ecommerce/profitsharing/orders?sub_mchid=%s&transaction_id=%s&out_order_no=%s",
       this.payService.getPayBaseUrl(), request.getSubMchid(), request.getTransactionId(), request.getOutOrderNo());
-    String response = this.payService.getV3(URI.create(url));
+    String response = this.payService.getV3(url);
     return GSON.fromJson(response, ProfitSharingResult.class);
   }
 
@@ -239,7 +234,7 @@ public class EcommerceServiceImpl implements EcommerceService {
       url = String.format("%s/v3/ecommerce/profitsharing/returnorders?sub_mchid=%s&order_id=%s&out_return_no=%s",
         this.payService.getPayBaseUrl(), subMchid, orderId, outReturnNo);
     }
-    String response = this.payService.getV3(URI.create(url));
+    String response = this.payService.getV3(url);
     return GSON.fromJson(response, ReturnOrdersResult.class);
   }
 
@@ -260,14 +255,14 @@ public class EcommerceServiceImpl implements EcommerceService {
   @Override
   public RefundQueryResult queryRefundByRefundId(String subMchid, String refundId) throws WxPayException {
     String url = String.format("%s/v3/ecommerce/refunds/id/%s?sub_mchid=%s", this.payService.getPayBaseUrl(), refundId, subMchid);
-    String response = this.payService.getV3(URI.create(url));
+    String response = this.payService.getV3(url);
     return GSON.fromJson(response, RefundQueryResult.class);
   }
 
   @Override
   public RefundQueryResult queryRefundByOutRefundNo(String subMchid, String outRefundNo) throws WxPayException {
     String url = String.format("%s/v3/ecommerce/refunds/out-refund-no/%s?sub_mchid=%s", this.payService.getPayBaseUrl(), outRefundNo, subMchid);
-    String response = this.payService.getV3(URI.create(url));
+    String response = this.payService.getV3(url);
     return GSON.fromJson(response, RefundQueryResult.class);
   }
 
@@ -309,14 +304,14 @@ public class EcommerceServiceImpl implements EcommerceService {
   @Override
   public SubWithdrawStatusResult querySubWithdrawByOutRequestNo(String subMchid, String outRequestNo) throws WxPayException {
     String url = String.format("%s/v3/ecommerce/fund/withdraw/out-request-no/%s?sub_mchid=%s", this.payService.getPayBaseUrl(), outRequestNo, subMchid);
-    String response = this.payService.getV3(URI.create(url));
+    String response = this.payService.getV3(url);
     return GSON.fromJson(response, SubWithdrawStatusResult.class);
   }
 
   @Override
   public SpWithdrawStatusResult querySpWithdrawByOutRequestNo(String outRequestNo) throws WxPayException {
     String url = String.format("%s/v3/merchant/fund/withdraw/out-request-no/%s", this.payService.getPayBaseUrl(), outRequestNo);
-    String response = this.payService.getV3(URI.create(url));
+    String response = this.payService.getV3(url);
     return GSON.fromJson(response, SpWithdrawStatusResult.class);
   }
 
@@ -330,27 +325,27 @@ public class EcommerceServiceImpl implements EcommerceService {
   @Override
   public SettlementResult querySettlement(String subMchid) throws WxPayException {
     String url = String.format("%s/v3/apply4sub/sub_merchants/%s/settlement", this.payService.getPayBaseUrl(), subMchid);
-    String response = this.payService.getV3(URI.create(url));
+    String response = this.payService.getV3(url);
     return GSON.fromJson(response, SettlementResult.class);
   }
 
   @Override
   public TradeBillResult applyBill(TradeBillRequest request) throws WxPayException {
     String url = String.format("%s/v3/bill/tradebill?%s", this.payService.getPayBaseUrl(), this.parseURLPair(request));
-    String response = this.payService.getV3(URI.create(url));
+    String response = this.payService.getV3(url);
     return GSON.fromJson(response, TradeBillResult.class);
   }
 
   @Override
   public FundBillResult applyFundBill(FundBillTypeEnum billType, FundBillRequest request) throws WxPayException {
     String url = String.format(billType.getUrl(), this.payService.getPayBaseUrl(), this.parseURLPair(request));
-    String response = this.payService.getV3(URI.create(url));
+    String response = this.payService.getV3(url);
     return GSON.fromJson(response, FundBillResult.class);
   }
 
   @Override
   public InputStream downloadBill(String url) throws WxPayException {
-    return this.payService.downloadV3(URI.create(url));
+    return this.payService.downloadV3(url);
   }
 
   /**
@@ -380,8 +375,10 @@ public class EcommerceServiceImpl implements EcommerceService {
     StringBuilder sb = new StringBuilder();
     while (it.hasNext()) {
       Map.Entry<Object, Object> e = it.next();
-      if ( !"class".equals(e.getKey()) && e.getValue() != null)
-        sb.append(CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, String.valueOf(e.getKey()))).append("=").append(e.getValue()).append("&");
+      if ( !"class".equals(e.getKey()) && e.getValue() != null) {
+        sb.append(CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, String.valueOf(e.getKey())))
+          .append("=").append(e.getValue()).append("&");
+      }
     }
     return sb.deleteCharAt(sb.length() - 1).toString();
   }

+ 32 - 37
weixin-java-pay/src/main/java/com/github/binarywang/wxpay/service/impl/PayScoreServiceImpl.java

@@ -1,16 +1,5 @@
 package com.github.binarywang.wxpay.service.impl;
 
-import java.io.IOException;
-import java.net.URISyntaxException;
-import java.nio.charset.StandardCharsets;
-import java.security.GeneralSecurityException;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Objects;
-
-import org.apache.commons.lang3.StringUtils;
-import org.apache.http.client.utils.URIBuilder;
-
 import com.github.binarywang.wxpay.bean.ecommerce.SignatureHeader;
 import com.github.binarywang.wxpay.bean.payscore.PayScoreNotifyData;
 import com.github.binarywang.wxpay.bean.payscore.UserAuthorizationStatusNotifyResult;
@@ -23,9 +12,18 @@ import com.github.binarywang.wxpay.service.WxPayService;
 import com.github.binarywang.wxpay.v3.util.AesUtils;
 import com.google.gson.Gson;
 import com.google.gson.GsonBuilder;
-
 import lombok.RequiredArgsConstructor;
 import me.chanjar.weixin.common.util.json.WxGsonBuilder;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.http.client.utils.URIBuilder;
+
+import java.io.IOException;
+import java.net.URISyntaxException;
+import java.nio.charset.StandardCharsets;
+import java.security.GeneralSecurityException;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Objects;
 
 /**
  * @author doger.wang
@@ -33,7 +31,6 @@ import me.chanjar.weixin.common.util.json.WxGsonBuilder;
  */
 @RequiredArgsConstructor
 public class PayScoreServiceImpl implements PayScoreService {
-	
   private static final Gson GSON = new GsonBuilder().create();
   private final WxPayService payService;
 
@@ -44,23 +41,23 @@ public class PayScoreServiceImpl implements PayScoreService {
     request.setAppid(config.getAppId());
     request.setServiceId(config.getServiceId());
     String permissionNotifyUrl = config.getPayScorePermissionNotifyUrl();
-    if (StringUtils.isBlank(permissionNotifyUrl)){
+    if (StringUtils.isBlank(permissionNotifyUrl)) {
       throw new WxPayException("授权回调地址未配置");
     }
     String authorizationCode = request.getAuthorizationCode();
-    if (StringUtils.isBlank(authorizationCode)){
+    if (StringUtils.isBlank(authorizationCode)) {
       throw new WxPayException("authorizationCode不允许为空");
     }
     request.setNotifyUrl(permissionNotifyUrl);
     String result = this.payService.postV3(url, request.toJson());
-   return WxPayScoreResult.fromJson(result);
+    return WxPayScoreResult.fromJson(result);
 
   }
 
   @Override
   public WxPayScoreResult permissionsQueryByAuthorizationCode(String authorizationCode) throws WxPayException {
     WxPayConfig config = this.payService.getConfig();
-    if (StringUtils.isBlank(authorizationCode)){
+    if (StringUtils.isBlank(authorizationCode)) {
       throw new WxPayException("authorizationCode不允许为空");
     }
     String url = String.format("%s/v3/payscore/permissions/authorization-code/%s", this.payService.getPayBaseUrl(), authorizationCode);
@@ -73,7 +70,7 @@ public class PayScoreServiceImpl implements PayScoreService {
 
     uriBuilder.setParameter("service_id", config.getServiceId());
     try {
-      String result = payService.getV3(uriBuilder.build());
+      String result = payService.getV3(uriBuilder.build().toString());
       return WxPayScoreResult.fromJson(result);
     } catch (URISyntaxException e) {
       throw new WxPayException("未知异常!", e);
@@ -82,9 +79,9 @@ public class PayScoreServiceImpl implements PayScoreService {
   }
 
   @Override
-  public WxPayScoreResult permissionsTerminateByAuthorizationCode(String authorizationCode,String reason) throws WxPayException {
+  public WxPayScoreResult permissionsTerminateByAuthorizationCode(String authorizationCode, String reason) throws WxPayException {
     WxPayConfig config = this.payService.getConfig();
-    if (StringUtils.isBlank(authorizationCode)){
+    if (StringUtils.isBlank(authorizationCode)) {
       throw new WxPayException("authorizationCode不允许为空");
     }
     String url = String.format("%s/v3/payscore/permissions/authorization-code/%s/terminate", this.payService.getPayBaseUrl(), authorizationCode);
@@ -99,7 +96,7 @@ public class PayScoreServiceImpl implements PayScoreService {
   @Override
   public WxPayScoreResult permissionsQueryByOpenId(String openId) throws WxPayException {
     WxPayConfig config = this.payService.getConfig();
-    if (StringUtils.isBlank(openId)){
+    if (StringUtils.isBlank(openId)) {
       throw new WxPayException("openId不允许为空");
     }
     String url = String.format("%s/v3/payscore/permissions/openid/%s", this.payService.getPayBaseUrl(), openId);
@@ -113,7 +110,7 @@ public class PayScoreServiceImpl implements PayScoreService {
     uriBuilder.setParameter("appid", config.getAppId());
     uriBuilder.setParameter("service_id", config.getServiceId());
     try {
-      String result = payService.getV3(uriBuilder.build());
+      String result = payService.getV3(uriBuilder.build().toString());
       return WxPayScoreResult.fromJson(result);
     } catch (URISyntaxException e) {
       throw new WxPayException("未知异常!", e);
@@ -124,7 +121,7 @@ public class PayScoreServiceImpl implements PayScoreService {
   @Override
   public WxPayScoreResult permissionsTerminateByOpenId(String openId, String reason) throws WxPayException {
     WxPayConfig config = this.payService.getConfig();
-    if (StringUtils.isBlank(openId)){
+    if (StringUtils.isBlank(openId)) {
       throw new WxPayException("openId不允许为空");
     }
     String url = String.format("%s/v3/payscore/permissions/openid/%s/terminate", this.payService.getPayBaseUrl(), openId);
@@ -191,7 +188,7 @@ public class PayScoreServiceImpl implements PayScoreService {
     uriBuilder.setParameter("service_id", config.getServiceId());
     uriBuilder.setParameter("appid", config.getAppId());
     try {
-      String result = payService.getV3(uriBuilder.build());
+      String result = payService.getV3(uriBuilder.build().toString());
       return WxPayScoreResult.fromJson(result);
     } catch (URISyntaxException e) {
       throw new WxPayException("未知异常!", e);
@@ -257,17 +254,17 @@ public class PayScoreServiceImpl implements PayScoreService {
     String result = payService.postV3(url, request.toJson());
     return WxPayScoreResult.fromJson(result);
   }
-  
+
   @Override
   public UserAuthorizationStatusNotifyResult parseUserAuthorizationStatusNotifyResult(String notifyData, SignatureHeader header) throws WxPayException {
-    PayScoreNotifyData response = parseNotifyData(notifyData,header);
+    PayScoreNotifyData response = parseNotifyData(notifyData, header);
     PayScoreNotifyData.Resource resource = response.getResource();
     String cipherText = resource.getCipherText();
     String associatedData = resource.getAssociatedData();
     String nonce = resource.getNonce();
     String apiV3Key = this.payService.getConfig().getApiV3Key();
     try {
-      String result = AesUtils.decryptToString(associatedData, nonce,cipherText, apiV3Key);
+      String result = AesUtils.decryptToString(associatedData, nonce, cipherText, apiV3Key);
       UserAuthorizationStatusNotifyResult notifyResult = GSON.fromJson(result, UserAuthorizationStatusNotifyResult.class);
       notifyResult.setRawData(response);
       return notifyResult;
@@ -277,10 +274,10 @@ public class PayScoreServiceImpl implements PayScoreService {
   }
 
   @Override
-  public PayScoreNotifyData parseNotifyData(String data,SignatureHeader header) throws WxPayException {
-	if(Objects.nonNull(header) && !this.verifyNotifySign(header, data)){
-	  throw new WxPayException("非法请求,头部信息验证失败");
-	}
+  public PayScoreNotifyData parseNotifyData(String data, SignatureHeader header) throws WxPayException {
+    if (Objects.nonNull(header) && !this.verifyNotifySign(header, data)) {
+      throw new WxPayException("非法请求,头部信息验证失败");
+    }
     return GSON.fromJson(data, PayScoreNotifyData.class);
   }
 
@@ -297,18 +294,16 @@ public class PayScoreServiceImpl implements PayScoreService {
       throw new WxPayException("解析报文异常!", e);
     }
   }
-  
+
   /**
    * 校验通知签名
+   *
    * @param header 通知头信息
-   * @param data 通知数据
+   * @param data   通知数据
    * @return true:校验通过 false:校验不通过
    */
   private boolean verifyNotifySign(SignatureHeader header, String data) {
-    String beforeSign = String.format("%s\n%s\n%s\n",
-      header.getTimeStamp(),
-      header.getNonce(),
-      data);
+    String beforeSign = String.format("%s%n%s%n%s%n", header.getTimeStamp(), header.getNonce(), data);
     return payService.getConfig().getVerifier().verify(header.getSerialNo(),
       beforeSign.getBytes(StandardCharsets.UTF_8), header.getSigned());
   }

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

@@ -16,6 +16,7 @@ import org.apache.http.client.config.RequestConfig;
 import org.apache.http.client.methods.CloseableHttpResponse;
 import org.apache.http.client.methods.HttpGet;
 import org.apache.http.client.methods.HttpPost;
+import org.apache.http.client.methods.HttpRequestBase;
 import org.apache.http.conn.ssl.DefaultHostnameVerifier;
 import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
 import org.apache.http.entity.ContentType;
@@ -28,7 +29,6 @@ import org.apache.http.util.EntityUtils;
 
 import javax.net.ssl.SSLContext;
 import java.io.InputStream;
-import java.net.URI;
 import java.nio.charset.StandardCharsets;
 import java.util.Base64;
 
@@ -104,7 +104,7 @@ public class WxPayServiceApacheHttpImpl extends BaseWxPayServiceImpl {
       String responseString;
       if (response.getEntity() == null) {
         responseString = null;
-      }else {
+      } else {
         responseString = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
       }
       if (HttpStatus.SC_OK == statusCode || HttpStatus.SC_NO_CONTENT == statusCode) {
@@ -117,7 +117,7 @@ public class WxPayServiceApacheHttpImpl extends BaseWxPayServiceImpl {
       }
     } catch (Exception e) {
       this.log.error("\n【请求地址】:{}\n【请求数据】:{}\n【异常信息】:{}", url, requestStr, e.getMessage());
-      throw (e instanceof WxPayException) ? (WxPayException)e : new WxPayException(e.getMessage(), e);
+      throw (e instanceof WxPayException) ? (WxPayException) e : new WxPayException(e.getMessage(), e);
     } finally {
       httpPost.releaseConnection();
     }
@@ -153,7 +153,7 @@ public class WxPayServiceApacheHttpImpl extends BaseWxPayServiceImpl {
     } catch (Exception e) {
       this.log.error("\n【请求地址】:{}\n【请求数据】:{}\n【异常信息】:{}", url, requestStr, e.getMessage());
       e.printStackTrace();
-      throw (e instanceof WxPayException) ? (WxPayException)e : new WxPayException(e.getMessage(), e);
+      throw (e instanceof WxPayException) ? (WxPayException) e : new WxPayException(e.getMessage(), e);
     } finally {
       httpPost.releaseConnection();
     }
@@ -161,22 +161,26 @@ public class WxPayServiceApacheHttpImpl extends BaseWxPayServiceImpl {
 
   @Override
   public String postV3(String url, HttpPost httpPost) throws WxPayException {
+    return this.requestV3(url, httpPost);
+  }
 
-    httpPost.setConfig(RequestConfig.custom()
+  @Override
+  public String requestV3(String url, HttpRequestBase httpRequest) throws WxPayException {
+    httpRequest.setConfig(RequestConfig.custom()
       .setConnectionRequestTimeout(this.getConfig().getHttpConnectionTimeout())
       .setConnectTimeout(this.getConfig().getHttpConnectionTimeout())
       .setSocketTimeout(this.getConfig().getHttpTimeout())
       .build());
 
     CloseableHttpClient httpClient = this.createApiV3HttpClient();
-    try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
+    try (CloseableHttpResponse response = httpClient.execute(httpRequest)) {
       //v3已经改为通过状态码判断200 204 成功
       int statusCode = response.getStatusLine().getStatusCode();
       //post方法有可能会没有返回值的情况
       String responseString;
       if (response.getEntity() == null) {
         responseString = null;
-      }else {
+      } else {
         responseString = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
       }
       if (HttpStatus.SC_OK == statusCode || HttpStatus.SC_NO_CONTENT == statusCode) {
@@ -189,40 +193,22 @@ public class WxPayServiceApacheHttpImpl extends BaseWxPayServiceImpl {
       }
     } catch (Exception e) {
       this.log.error("\n【请求地址】:{}\n【异常信息】:{}", url, e.getMessage());
-      throw (e instanceof WxPayException) ? (WxPayException)e : new WxPayException(e.getMessage(), e);
+      throw (e instanceof WxPayException) ? (WxPayException) e : new WxPayException(e.getMessage(), e);
     } finally {
-      httpPost.releaseConnection();
+      httpRequest.releaseConnection();
     }
   }
 
   @Override
-  public String getV3(URI url) throws WxPayException {
-    CloseableHttpClient httpClient = this.createApiV3HttpClient();
+  public String getV3(String url) throws WxPayException {
     HttpGet httpGet = new HttpGet(url);
     httpGet.addHeader("Accept", "application/json");
     httpGet.addHeader("Content-Type", "application/json");
-    try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
-      //v3已经改为通过状态码判断200 204 成功
-      int statusCode = response.getStatusLine().getStatusCode();
-      String responseString = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
-      if (HttpStatus.SC_OK == statusCode || HttpStatus.SC_NO_CONTENT == statusCode) {
-        this.log.info("\n【请求地址】:{}\n【响应数据】:{}", url, responseString);
-        return responseString;
-      } else {
-        //有错误提示信息返回
-        JsonObject jsonObject = GsonParser.parse(responseString);
-        throw convertException(jsonObject);
-      }
-    } catch (Exception e) {
-      this.log.error("\n【请求地址】:{}\n【异常信息】:{}", url, e.getMessage());
-      throw (e instanceof WxPayException) ? (WxPayException)e : new WxPayException(e.getMessage(), e);
-    } finally {
-      httpGet.releaseConnection();
-    }
+    return this.requestV3(url.toString(), httpGet);
   }
 
   @Override
-  public InputStream downloadV3(URI url) throws WxPayException {
+  public InputStream downloadV3(String url) throws WxPayException {
     CloseableHttpClient httpClient = this.createApiV3HttpClient();
     HttpGet httpGet = new HttpGet(url);
     httpGet.addHeader("Accept", ContentType.WILDCARD.getMimeType());
@@ -240,7 +226,7 @@ public class WxPayServiceApacheHttpImpl extends BaseWxPayServiceImpl {
       }
     } catch (Exception e) {
       this.log.error("\n【请求地址】:{}\n【异常信息】:{}", url, e.getMessage());
-      throw (e instanceof WxPayException) ? (WxPayException)e : new WxPayException(e.getMessage(), e);
+      throw (e instanceof WxPayException) ? (WxPayException) e : new WxPayException(e.getMessage(), e);
     } finally {
       httpGet.releaseConnection();
     }

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

@@ -11,10 +11,10 @@ import jodd.http.net.SSLSocketHttpConnectionProvider;
 import jodd.http.net.SocketHttpConnectionProvider;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.http.client.methods.HttpPost;
+import org.apache.http.client.methods.HttpRequestBase;
 
 import javax.net.ssl.SSLContext;
 import java.io.InputStream;
-import java.net.URI;
 import java.nio.charset.StandardCharsets;
 import java.util.Base64;
 
@@ -77,12 +77,17 @@ public class WxPayServiceJoddHttpImpl extends BaseWxPayServiceImpl {
   }
 
   @Override
-  public String getV3(URI url) throws WxPayException {
+  public String requestV3(String url, HttpRequestBase httpRequest) throws WxPayException {
     return null;
   }
 
   @Override
-  public InputStream downloadV3(URI url) throws WxPayException {
+  public String getV3(String url) throws WxPayException {
+    return null;
+  }
+
+  @Override
+  public InputStream downloadV3(String url) throws WxPayException {
     return null;
   }