格式化不规范的代码

This commit is contained in:
BinaryWang
2016-08-19 09:45:33 +08:00
parent 184e6d785a
commit c8d21e3fba

View File

@ -26,12 +26,15 @@ import java.util.TreeMap;
/** /**
* Created by Binary Wang on 2016/7/28. * Created by Binary Wang on 2016/7/28.
*
* @author binarywang (https://github.com/binarywang) * @author binarywang (https://github.com/binarywang)
*/ */
public class WxMpPayServiceImpl implements WxMpPayService { public class WxMpPayServiceImpl implements WxMpPayService {
private final Logger log = LoggerFactory.getLogger(WxMpPayServiceImpl.class); 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 HttpHost httpProxy;
private WxMpServiceImpl wxMpService; private WxMpServiceImpl wxMpService;
@ -41,10 +44,14 @@ public class WxMpPayServiceImpl implements WxMpPayService {
} }
@Override @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<String, String> packageParams = new HashMap<>(); Map<String, String> packageParams = new HashMap<>();
packageParams.put("appid", this.wxMpService.getWxMpConfigStorage().getAppId()); packageParams.put("appid",
packageParams.put("mch_id", this.wxMpService.getWxMpConfigStorage().getPartnerId()); this.wxMpService.getWxMpConfigStorage().getAppId());
packageParams.put("mch_id",
this.wxMpService.getWxMpConfigStorage().getPartnerId());
packageParams.put("body", body); packageParams.put("body", body);
packageParams.put("out_trade_no", outTradeNo); packageParams.put("out_trade_no", outTradeNo);
packageParams.put("total_fee", (int) (amt * 100) + ""); packageParams.put("total_fee", (int) (amt * 100) + "");
@ -58,62 +65,81 @@ public class WxMpPayServiceImpl implements WxMpPayService {
@Override @Override
public WxMpPrepayIdResult getPrepayId(final Map<String, String> parameters) { public WxMpPrepayIdResult getPrepayId(final Map<String, String> parameters) {
String nonce_str = System.currentTimeMillis() + "";
final SortedMap<String, String> packageParams = new TreeMap<>(parameters); final SortedMap<String, String> packageParams = new TreeMap<>(parameters);
packageParams.put("appid", this.wxMpService.getWxMpConfigStorage().getAppId()); packageParams.put("appid",
packageParams.put("mch_id", this.wxMpService.getWxMpConfigStorage().getPartnerId()); this.wxMpService.getWxMpConfigStorage().getAppId());
packageParams.put("nonce_str", nonce_str); packageParams.put("mch_id",
this.wxMpService.getWxMpConfigStorage().getPartnerId());
packageParams.put("nonce_str", System.currentTimeMillis() + "");
checkParameters(packageParams); checkParameters(packageParams);
String sign = WxCryptUtil.createSign(packageParams, this.wxMpService.getWxMpConfigStorage().getPartnerKey()); String sign = WxCryptUtil.createSign(packageParams,
this.wxMpService.getWxMpConfigStorage().getPartnerKey());
packageParams.put("sign", sign); packageParams.put("sign", sign);
StringBuilder request = new StringBuilder("<xml>"); StringBuilder request = new StringBuilder("<xml>");
for (Map.Entry<String, String> para : packageParams.entrySet()) { for (Map.Entry<String, String> para : packageParams.entrySet()) {
request.append(String.format("<%s>%s</%s>", para.getKey(), para.getValue(), para.getKey())); request.append(String.format("<%s>%s</%s>", para.getKey(),
para.getValue(), para.getKey()));
} }
request.append("</xml>"); request.append("</xml>");
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) { if (this.httpProxy != null) {
RequestConfig config = RequestConfig.custom().setProxy(this.httpProxy).build(); RequestConfig config = RequestConfig.custom().setProxy(this.httpProxy)
.build();
httpPost.setConfig(config); httpPost.setConfig(config);
} }
StringEntity entity = new StringEntity(request.toString(), Consts.UTF_8); StringEntity entity = new StringEntity(request.toString(), Consts.UTF_8);
httpPost.setEntity(entity); httpPost.setEntity(entity);
try(CloseableHttpResponse response = this.wxMpService.getHttpclient().execute(httpPost)) { try (CloseableHttpResponse response = this.wxMpService.getHttpclient()
String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response); .execute(httpPost)) {
String responseContent = Utf8ResponseHandler.INSTANCE
.handleResponse(response);
XStream xstream = XStreamInitializer.getInstance(); XStream xstream = XStreamInitializer.getInstance();
xstream.alias("xml", WxMpPrepayIdResult.class); xstream.alias("xml", WxMpPrepayIdResult.class);
return (WxMpPrepayIdResult) xstream.fromXML(responseContent); return (WxMpPrepayIdResult) xstream.fromXML(responseContent);
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException("Failed to get prepay id due to IO exception.", e); throw new RuntimeException("Failed to get prepay id due to IO exception.",
}finally { e);
} finally {
httpPost.releaseConnection(); 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<String, String> parameters) { private void checkParameters(Map<String, String> parameters) {
for (String para : this.REQUIRED_ORDER_PARAMETERS) { for (String para : this.REQUIRED_ORDER_PARAMETERS) {
if (!parameters.containsKey(para)) if (!parameters.containsKey(para)) {
throw new IllegalArgumentException("Reqiured argument '" + para + "' is missing."); 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 @Override
public Map<String, String> getJsapiPayInfo(String openId,String outTradeNo, double amt, String body,String ip, String callbackUrl) throws WxErrorException { public Map<String, String> getJsapiPayInfo(String openId, String outTradeNo,
double amt, String body, String ip, String callbackUrl)
throws WxErrorException {
Map<String, String> packageParams = new HashMap<>(); Map<String, String> packageParams = new HashMap<>();
packageParams.put("appid", this.wxMpService.getWxMpConfigStorage().getAppId()); packageParams.put("appid",
packageParams.put("mch_id", this.wxMpService.getWxMpConfigStorage().getPartnerId()); this.wxMpService.getWxMpConfigStorage().getAppId());
packageParams.put("mch_id",
this.wxMpService.getWxMpConfigStorage().getPartnerId());
packageParams.put("body", body); packageParams.put("body", body);
packageParams.put("out_trade_no", outTradeNo); packageParams.put("out_trade_no", outTradeNo);
packageParams.put("total_fee", (int) (amt * 100) + ""); packageParams.put("total_fee", (int) (amt * 100) + "");
@ -126,10 +152,14 @@ public class WxMpPayServiceImpl implements WxMpPayService {
} }
@Override @Override
public Map<String, String> getNativePayInfo(String productId,String outTradeNo, double amt, String body,String ip, String callbackUrl) throws WxErrorException{ public Map<String, String> getNativePayInfo(String productId,
String outTradeNo, double amt, String body, String ip, String callbackUrl)
throws WxErrorException {
Map<String, String> packageParams = new HashMap<>(); Map<String, String> packageParams = new HashMap<>();
packageParams.put("appid", this.wxMpService.getWxMpConfigStorage().getAppId()); packageParams.put("appid",
packageParams.put("mch_id", this.wxMpService.getWxMpConfigStorage().getPartnerId()); this.wxMpService.getWxMpConfigStorage().getAppId());
packageParams.put("mch_id",
this.wxMpService.getWxMpConfigStorage().getPartnerId());
packageParams.put("body", body); packageParams.put("body", body);
packageParams.put("out_trade_no", outTradeNo); packageParams.put("out_trade_no", outTradeNo);
packageParams.put("total_fee", (int) (amt * 100) + ""); packageParams.put("total_fee", (int) (amt * 100) + "");
@ -142,24 +172,28 @@ public class WxMpPayServiceImpl implements WxMpPayService {
} }
@Override @Override
public Map<String, String> getPayInfo(Map<String, String> parameters) throws WxErrorException { public Map<String, String> getPayInfo(Map<String, String> parameters)
throws WxErrorException {
WxMpPrepayIdResult wxMpPrepayIdResult = getPrepayId(parameters); WxMpPrepayIdResult wxMpPrepayIdResult = getPrepayId(parameters);
if (!"SUCCESS".equalsIgnoreCase(wxMpPrepayIdResult.getReturn_code()) if (!"SUCCESS".equalsIgnoreCase(wxMpPrepayIdResult.getReturn_code())
||!"SUCCESS".equalsIgnoreCase(wxMpPrepayIdResult.getResult_code())) { || !"SUCCESS".equalsIgnoreCase(wxMpPrepayIdResult.getResult_code())) {
WxError error = new WxError(); WxError error = new WxError();
error.setErrorCode(-1); error.setErrorCode(-1);
error.setErrorMsg("return_code:" + wxMpPrepayIdResult.getReturn_code() + error.setErrorMsg("return_code:" + wxMpPrepayIdResult.getReturn_code()
";return_msg:" + wxMpPrepayIdResult.getReturn_msg() + + ";return_msg:" + wxMpPrepayIdResult.getReturn_msg()
";result_code:" + wxMpPrepayIdResult.getResult_code() + + ";result_code:" + wxMpPrepayIdResult.getResult_code() + ";err_code"
";err_code" + wxMpPrepayIdResult.getErr_code() + + wxMpPrepayIdResult.getErr_code() + ";err_code_des"
";err_code_des" + wxMpPrepayIdResult.getErr_code_des()); + wxMpPrepayIdResult.getErr_code_des());
throw new WxErrorException(error); throw new WxErrorException(error);
} }
String prepayId = wxMpPrepayIdResult.getPrepay_id(); String prepayId = wxMpPrepayIdResult.getPrepay_id();
if (prepayId == null || prepayId.equals("")) { 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<String, String> payInfo = new HashMap<>(); Map<String, String> payInfo = new HashMap<>();
@ -169,52 +203,67 @@ public class WxMpPayServiceImpl implements WxMpPayService {
payInfo.put("nonceStr", System.currentTimeMillis() + ""); payInfo.put("nonceStr", System.currentTimeMillis() + "");
payInfo.put("package", "prepay_id=" + prepayId); payInfo.put("package", "prepay_id=" + prepayId);
payInfo.put("signType", "MD5"); payInfo.put("signType", "MD5");
if("NATIVE".equals(parameters.get("trade_type"))){ if ("NATIVE".equals(parameters.get("trade_type"))) {
payInfo.put("codeUrl", wxMpPrepayIdResult.getCode_url()); 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); payInfo.put("paySign", finalSign);
return payInfo; return payInfo;
} }
@Override @Override
public WxMpPayResult getJSSDKPayResult(String transactionId, String outTradeNo) { public WxMpPayResult getJSSDKPayResult(String transactionId,
String outTradeNo) {
String nonce_str = System.currentTimeMillis() + ""; String nonce_str = System.currentTimeMillis() + "";
SortedMap<String, String> packageParams = new TreeMap<>(); SortedMap<String, String> packageParams = new TreeMap<>();
packageParams.put("appid", this.wxMpService.getWxMpConfigStorage().getAppId()); packageParams.put("appid",
packageParams.put("mch_id", this.wxMpService.getWxMpConfigStorage().getPartnerId()); this.wxMpService.getWxMpConfigStorage().getAppId());
if (transactionId != null && !"".equals(transactionId.trim())) packageParams.put("mch_id",
this.wxMpService.getWxMpConfigStorage().getPartnerId());
if (transactionId != null && !"".equals(transactionId.trim())) {
packageParams.put("transaction_id", transactionId); 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); packageParams.put("out_trade_no", outTradeNo);
else } else {
throw new IllegalArgumentException("Either 'transactionId' or 'outTradeNo' must be given."); throw new IllegalArgumentException(
"Either 'transactionId' or 'outTradeNo' must be given.");
}
packageParams.put("nonce_str", nonce_str); 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("<xml>"); StringBuilder request = new StringBuilder("<xml>");
for (Map.Entry<String, String> para : packageParams.entrySet()) { for (Map.Entry<String, String> para : packageParams.entrySet()) {
request.append(String.format("<%s>%s</%s>", para.getKey(), para.getValue(), para.getKey())); request.append(String.format("<%s>%s</%s>", para.getKey(),
para.getValue(), para.getKey()));
} }
request.append("</xml>"); request.append("</xml>");
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) { if (this.httpProxy != null) {
RequestConfig config = RequestConfig.custom().setProxy(this.httpProxy).build(); RequestConfig config = RequestConfig.custom().setProxy(this.httpProxy)
.build();
httpPost.setConfig(config); httpPost.setConfig(config);
} }
StringEntity entity = new StringEntity(request.toString(), Consts.UTF_8); StringEntity entity = new StringEntity(request.toString(), Consts.UTF_8);
httpPost.setEntity(entity); httpPost.setEntity(entity);
try(CloseableHttpResponse response = this.wxMpService.getHttpclient().execute(httpPost)) { try (CloseableHttpResponse response = this.wxMpService.getHttpclient()
String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response); .execute(httpPost)) {
String responseContent = Utf8ResponseHandler.INSTANCE
.handleResponse(response);
XStream xstream = XStreamInitializer.getInstance(); XStream xstream = XStreamInitializer.getInstance();
xstream.alias("xml", WxMpPayResult.class); xstream.alias("xml", WxMpPayResult.class);
return (WxMpPayResult) xstream.fromXML(responseContent); return (WxMpPayResult) xstream.fromXML(responseContent);
} catch (IOException e) { } 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 xstream = XStreamInitializer.getInstance();
xstream.alias("xml", WxMpPayCallback.class); xstream.alias("xml", WxMpPayCallback.class);
return (WxMpPayCallback) xstream.fromXML(xmlData); return (WxMpPayCallback) xstream.fromXML(xmlData);
} catch (Exception e){ } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -232,102 +281,126 @@ public class WxMpPayServiceImpl implements WxMpPayService {
} }
@Override @Override
public WxMpPayRefundResult refundPay(Map<String, String> parameters) throws WxErrorException { public WxMpPayRefundResult refundPay(Map<String, String> parameters)
throws WxErrorException {
SortedMap<String, String> refundParams = new TreeMap<>(parameters); SortedMap<String, String> refundParams = new TreeMap<>(parameters);
refundParams.put("appid", this.wxMpService.getWxMpConfigStorage().getAppId()); refundParams.put("appid",
refundParams.put("mch_id", this.wxMpService.getWxMpConfigStorage().getPartnerId()); this.wxMpService.getWxMpConfigStorage().getAppId());
refundParams.put("mch_id",
this.wxMpService.getWxMpConfigStorage().getPartnerId());
refundParams.put("nonce_str", System.currentTimeMillis() + ""); refundParams.put("nonce_str", System.currentTimeMillis() + "");
refundParams.put("op_user_id", this.wxMpService.getWxMpConfigStorage().getPartnerId()); refundParams.put("op_user_id",
String sign = WxCryptUtil.createSign(refundParams, this.wxMpService.getWxMpConfigStorage().getPartnerKey()); this.wxMpService.getWxMpConfigStorage().getPartnerId());
String sign = WxCryptUtil.createSign(refundParams,
this.wxMpService.getWxMpConfigStorage().getPartnerKey());
refundParams.put("sign", sign); refundParams.put("sign", sign);
StringBuilder request = new StringBuilder("<xml>"); StringBuilder request = new StringBuilder("<xml>");
for (Map.Entry<String, String> para : refundParams.entrySet()) { for (Map.Entry<String, String> para : refundParams.entrySet()) {
request.append(String.format("<%s>%s</%s>", para.getKey(), para.getValue(), para.getKey())); request.append(String.format("<%s>%s</%s>", para.getKey(),
para.getValue(), para.getKey()));
} }
request.append("</xml>"); request.append("</xml>");
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) { if (this.httpProxy != null) {
RequestConfig config = RequestConfig.custom().setProxy(this.httpProxy).build(); RequestConfig config = RequestConfig.custom().setProxy(this.httpProxy)
.build();
httpPost.setConfig(config); httpPost.setConfig(config);
} }
StringEntity entity = new StringEntity(request.toString(), Consts.UTF_8); StringEntity entity = new StringEntity(request.toString(), Consts.UTF_8);
httpPost.setEntity(entity); httpPost.setEntity(entity);
try(CloseableHttpResponse response = this.wxMpService.getHttpclient().execute(httpPost)) { try (CloseableHttpResponse response = this.wxMpService.getHttpclient()
String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response); .execute(httpPost)) {
String responseContent = Utf8ResponseHandler.INSTANCE
.handleResponse(response);
XStream xstream = XStreamInitializer.getInstance(); XStream xstream = XStreamInitializer.getInstance();
xstream.processAnnotations(WxMpPayRefundResult.class); xstream.processAnnotations(WxMpPayRefundResult.class);
WxMpPayRefundResult wxMpPayRefundResult = (WxMpPayRefundResult) xstream.fromXML(responseContent); WxMpPayRefundResult wxMpPayRefundResult = (WxMpPayRefundResult) xstream
.fromXML(responseContent);
if (!"SUCCESS".equalsIgnoreCase(wxMpPayRefundResult.getResultCode()) if (!"SUCCESS".equalsIgnoreCase(wxMpPayRefundResult.getResultCode())
||!"SUCCESS".equalsIgnoreCase(wxMpPayRefundResult.getReturnCode())) { || !"SUCCESS".equalsIgnoreCase(wxMpPayRefundResult.getReturnCode())) {
WxError error = new WxError(); WxError error = new WxError();
error.setErrorCode(-1); error.setErrorCode(-1);
error.setErrorMsg("return_code:" + wxMpPayRefundResult.getReturnCode() + error.setErrorMsg("return_code:" + wxMpPayRefundResult.getReturnCode()
";return_msg:" + wxMpPayRefundResult.getReturnMsg() + + ";return_msg:" + wxMpPayRefundResult.getReturnMsg()
";result_code:" + wxMpPayRefundResult.getResultCode() + + ";result_code:" + wxMpPayRefundResult.getResultCode()
";err_code" + wxMpPayRefundResult.getErrCode() + + ";err_code" + wxMpPayRefundResult.getErrCode() + ";err_code_des"
";err_code_des" + wxMpPayRefundResult.getErrCodeDes()); + wxMpPayRefundResult.getErrCodeDes());
throw new WxErrorException(error); throw new WxErrorException(error);
} }
return wxMpPayRefundResult; return wxMpPayRefundResult;
} catch (IOException e) { } catch (IOException e) {
this.log.error(MessageFormatter.format("The exception was happened when sending refund '{}'.", String message = MessageFormatter
request.toString()).getMessage(), e); .format("Exception happened when sending refund '{}'.",
WxError error = new WxError(); request.toString())
error.setErrorCode(-1); .getMessage();
error.setErrorMsg("incorrect response."); this.log.error(message, e);
throw new WxErrorException(error); throw new WxErrorException(
}finally { WxError.newBuilder().setErrorMsg(message).build());
} finally {
httpPost.releaseConnection(); httpPost.releaseConnection();
} }
} }
@Override @Override
public boolean checkJSSDKCallbackDataSignature(Map<String, String> kvm, String signature) { public boolean checkJSSDKCallbackDataSignature(Map<String, String> kvm,
return signature.equals(WxCryptUtil.createSign(kvm, this.wxMpService.getWxMpConfigStorage().getPartnerKey())); String signature) {
return signature.equals(WxCryptUtil.createSign(kvm,
this.wxMpService.getWxMpConfigStorage().getPartnerKey()));
} }
@Override @Override
public WxRedpackResult sendRedpack(Map<String, String> parameters) throws WxErrorException { public WxRedpackResult sendRedpack(Map<String, String> parameters)
String nonce_str = System.currentTimeMillis() + ""; throws WxErrorException {
SortedMap<String, String> packageParams = new TreeMap<>(parameters); SortedMap<String, String> packageParams = new TreeMap<>(parameters);
packageParams.put("wxappid", this.wxMpService.getWxMpConfigStorage().getAppId()); packageParams.put("wxappid",
packageParams.put("mch_id", this.wxMpService.getWxMpConfigStorage().getPartnerId()); this.wxMpService.getWxMpConfigStorage().getAppId());
packageParams.put("nonce_str", nonce_str); packageParams.put("mch_id",
this.wxMpService.getWxMpConfigStorage().getPartnerId());
packageParams.put("nonce_str", System.currentTimeMillis() + "");
String sign = WxCryptUtil.createSign(packageParams, this.wxMpService.getWxMpConfigStorage().getPartnerKey()); String sign = WxCryptUtil.createSign(packageParams,
this.wxMpService.getWxMpConfigStorage().getPartnerKey());
packageParams.put("sign", sign); packageParams.put("sign", sign);
StringBuilder request = new StringBuilder("<xml>"); StringBuilder request = new StringBuilder("<xml>");
for (Map.Entry<String, String> para : packageParams.entrySet()) { for (Map.Entry<String, String> para : packageParams.entrySet()) {
request.append(String.format("<%s>%s</%s>", para.getKey(), para.getValue(), para.getKey())); request.append(String.format("<%s>%s</%s>", para.getKey(),
para.getValue(), para.getKey()));
} }
request.append("</xml>"); request.append("</xml>");
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) { if (this.httpProxy != null) {
RequestConfig config = RequestConfig.custom().setProxy(this.httpProxy).build(); RequestConfig config = RequestConfig.custom().setProxy(this.httpProxy)
.build();
httpPost.setConfig(config); httpPost.setConfig(config);
} }
StringEntity entity = new StringEntity(request.toString(), Consts.UTF_8); StringEntity entity = new StringEntity(request.toString(), Consts.UTF_8);
httpPost.setEntity(entity); httpPost.setEntity(entity);
try(CloseableHttpResponse response = this.wxMpService.getHttpclient().execute(httpPost)) { try (CloseableHttpResponse response = this.wxMpService.getHttpclient()
String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response); .execute(httpPost)) {
String responseContent = Utf8ResponseHandler.INSTANCE
.handleResponse(response);
XStream xstream = XStreamInitializer.getInstance(); XStream xstream = XStreamInitializer.getInstance();
xstream.processAnnotations(WxRedpackResult.class); xstream.processAnnotations(WxRedpackResult.class);
return (WxRedpackResult) xstream.fromXML(responseContent); return (WxRedpackResult) xstream.fromXML(responseContent);
} catch (IOException e) { } catch (IOException e) {
this.log.error(MessageFormatter.format("The exception was happened when sending redpack '{}'.", request.toString()).getMessage(), e); String message = MessageFormatter
WxError error = new WxError(); .format("Exception occured when sending redpack '{}'.",
error.setErrorCode(-1); request.toString())
throw new WxErrorException(error); .getMessage();
}finally { this.log.error(message, e);
throw new WxErrorException(WxError.newBuilder().setErrorMsg(message).build());
} finally {
httpPost.releaseConnection(); httpPost.releaseConnection();
} }
} }