From c8d21e3fbac9418c4fae2cf64557852720f35c39 Mon Sep 17 00:00:00 2001 From: BinaryWang Date: Fri, 19 Aug 2016 09:45:33 +0800 Subject: [PATCH] =?UTF-8?q?=E6=A0=BC=E5=BC=8F=E5=8C=96=E4=B8=8D=E8=A7=84?= =?UTF-8?q?=E8=8C=83=E7=9A=84=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mp/api/impl/WxMpPayServiceImpl.java | 275 +++++++++++------- 1 file changed, 174 insertions(+), 101 deletions(-) diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java index 81638b7a..ce7f9517 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java @@ -26,12 +26,15 @@ import java.util.TreeMap; /** * Created by Binary Wang on 2016/7/28. + * * @author binarywang (https://github.com/binarywang) */ public class WxMpPayServiceImpl implements WxMpPayService { private final Logger log = LoggerFactory.getLogger(WxMpPayServiceImpl.class); - + private final String[] REQUIRED_ORDER_PARAMETERS = new String[]{"appid", + "mch_id", "body", "out_trade_no", "total_fee", "spbill_create_ip", + "notify_url", "trade_type"}; private HttpHost httpProxy; private WxMpServiceImpl wxMpService; @@ -41,10 +44,14 @@ public class WxMpPayServiceImpl implements WxMpPayService { } @Override - public WxMpPrepayIdResult getPrepayId(String openId, String outTradeNo, double amt, String body, String tradeType, String ip, String callbackUrl) { + public WxMpPrepayIdResult getPrepayId(String openId, String outTradeNo, + double amt, String body, String tradeType, String ip, + String callbackUrl) { Map packageParams = new HashMap<>(); - packageParams.put("appid", this.wxMpService.getWxMpConfigStorage().getAppId()); - packageParams.put("mch_id", this.wxMpService.getWxMpConfigStorage().getPartnerId()); + packageParams.put("appid", + this.wxMpService.getWxMpConfigStorage().getAppId()); + packageParams.put("mch_id", + this.wxMpService.getWxMpConfigStorage().getPartnerId()); packageParams.put("body", body); packageParams.put("out_trade_no", outTradeNo); packageParams.put("total_fee", (int) (amt * 100) + ""); @@ -58,62 +65,81 @@ public class WxMpPayServiceImpl implements WxMpPayService { @Override public WxMpPrepayIdResult getPrepayId(final Map parameters) { - String nonce_str = System.currentTimeMillis() + ""; - final SortedMap packageParams = new TreeMap<>(parameters); - packageParams.put("appid", this.wxMpService.getWxMpConfigStorage().getAppId()); - packageParams.put("mch_id", this.wxMpService.getWxMpConfigStorage().getPartnerId()); - packageParams.put("nonce_str", nonce_str); + packageParams.put("appid", + this.wxMpService.getWxMpConfigStorage().getAppId()); + packageParams.put("mch_id", + this.wxMpService.getWxMpConfigStorage().getPartnerId()); + packageParams.put("nonce_str", System.currentTimeMillis() + ""); checkParameters(packageParams); - String sign = WxCryptUtil.createSign(packageParams, this.wxMpService.getWxMpConfigStorage().getPartnerKey()); + String sign = WxCryptUtil.createSign(packageParams, + this.wxMpService.getWxMpConfigStorage().getPartnerKey()); packageParams.put("sign", sign); StringBuilder request = new StringBuilder(""); for (Map.Entry para : packageParams.entrySet()) { - request.append(String.format("<%s>%s", para.getKey(), para.getValue(), para.getKey())); + request.append(String.format("<%s>%s", para.getKey(), + para.getValue(), para.getKey())); } + request.append(""); - HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/pay/unifiedorder"); + HttpPost httpPost = new HttpPost( + "https://api.mch.weixin.qq.com/pay/unifiedorder"); if (this.httpProxy != null) { - RequestConfig config = RequestConfig.custom().setProxy(this.httpProxy).build(); + RequestConfig config = RequestConfig.custom().setProxy(this.httpProxy) + .build(); httpPost.setConfig(config); } StringEntity entity = new StringEntity(request.toString(), Consts.UTF_8); httpPost.setEntity(entity); - try(CloseableHttpResponse response = this.wxMpService.getHttpclient().execute(httpPost)) { - String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response); + try (CloseableHttpResponse response = this.wxMpService.getHttpclient() + .execute(httpPost)) { + String responseContent = Utf8ResponseHandler.INSTANCE + .handleResponse(response); XStream xstream = XStreamInitializer.getInstance(); xstream.alias("xml", WxMpPrepayIdResult.class); return (WxMpPrepayIdResult) xstream.fromXML(responseContent); } catch (IOException e) { - throw new RuntimeException("Failed to get prepay id due to IO exception.", e); - }finally { + throw new RuntimeException("Failed to get prepay id due to IO exception.", + e); + } finally { httpPost.releaseConnection(); } } - private final String[] REQUIRED_ORDER_PARAMETERS = new String[] { "appid", "mch_id", "body", "out_trade_no", - "total_fee", "spbill_create_ip", "notify_url","trade_type"}; - private void checkParameters(Map parameters) { for (String para : this.REQUIRED_ORDER_PARAMETERS) { - if (!parameters.containsKey(para)) - throw new IllegalArgumentException("Reqiured argument '" + para + "' is missing."); + if (!parameters.containsKey(para)) { + throw new IllegalArgumentException( + "Reqiured argument '" + para + "' is missing."); + } + } + + if ("JSAPI".equals(parameters.get("trade_type")) + && !parameters.containsKey("openid")) { + throw new IllegalArgumentException( + "Reqiured argument 'openid' is missing when trade_type is 'JSAPI'."); + } + + if ("NATIVE".equals(parameters.get("trade_type")) + && !parameters.containsKey("product_id")) { + throw new IllegalArgumentException( + "Reqiured argument 'product_id' is missing when trade_type is 'NATIVE'."); } - if ("JSAPI".equals(parameters.get("trade_type")) && !parameters.containsKey("openid")) - throw new IllegalArgumentException("Reqiured argument 'openid' is missing when trade_type is 'JSAPI'."); - if ("NATIVE".equals(parameters.get("trade_type")) && !parameters.containsKey("product_id")) - throw new IllegalArgumentException("Reqiured argument 'product_id' is missing when trade_type is 'NATIVE'."); } @Override - public Map getJsapiPayInfo(String openId,String outTradeNo, double amt, String body,String ip, String callbackUrl) throws WxErrorException { + public Map getJsapiPayInfo(String openId, String outTradeNo, + double amt, String body, String ip, String callbackUrl) + throws WxErrorException { Map packageParams = new HashMap<>(); - packageParams.put("appid", this.wxMpService.getWxMpConfigStorage().getAppId()); - packageParams.put("mch_id", this.wxMpService.getWxMpConfigStorage().getPartnerId()); + packageParams.put("appid", + this.wxMpService.getWxMpConfigStorage().getAppId()); + packageParams.put("mch_id", + this.wxMpService.getWxMpConfigStorage().getPartnerId()); packageParams.put("body", body); packageParams.put("out_trade_no", outTradeNo); packageParams.put("total_fee", (int) (amt * 100) + ""); @@ -126,10 +152,14 @@ public class WxMpPayServiceImpl implements WxMpPayService { } @Override - public Map getNativePayInfo(String productId,String outTradeNo, double amt, String body,String ip, String callbackUrl) throws WxErrorException{ + public Map getNativePayInfo(String productId, + String outTradeNo, double amt, String body, String ip, String callbackUrl) + throws WxErrorException { Map packageParams = new HashMap<>(); - packageParams.put("appid", this.wxMpService.getWxMpConfigStorage().getAppId()); - packageParams.put("mch_id", this.wxMpService.getWxMpConfigStorage().getPartnerId()); + packageParams.put("appid", + this.wxMpService.getWxMpConfigStorage().getAppId()); + packageParams.put("mch_id", + this.wxMpService.getWxMpConfigStorage().getPartnerId()); packageParams.put("body", body); packageParams.put("out_trade_no", outTradeNo); packageParams.put("total_fee", (int) (amt * 100) + ""); @@ -142,24 +172,28 @@ public class WxMpPayServiceImpl implements WxMpPayService { } @Override - public Map getPayInfo(Map parameters) throws WxErrorException { + public Map getPayInfo(Map parameters) + throws WxErrorException { WxMpPrepayIdResult wxMpPrepayIdResult = getPrepayId(parameters); if (!"SUCCESS".equalsIgnoreCase(wxMpPrepayIdResult.getReturn_code()) - ||!"SUCCESS".equalsIgnoreCase(wxMpPrepayIdResult.getResult_code())) { + || !"SUCCESS".equalsIgnoreCase(wxMpPrepayIdResult.getResult_code())) { WxError error = new WxError(); error.setErrorCode(-1); - error.setErrorMsg("return_code:" + wxMpPrepayIdResult.getReturn_code() + - ";return_msg:" + wxMpPrepayIdResult.getReturn_msg() + - ";result_code:" + wxMpPrepayIdResult.getResult_code() + - ";err_code" + wxMpPrepayIdResult.getErr_code() + - ";err_code_des" + wxMpPrepayIdResult.getErr_code_des()); + error.setErrorMsg("return_code:" + wxMpPrepayIdResult.getReturn_code() + + ";return_msg:" + wxMpPrepayIdResult.getReturn_msg() + + ";result_code:" + wxMpPrepayIdResult.getResult_code() + ";err_code" + + wxMpPrepayIdResult.getErr_code() + ";err_code_des" + + wxMpPrepayIdResult.getErr_code_des()); throw new WxErrorException(error); } String prepayId = wxMpPrepayIdResult.getPrepay_id(); if (prepayId == null || prepayId.equals("")) { - throw new RuntimeException(String.format("Failed to get prepay id due to error code '%s'(%s).", wxMpPrepayIdResult.getErr_code(), wxMpPrepayIdResult.getErr_code_des())); + throw new RuntimeException( + String.format("Failed to get prepay id due to error code '%s'(%s).", + wxMpPrepayIdResult.getErr_code(), + wxMpPrepayIdResult.getErr_code_des())); } Map payInfo = new HashMap<>(); @@ -169,52 +203,67 @@ public class WxMpPayServiceImpl implements WxMpPayService { payInfo.put("nonceStr", System.currentTimeMillis() + ""); payInfo.put("package", "prepay_id=" + prepayId); payInfo.put("signType", "MD5"); - if("NATIVE".equals(parameters.get("trade_type"))){ + if ("NATIVE".equals(parameters.get("trade_type"))) { payInfo.put("codeUrl", wxMpPrepayIdResult.getCode_url()); } - String finalSign = WxCryptUtil.createSign(payInfo, this.wxMpService.getWxMpConfigStorage().getPartnerKey()); + String finalSign = WxCryptUtil.createSign(payInfo, + this.wxMpService.getWxMpConfigStorage().getPartnerKey()); payInfo.put("paySign", finalSign); return payInfo; } @Override - public WxMpPayResult getJSSDKPayResult(String transactionId, String outTradeNo) { + public WxMpPayResult getJSSDKPayResult(String transactionId, + String outTradeNo) { String nonce_str = System.currentTimeMillis() + ""; SortedMap packageParams = new TreeMap<>(); - packageParams.put("appid", this.wxMpService.getWxMpConfigStorage().getAppId()); - packageParams.put("mch_id", this.wxMpService.getWxMpConfigStorage().getPartnerId()); - if (transactionId != null && !"".equals(transactionId.trim())) + packageParams.put("appid", + this.wxMpService.getWxMpConfigStorage().getAppId()); + packageParams.put("mch_id", + this.wxMpService.getWxMpConfigStorage().getPartnerId()); + + if (transactionId != null && !"".equals(transactionId.trim())) { packageParams.put("transaction_id", transactionId); - else if (outTradeNo != null && !"".equals(outTradeNo.trim())) + } else if (outTradeNo != null && !"".equals(outTradeNo.trim())) { packageParams.put("out_trade_no", outTradeNo); - else - throw new IllegalArgumentException("Either 'transactionId' or 'outTradeNo' must be given."); + } else { + throw new IllegalArgumentException( + "Either 'transactionId' or 'outTradeNo' must be given."); + } + packageParams.put("nonce_str", nonce_str); - packageParams.put("sign", WxCryptUtil.createSign(packageParams, this.wxMpService.getWxMpConfigStorage().getPartnerKey())); + packageParams.put("sign", WxCryptUtil.createSign(packageParams, + this.wxMpService.getWxMpConfigStorage().getPartnerKey())); StringBuilder request = new StringBuilder(""); for (Map.Entry para : packageParams.entrySet()) { - request.append(String.format("<%s>%s", para.getKey(), para.getValue(), para.getKey())); + request.append(String.format("<%s>%s", para.getKey(), + para.getValue(), para.getKey())); } request.append(""); - HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/pay/orderquery"); + HttpPost httpPost = new HttpPost( + "https://api.mch.weixin.qq.com/pay/orderquery"); if (this.httpProxy != null) { - RequestConfig config = RequestConfig.custom().setProxy(this.httpProxy).build(); + RequestConfig config = RequestConfig.custom().setProxy(this.httpProxy) + .build(); httpPost.setConfig(config); } StringEntity entity = new StringEntity(request.toString(), Consts.UTF_8); httpPost.setEntity(entity); - try(CloseableHttpResponse response = this.wxMpService.getHttpclient().execute(httpPost)) { - String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response); + try (CloseableHttpResponse response = this.wxMpService.getHttpclient() + .execute(httpPost)) { + String responseContent = Utf8ResponseHandler.INSTANCE + .handleResponse(response); XStream xstream = XStreamInitializer.getInstance(); xstream.alias("xml", WxMpPayResult.class); return (WxMpPayResult) xstream.fromXML(responseContent); } catch (IOException e) { - throw new RuntimeException("Failed to query order due to IO exception.", e); + throw new RuntimeException("Failed to query order due to IO exception.", + e); } } @@ -224,7 +273,7 @@ public class WxMpPayServiceImpl implements WxMpPayService { XStream xstream = XStreamInitializer.getInstance(); xstream.alias("xml", WxMpPayCallback.class); return (WxMpPayCallback) xstream.fromXML(xmlData); - } catch (Exception e){ + } catch (Exception e) { e.printStackTrace(); } @@ -232,102 +281,126 @@ public class WxMpPayServiceImpl implements WxMpPayService { } @Override - public WxMpPayRefundResult refundPay(Map parameters) throws WxErrorException { + public WxMpPayRefundResult refundPay(Map parameters) + throws WxErrorException { SortedMap refundParams = new TreeMap<>(parameters); - refundParams.put("appid", this.wxMpService.getWxMpConfigStorage().getAppId()); - refundParams.put("mch_id", this.wxMpService.getWxMpConfigStorage().getPartnerId()); + refundParams.put("appid", + this.wxMpService.getWxMpConfigStorage().getAppId()); + refundParams.put("mch_id", + this.wxMpService.getWxMpConfigStorage().getPartnerId()); refundParams.put("nonce_str", System.currentTimeMillis() + ""); - refundParams.put("op_user_id", this.wxMpService.getWxMpConfigStorage().getPartnerId()); - String sign = WxCryptUtil.createSign(refundParams, this.wxMpService.getWxMpConfigStorage().getPartnerKey()); + refundParams.put("op_user_id", + this.wxMpService.getWxMpConfigStorage().getPartnerId()); + String sign = WxCryptUtil.createSign(refundParams, + this.wxMpService.getWxMpConfigStorage().getPartnerKey()); refundParams.put("sign", sign); StringBuilder request = new StringBuilder(""); for (Map.Entry para : refundParams.entrySet()) { - request.append(String.format("<%s>%s", para.getKey(), para.getValue(), para.getKey())); + request.append(String.format("<%s>%s", para.getKey(), + para.getValue(), para.getKey())); } request.append(""); - HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/secapi/pay/refund"); + HttpPost httpPost = new HttpPost( + "https://api.mch.weixin.qq.com/secapi/pay/refund"); if (this.httpProxy != null) { - RequestConfig config = RequestConfig.custom().setProxy(this.httpProxy).build(); + RequestConfig config = RequestConfig.custom().setProxy(this.httpProxy) + .build(); httpPost.setConfig(config); } StringEntity entity = new StringEntity(request.toString(), Consts.UTF_8); httpPost.setEntity(entity); - try(CloseableHttpResponse response = this.wxMpService.getHttpclient().execute(httpPost)) { - String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response); + try (CloseableHttpResponse response = this.wxMpService.getHttpclient() + .execute(httpPost)) { + String responseContent = Utf8ResponseHandler.INSTANCE + .handleResponse(response); XStream xstream = XStreamInitializer.getInstance(); xstream.processAnnotations(WxMpPayRefundResult.class); - WxMpPayRefundResult wxMpPayRefundResult = (WxMpPayRefundResult) xstream.fromXML(responseContent); + WxMpPayRefundResult wxMpPayRefundResult = (WxMpPayRefundResult) xstream + .fromXML(responseContent); if (!"SUCCESS".equalsIgnoreCase(wxMpPayRefundResult.getResultCode()) - ||!"SUCCESS".equalsIgnoreCase(wxMpPayRefundResult.getReturnCode())) { + || !"SUCCESS".equalsIgnoreCase(wxMpPayRefundResult.getReturnCode())) { WxError error = new WxError(); error.setErrorCode(-1); - error.setErrorMsg("return_code:" + wxMpPayRefundResult.getReturnCode() + - ";return_msg:" + wxMpPayRefundResult.getReturnMsg() + - ";result_code:" + wxMpPayRefundResult.getResultCode() + - ";err_code" + wxMpPayRefundResult.getErrCode() + - ";err_code_des" + wxMpPayRefundResult.getErrCodeDes()); + error.setErrorMsg("return_code:" + wxMpPayRefundResult.getReturnCode() + + ";return_msg:" + wxMpPayRefundResult.getReturnMsg() + + ";result_code:" + wxMpPayRefundResult.getResultCode() + + ";err_code" + wxMpPayRefundResult.getErrCode() + ";err_code_des" + + wxMpPayRefundResult.getErrCodeDes()); throw new WxErrorException(error); } return wxMpPayRefundResult; } catch (IOException e) { - this.log.error(MessageFormatter.format("The exception was happened when sending refund '{}'.", - request.toString()).getMessage(), e); - WxError error = new WxError(); - error.setErrorCode(-1); - error.setErrorMsg("incorrect response."); - throw new WxErrorException(error); - }finally { + String message = MessageFormatter + .format("Exception happened when sending refund '{}'.", + request.toString()) + .getMessage(); + this.log.error(message, e); + throw new WxErrorException( + WxError.newBuilder().setErrorMsg(message).build()); + } finally { httpPost.releaseConnection(); } } @Override - public boolean checkJSSDKCallbackDataSignature(Map kvm, String signature) { - return signature.equals(WxCryptUtil.createSign(kvm, this.wxMpService.getWxMpConfigStorage().getPartnerKey())); + public boolean checkJSSDKCallbackDataSignature(Map kvm, + String signature) { + return signature.equals(WxCryptUtil.createSign(kvm, + this.wxMpService.getWxMpConfigStorage().getPartnerKey())); } @Override - public WxRedpackResult sendRedpack(Map parameters) throws WxErrorException { - String nonce_str = System.currentTimeMillis() + ""; - + public WxRedpackResult sendRedpack(Map parameters) + throws WxErrorException { SortedMap packageParams = new TreeMap<>(parameters); - packageParams.put("wxappid", this.wxMpService.getWxMpConfigStorage().getAppId()); - packageParams.put("mch_id", this.wxMpService.getWxMpConfigStorage().getPartnerId()); - packageParams.put("nonce_str", nonce_str); - - String sign = WxCryptUtil.createSign(packageParams, this.wxMpService.getWxMpConfigStorage().getPartnerKey()); + packageParams.put("wxappid", + this.wxMpService.getWxMpConfigStorage().getAppId()); + packageParams.put("mch_id", + this.wxMpService.getWxMpConfigStorage().getPartnerId()); + packageParams.put("nonce_str", System.currentTimeMillis() + ""); + + String sign = WxCryptUtil.createSign(packageParams, + this.wxMpService.getWxMpConfigStorage().getPartnerKey()); packageParams.put("sign", sign); StringBuilder request = new StringBuilder(""); for (Map.Entry para : packageParams.entrySet()) { - request.append(String.format("<%s>%s", para.getKey(), para.getValue(), para.getKey())); + request.append(String.format("<%s>%s", para.getKey(), + para.getValue(), para.getKey())); } + request.append(""); - HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack"); + HttpPost httpPost = new HttpPost( + "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack"); if (this.httpProxy != null) { - RequestConfig config = RequestConfig.custom().setProxy(this.httpProxy).build(); + RequestConfig config = RequestConfig.custom().setProxy(this.httpProxy) + .build(); httpPost.setConfig(config); } StringEntity entity = new StringEntity(request.toString(), Consts.UTF_8); httpPost.setEntity(entity); - try(CloseableHttpResponse response = this.wxMpService.getHttpclient().execute(httpPost)) { - String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response); + try (CloseableHttpResponse response = this.wxMpService.getHttpclient() + .execute(httpPost)) { + String responseContent = Utf8ResponseHandler.INSTANCE + .handleResponse(response); XStream xstream = XStreamInitializer.getInstance(); xstream.processAnnotations(WxRedpackResult.class); return (WxRedpackResult) xstream.fromXML(responseContent); } catch (IOException e) { - this.log.error(MessageFormatter.format("The exception was happened when sending redpack '{}'.", request.toString()).getMessage(), e); - WxError error = new WxError(); - error.setErrorCode(-1); - throw new WxErrorException(error); - }finally { + String message = MessageFormatter + .format("Exception occured when sending redpack '{}'.", + request.toString()) + .getMessage(); + this.log.error(message, e); + throw new WxErrorException(WxError.newBuilder().setErrorMsg(message).build()); + } finally { httpPost.releaseConnection(); } }