WechatUtil.java 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  1. package com.kmall.common.utils.wechat;
  2. import com.alibaba.druid.support.logging.Log;
  3. import com.alibaba.druid.support.logging.LogFactory;
  4. import com.kmall.common.service.pay.wxpay.CommonWxPayPropertiesBuilder;
  5. import com.kmall.common.utils.*;
  6. import org.apache.http.HttpEntity;
  7. import org.apache.http.HttpResponse;
  8. import org.apache.http.client.HttpClient;
  9. import org.apache.http.client.config.RequestConfig;
  10. import org.apache.http.client.methods.CloseableHttpResponse;
  11. import org.apache.http.client.methods.HttpGet;
  12. import org.apache.http.client.methods.HttpPost;
  13. import org.apache.http.config.RegistryBuilder;
  14. import org.apache.http.conn.socket.ConnectionSocketFactory;
  15. import org.apache.http.conn.socket.PlainConnectionSocketFactory;
  16. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
  17. import org.apache.http.entity.StringEntity;
  18. import org.apache.http.impl.client.CloseableHttpClient;
  19. import org.apache.http.impl.client.HttpClientBuilder;
  20. import org.apache.http.impl.client.HttpClients;
  21. import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
  22. import org.apache.http.util.EntityUtils;
  23. import java.io.IOException;
  24. import java.io.UnsupportedEncodingException;
  25. import java.math.BigDecimal;
  26. import java.math.MathContext;
  27. import java.net.URLEncoder;
  28. import java.text.SimpleDateFormat;
  29. import java.util.*;
  30. /**
  31. * <p>Title: 微信退款工具类</p>
  32. * <p>Description: 微信退款工具类,通过充值客户端的不同初始化不同的工具类,得到相应微信退款相关的appid和muchid</p>
  33. *
  34. * @author xubo
  35. * @date 2017年6月6日 下午5:05:03
  36. */
  37. public class WechatUtil {
  38. private static Log logger = LogFactory.getLog(WechatUtil.class);
  39. /**
  40. * 充值客户端类型--微信公众号
  41. */
  42. public static Integer CLIENTTYPE_WX = 2;
  43. /**
  44. * 充值客户端类型--app
  45. */
  46. public static Integer CLIENTTYPE_APP = 1;
  47. private static final String EMPTY = "";
  48. private static final String URL_PARAM_CONNECT_FLAG = "&";
  49. /**
  50. * 菜单类型
  51. *
  52. * @author Scott
  53. * @email
  54. * @date 2016年11月15日 下午1:24:29
  55. */
  56. public enum WXTradeState {
  57. /**
  58. * 支付成功
  59. */
  60. SUCCESS("SUCCESS", "支付成功"),
  61. /**
  62. * 转入退款
  63. */
  64. REFUND("REFUND", "转入退款"),
  65. /**
  66. * 未支付
  67. */
  68. NOTPAY("NOTPAY", "未支付"),
  69. /**
  70. * 已关闭
  71. */
  72. CLOSED("CLOSED", "已关闭"),
  73. /**
  74. * 已撤销(付款码支付)
  75. */
  76. REVOKED("REVOKED", "已撤销"),
  77. /**
  78. * 用户支付中(付款码支付)
  79. */
  80. USERPAYING("USERPAYING", "用户支付中"),
  81. /**
  82. * 支付失败(付款码支付)
  83. */
  84. PAYERROR("PAYERROR", "支付失败");
  85. private String code;
  86. private String codeZn;
  87. private WXTradeState(String code, String codeZn) {
  88. this.code = code;
  89. this.codeZn = codeZn;
  90. }
  91. public String getCode() {
  92. return code;
  93. }
  94. public String getCodeZn() {
  95. return codeZn;
  96. }
  97. }
  98. /**
  99. * 方法描述:微信退款逻辑
  100. * 创建时间:2017年4月12日 上午11:04:25
  101. * 作者: xubo
  102. *
  103. * @param
  104. * @return
  105. */
  106. public static WechatRefundApiResult wxRefund(String out_trade_no, Double orderMoney, Double refundMoney) {
  107. //初始化请求微信服务器的配置信息包括appid密钥等
  108. //转换金钱格式
  109. BigDecimal bdOrderMoney = new BigDecimal(orderMoney, MathContext.DECIMAL32);
  110. BigDecimal bdRefundMoney = new BigDecimal(refundMoney, MathContext.DECIMAL32);
  111. //构建请求参数
  112. Map<Object, Object> params = buildRefundRequsetMapParam(out_trade_no, bdOrderMoney, bdRefundMoney);
  113. String mapToXml = MapUtils.convertMap2Xml(params);
  114. //请求微信
  115. String reponseXml = sendRefundSSLPostToWx(mapToXml, WechatConfig.getSslcsf());
  116. logger.info("-----------reponseXml : "+reponseXml);
  117. WechatRefundApiResult result =
  118. (WechatRefundApiResult) XmlUtil.xmlStrToBean(reponseXml, WechatRefundApiResult.class);
  119. result.setOut_refund_no((String) params.get("out_refund_no"));
  120. logger.info("-----------result : "+result);
  121. return result;
  122. }
  123. /**
  124. * 方法描述:得到请求微信退款请求的参数
  125. * 创建时间:2017年6月8日 上午11:27:02
  126. * 作者: xubo
  127. *
  128. * @param
  129. * @return
  130. */
  131. private static Map<Object, Object> buildRefundRequsetMapParam(String out_trade_no, BigDecimal bdOrderMoney,
  132. BigDecimal bdRefundMoney) {
  133. Map<Object, Object> params = new HashMap<Object, Object>();
  134. params.put("appid", CommonWxPayPropertiesBuilder.instance().getAppId());//微信分配的公众账号ID(企业号corpid即为此appId)
  135. params.put("mch_id", CommonWxPayPropertiesBuilder.instance().getMchId());//微信支付分配的商户号
  136. params.put("nonce_str", CharUtil.getRandomString(16));//随机字符串,不长于32位。推荐随机数生成算法
  137. params.put("out_trade_no", out_trade_no);//商户传给微信的订单号
  138. params.put("out_refund_no", System.currentTimeMillis() + "");//商户系统内部的退款单号,商户系统内部唯一,同一退款单号多次请求只退一笔
  139. params.put("total_fee", bdOrderMoney.multiply(Constant.ONE_HUNDRED).intValue());//订单总金额,单位为分,只能为整数
  140. params.put("refund_fee", bdRefundMoney.multiply(Constant.ONE_HUNDRED).intValue());//退款总金额,订单总金额,单位为分,只能为整数
  141. params.put("op_user_id", CommonWxPayPropertiesBuilder.instance().getMchId());//操作员帐号, 默认为商户号
  142. params.put("notify_url", CommonWxPayPropertiesBuilder.instance().getRefundNotifyUrl());
  143. //签名前必须要参数全部写在前面
  144. params.put("sign", arraySign(params, CommonWxPayPropertiesBuilder.instance().getPaySignKey()));//签名
  145. return params;
  146. }
  147. /**
  148. * 请求退款微信
  149. **/
  150. public static String sendRefundSSLPostToWx(String mapToXml, SSLConnectionSocketFactory sslcsf) {
  151. logger.info("*******退款(WX Request:" + mapToXml);
  152. String xmlStr = sendSSLPostToWx(mapToXml, sslcsf, CommonWxPayPropertiesBuilder.instance().getRefundUrl());
  153. logger.info("*******退款(WX Response:" + xmlStr);
  154. return xmlStr;
  155. }
  156. /**
  157. * 请求微信https
  158. **/
  159. public static String sendSSLPostToWx(String mapToXml, SSLConnectionSocketFactory sslcsf, String requestUrl) {
  160. HttpPost httPost = new HttpPost(requestUrl);
  161. httPost.addHeader("Connection", "keep-alive");
  162. httPost.addHeader("Accept", "*/*");
  163. httPost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
  164. httPost.addHeader("Host", "api.mch.weixin.qq.com");
  165. httPost.addHeader("X-Requested-With", "XMLHttpRequest");
  166. httPost.addHeader("Cache-Control", "max-age=0");
  167. httPost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
  168. httPost.setEntity(new StringEntity(mapToXml, "UTF-8"));
  169. CloseableHttpClient httpClient = null;
  170. if (sslcsf != null) {
  171. httpClient = HttpClients.custom().setSSLSocketFactory(sslcsf).build();
  172. } else {
  173. httpClient = HttpClients.createDefault();
  174. }
  175. CloseableHttpResponse response = null;
  176. try {
  177. response = httpClient.execute(httPost);
  178. HttpEntity entity = response.getEntity();
  179. String xmlStr = EntityUtils.toString(entity, "UTF-8");
  180. return xmlStr;
  181. } catch (Exception e) {
  182. logger.error(e.getMessage(), e);
  183. return null;
  184. } finally {
  185. try {
  186. if (response != null) {
  187. response.close();
  188. }
  189. } catch (IOException e) {
  190. logger.error(e.getMessage(), e);
  191. }
  192. }
  193. }
  194. /**
  195. * 方法描述:微信查询退款逻辑
  196. * 创建时间:2017年4月12日 上午11:04:25
  197. * 作者: xubo
  198. *
  199. * @param
  200. * @return
  201. */
  202. public static WechatRefundQueryResult wxRefundquery(String out_trade_no) {
  203. Map<Object, Object> params = new HashMap<Object, Object>();
  204. params.put("appid", CommonWxPayPropertiesBuilder.instance().getAppId());//微信分配的公众账号ID(企业号corpid即为此appId)
  205. params.put("mch_id", CommonWxPayPropertiesBuilder.instance().getMchId());//微信支付分配的商户号
  206. params.put("nonce_str", CharUtil.getRandomString(16));//随机字符串,不长于32位。推荐随机数生成算法
  207. params.put("out_trade_no", out_trade_no);//商户侧传给微信的订单号
  208. //签名前必须要参数全部写在前面
  209. params.put("sign", arraySign(params, CommonWxPayPropertiesBuilder.instance().getPaySignKey()));//签名
  210. String mapToXml = MapUtils.convertMap2Xml(params);
  211. HttpPost httPost = new HttpPost(CommonWxPayPropertiesBuilder.instance().getRefundqueryUrl());
  212. httPost.addHeader("Connection", "keep-alive");
  213. httPost.addHeader("Accept", "*/*");
  214. httPost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
  215. httPost.addHeader("Host", "api.mch.weixin.qq.com");
  216. httPost.addHeader("X-Requested-With", "XMLHttpRequest");
  217. httPost.addHeader("Cache-Control", "max-age=0");
  218. httPost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
  219. httPost.setEntity(new StringEntity(mapToXml, "UTF-8"));
  220. CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(WechatConfig.getSslcsf()).build();
  221. CloseableHttpResponse response = null;
  222. try {
  223. response = httpClient.execute(httPost);
  224. HttpEntity entity = response.getEntity();
  225. String xmlStr = EntityUtils.toString(entity, "UTF-8");
  226. System.out.println(xmlStr);
  227. WechatRefundQueryResult result =
  228. (WechatRefundQueryResult) XmlUtil.xmlStrToBean(xmlStr, WechatRefundQueryResult.class);
  229. result.setXmlStr(xmlStr);
  230. // Map<String, Object> result = XmlUtil.xmlStrToMap(xmlStr);//.xmlStrToBean(xmlStr, WechatRefundApiResult.class);
  231. return result;
  232. //将信息保存到数据库
  233. } catch (Exception e) {
  234. logger.error(e.getMessage(), e);
  235. return null;
  236. } finally {
  237. try {
  238. if (response != null) {
  239. response.close();
  240. }
  241. } catch (IOException e) {
  242. logger.error(e.getMessage(), e);
  243. }
  244. }
  245. }
  246. /**
  247. * 支付交易ID
  248. */
  249. public static String getBundleId() {
  250. SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
  251. String tradeno = dateFormat.format(new Date());
  252. String str = "000000" + (int) (Math.random() * 1000000);
  253. tradeno = tradeno + str.substring(str.length() - 6);
  254. return tradeno;
  255. }
  256. /**
  257. * 方法描述:根据签名加密请求参数
  258. * 创建时间:2017年6月8日 上午11:28:52
  259. * 作者: xubo
  260. * @param
  261. * @return
  262. */
  263. public static String arraySign(Map<Object, Object> params, String paySignKey) {
  264. boolean encode = false;
  265. Set<Object> keysSet = params.keySet();
  266. Object[] keys = keysSet.toArray();
  267. Arrays.sort(keys);
  268. StringBuffer temp = new StringBuffer();
  269. boolean first = true;
  270. for (Object key : keys) {
  271. if (first) {
  272. first = false;
  273. } else {
  274. temp.append("&");
  275. }
  276. temp.append(key).append("=");
  277. Object value = params.get(key);
  278. String valueString = "";
  279. if (null != value) {
  280. valueString = value.toString();
  281. }
  282. if (encode) {
  283. try {
  284. temp.append(URLEncoder.encode(valueString, "UTF-8"));
  285. } catch (UnsupportedEncodingException e) {
  286. e.printStackTrace();
  287. }
  288. } else {
  289. temp.append(valueString);
  290. }
  291. }
  292. temp.append("&key=");
  293. temp.append(paySignKey);
  294. System.out.println(temp.toString());
  295. String packageSign = MD5.getMessageDigest(temp.toString());
  296. return packageSign;
  297. }
  298. /**
  299. * 请求,只请求一次,不做重试
  300. *
  301. * @param url
  302. * @param data
  303. * @return
  304. * @throws Exception
  305. */
  306. public static String requestOnce(final String url, String data) {
  307. BasicHttpClientConnectionManager connManager;
  308. connManager = new BasicHttpClientConnectionManager(RegistryBuilder.<ConnectionSocketFactory>create()
  309. .register("http", PlainConnectionSocketFactory
  310. .getSocketFactory()).register("https",
  311. SSLConnectionSocketFactory
  312. .getSocketFactory())
  313. .build(), null, null, null);
  314. HttpClient httpClient = HttpClientBuilder.create().setConnectionManager(connManager).build();
  315. HttpPost httpPost = new HttpPost(url);
  316. RequestConfig requestConfig =
  317. RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).setConnectionRequestTimeout(10000)
  318. .build();
  319. httpPost.setConfig(requestConfig);
  320. StringEntity postEntity = new StringEntity(data, "UTF-8");
  321. httpPost.addHeader("Content-Type", "text/xml");
  322. // httpPost.addHeader("User-Agent", "wxpay sdk java v1.0 " + CommonWxPayPropertiesBuilder.instance().getMchId());
  323. httpPost.addHeader("User-Agent", "wxpay sdk java v1.0 " + "1517534731");
  324. httpPost.setEntity(postEntity);
  325. try {
  326. HttpResponse httpResponse = httpClient.execute(httpPost);
  327. HttpEntity httpEntity = httpResponse.getEntity();
  328. String reusltObj = null;
  329. reusltObj = EntityUtils.toString(httpEntity, "UTF-8");
  330. logger.info("请求结果:" + reusltObj);
  331. return reusltObj;
  332. } catch (IOException e) {
  333. e.printStackTrace();
  334. }
  335. return "";
  336. }
  337. /**
  338. * 请求,只请求一次,不做重试
  339. *
  340. * @param url
  341. * @param params
  342. * @return
  343. * @throws Exception
  344. */
  345. public static String requestOnceGet(final String url, Map params) {
  346. StringBuffer strtTotalURL = new StringBuffer(EMPTY);
  347. BasicHttpClientConnectionManager connManager;
  348. connManager = new BasicHttpClientConnectionManager(RegistryBuilder.<ConnectionSocketFactory>create()
  349. .register("http", PlainConnectionSocketFactory
  350. .getSocketFactory()).register("https",
  351. SSLConnectionSocketFactory
  352. .getSocketFactory())
  353. .build(), null, null, null);
  354. HttpClient httpClient = HttpClientBuilder.create().setConnectionManager(connManager).build();
  355. HttpGet httpGet = new HttpGet(url);
  356. RequestConfig requestConfig =
  357. RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).setConnectionRequestTimeout(10000)
  358. .build();
  359. httpGet.setConfig(requestConfig);
  360. httpGet.addHeader("Content-Type", "text/xml");
  361. // httpGet.addHeader("User-Agent", "wxpay sdk java v1.0 " + CommonWxPayPropertiesBuilder.instance().getMchId());
  362. httpGet.addHeader("User-Agent", "wxpay sdk java v1.0 " + "1517534731");
  363. if (strtTotalURL.indexOf("?") == -1) {
  364. strtTotalURL.append(url).append("?").append(getUrl(params, "UTF-8"));
  365. } else {
  366. strtTotalURL.append(url).append("&").append(getUrl(params, "UTF-8"));
  367. }
  368. try {
  369. HttpResponse httpResponse = httpClient.execute(httpGet);
  370. HttpEntity httpEntity = httpResponse.getEntity();
  371. String reusltObj = EntityUtils.toString(httpEntity, "UTF-8");
  372. logger.info("请求结果:" + reusltObj);
  373. return reusltObj;
  374. } catch (Exception e) {
  375. e.printStackTrace();
  376. }
  377. return "";
  378. }
  379. /**
  380. * 据Map生成URL字符串
  381. *
  382. * @param map Map
  383. * @param valueEnc URL编码
  384. * @return URL
  385. */
  386. private static String getUrl(Map<String, String> map, String valueEnc) {
  387. if (null == map || map.keySet().size() == 0) {
  388. return (EMPTY);
  389. }
  390. StringBuffer url = new StringBuffer();
  391. Set<String> keys = map.keySet();
  392. for (Iterator<String> it = keys.iterator(); it.hasNext(); ) {
  393. String key = it.next();
  394. if (map.containsKey(key)) {
  395. String val = map.get(key);
  396. String str = val != null ? val : EMPTY;
  397. try {
  398. str = URLEncoder.encode(str, valueEnc);
  399. } catch (UnsupportedEncodingException e) {
  400. e.printStackTrace();
  401. }
  402. url.append(key).append("=").append(str).append(URL_PARAM_CONNECT_FLAG);
  403. }
  404. }
  405. String strURL = EMPTY;
  406. strURL = url.toString();
  407. if (URL_PARAM_CONNECT_FLAG.equals(EMPTY + strURL.charAt(strURL.length() - 1))) {
  408. strURL = strURL.substring(0, strURL.length() - 1);
  409. }
  410. return (strURL);
  411. }
  412. /**
  413. * 调用付款码支付逻辑
  414. *
  415. * @param shop_name 门店名称
  416. * @param orderBizType 订单业务类型
  417. * @param attach 附加数据,该字段主要用于商户携带订单的自定义数据,如无可为null
  418. * @param out_trade_no 商户订单编号
  419. * @param orderMoney 订单总金额,单位:元
  420. * @param ip 当前机器ip
  421. * @param auth_code 扫码得到支付授权码
  422. * @return 微信返回信息
  423. */
  424. public static WechatMicropayApiResult wxMicropay(String shop_name, String orderBizType, String attach,
  425. String out_trade_no, double orderMoney, String ip,
  426. String auth_code) {
  427. //初始化请求微信服务器的配置信息包括appid密钥等
  428. //转换金钱格式
  429. BigDecimal bdOrderMoney = new BigDecimal(orderMoney, MathContext.DECIMAL32);
  430. //构建请求参数
  431. Map<Object, Object> params =
  432. buildMicropayRequsetMapParam(shop_name, orderBizType, attach, out_trade_no, bdOrderMoney, ip,
  433. auth_code);
  434. String mapToXml = MapUtils.convertMap2Xml(params);
  435. //请求微信
  436. String reponseXml = sendMicropaySSLPostToWx(mapToXml);
  437. WechatMicropayApiResult result =
  438. (WechatMicropayApiResult) XmlUtil.xmlStrToBean(reponseXml, WechatMicropayApiResult.class);
  439. if (WXTradeState.SUCCESS.getCode().equals(result.getReturn_code()) && "OK".equals(result.getReturn_msg())) {
  440. //支付成功
  441. if (WXTradeState.SUCCESS.getCode().equals(result.getResult_code())) {
  442. result.setTrade_state(WXTradeState.SUCCESS.getCode());
  443. } else if ("FAIL".equals(result.getResult_code())) {
  444. //支付中
  445. if ("USERPAYING".equals(result.getErr_code()) || "SYSTEMERROR".equals(result.getErr_code()) ||
  446. "BANKERROR".equals(result.getErr_code())) {
  447. result.setTrade_state(WXTradeState.USERPAYING.getCode());
  448. //支付失败
  449. } else {
  450. result.setTrade_state(WXTradeState.PAYERROR.getCode());
  451. }
  452. }
  453. }
  454. return result;
  455. }
  456. public static WechatReverseApiResult wxReverse(String out_trade_no) {
  457. //初始化请求微信服务器的配置信息包括appid密钥等
  458. //构建请求参数
  459. Map<Object, Object> params = buildReverseRequsetMapParam(out_trade_no);
  460. String mapToXml = MapUtils.convertMap2Xml(params);
  461. //请求微信
  462. String reponseXml = sendReverseSSLPostToWx(mapToXml, WechatConfig.getSslcsf());
  463. WechatReverseApiResult result =
  464. (WechatReverseApiResult) XmlUtil.xmlStrToBean(reponseXml, WechatReverseApiResult.class);
  465. return result;
  466. }
  467. /**
  468. * 方法描述:微信查询订单逻辑
  469. * 创建时间:2018年11月02日 上午11:04:25
  470. * 作者: huangyaqin
  471. *
  472. * @param
  473. * @return
  474. */
  475. public static WechatRefundApiResult wxOrderQuery(String out_trade_no) {
  476. //初始化请求微信服务器的配置信息包括appid密钥等
  477. //构建请求参数
  478. Map<Object, Object> params = buildQueryRequsetMapParam(out_trade_no);
  479. String mapToXml = MapUtils.convertMap2Xml(params);
  480. //请求微信
  481. String reponseXml = sendQuerySSLPostToWx(mapToXml);
  482. WechatRefundApiResult result =
  483. (WechatRefundApiResult) XmlUtil.xmlStrToBean(reponseXml, WechatRefundApiResult.class);
  484. return result;
  485. }
  486. /**
  487. * 方法描述:微信查询订单逻辑
  488. * 创建时间:2018年11月02日 上午11:04:25
  489. * 作者: huangyaqin
  490. *
  491. * @param
  492. * @return
  493. */
  494. public static WechatRefundApiResult wxOrderQueryByTransactionId(String payTransactionId) {
  495. //初始化请求微信服务器的配置信息包括appid密钥等
  496. //构建请求参数
  497. Map<Object, Object> params = new HashMap<Object, Object>();
  498. params.put("appid", CommonWxPayPropertiesBuilder.instance().getAppId());//微信分配的公众账号ID(企业号corpid即为此appId)
  499. params.put("mch_id", CommonWxPayPropertiesBuilder.instance().getMchId());//微信支付分配的商户号
  500. params.put("transaction_id", payTransactionId);//微信的订单号
  501. params.put("nonce_str", CharUtil.getRandomString(16));//随机字符串,不长于32位。推荐随机数生成算法
  502. //签名前必须要参数全部写在前面
  503. params.put("sign", arraySign(params, CommonWxPayPropertiesBuilder.instance().getPaySignKey()));//签名
  504. String mapToXml = MapUtils.convertMap2Xml(params);
  505. //请求微信
  506. String reponseXml = sendQuerySSLPostToWx(mapToXml);
  507. WechatRefundApiResult result =
  508. (WechatRefundApiResult) XmlUtil.xmlStrToBean(reponseXml, WechatRefundApiResult.class);
  509. return result;
  510. }
  511. /**
  512. * 绑定提交付款码支付请求参数
  513. *
  514. * @param shop_name 门店名称
  515. * @param orderBizType 订单业务类型
  516. * @param attach 附加数据,该字段主要用于商户携带订单的自定义数据,如无可为null
  517. * @param out_trade_no 商户订单编号
  518. * @param orderMoney 订单总金额,单位:元
  519. * @param ip 当前机器ip
  520. * @param auth_code 扫码得到支付授权码
  521. * @return 提交付款码支付请求参数
  522. */
  523. private static Map<Object, Object> buildMicropayRequsetMapParam(String shop_name, String orderBizType,
  524. String attach, String out_trade_no,
  525. BigDecimal orderMoney, String ip,
  526. String auth_code) {
  527. Map<Object, Object> params = new HashMap<Object, Object>();
  528. params.put("appid", CommonWxPayPropertiesBuilder.instance().getAppId());//微信分配的公众账号ID(企业号corpid即为此appId)
  529. params.put("mch_id", CommonWxPayPropertiesBuilder.instance().getMchId());//微信支付分配的商户号
  530. params.put("nonce_str", CharUtil.getRandomString(16));//随机字符串,不长于32位。推荐随机数生成算法
  531. String orderBizTypeZn = "普通货物";
  532. if ("00".equals(orderBizType)) {
  533. orderBizTypeZn = "保税备货";
  534. } else if ("02".equals(orderBizType)) {
  535. orderBizTypeZn = "保税展示补货";
  536. } else if ("10".equals(orderBizType)) {
  537. orderBizTypeZn = "保税展示跨境";
  538. }
  539. params.put("body", shop_name + "-" + orderBizTypeZn);//商品简单描述,不长于128位
  540. if (StringUtils.isNotEmpty(attach)) {
  541. params.put("attach", attach);//附加数据,不长于127位,该字段主要用于商户携带订单的自定义数据
  542. }
  543. params.put("out_trade_no", out_trade_no);//商户传给微信的订单号
  544. params.put("total_fee", orderMoney.multiply(Constant.ONE_HUNDRED).intValue());//订单总金额,单位为分,只能为整数
  545. params.put("spbill_create_ip", ip);//当前机器ip
  546. params.put("auth_code", auth_code);//扫码支付授权码,设备读取用户微信中的条码或者二维码信息
  547. //签名前必须要参数全部写在前面
  548. params.put("sign", arraySign(params, CommonWxPayPropertiesBuilder.instance().getPaySignKey()));//签名
  549. return params;
  550. }
  551. /**
  552. * 撤销订单输入参数
  553. *
  554. * @param out_trade_no 订单编号(发送到微信的编号)
  555. * @return 撤销订单输入参数
  556. */
  557. private static Map<Object, Object> buildReverseRequsetMapParam(String out_trade_no) {
  558. Map<Object, Object> params = new HashMap<Object, Object>();
  559. params.put("appid", CommonWxPayPropertiesBuilder.instance().getAppId());//微信分配的公众账号ID(企业号corpid即为此appId)
  560. params.put("mch_id", CommonWxPayPropertiesBuilder.instance().getMchId());//微信支付分配的商户号
  561. params.put("nonce_str", CharUtil.getRandomString(16));//随机字符串,不长于32位。推荐随机数生成算法
  562. params.put("out_trade_no", out_trade_no);//商户传给微信的订单号
  563. //签名前必须要参数全部写在前面
  564. params.put("sign", arraySign(params, CommonWxPayPropertiesBuilder.instance().getPaySignKey()));//签名
  565. return params;
  566. }
  567. /**
  568. * 绑定查询订单求输入参数
  569. *
  570. * @param out_trade_no 订单编号(发送到微信的编号)
  571. * @return 查询订单求输入参数
  572. */
  573. private static Map<Object, Object> buildQueryRequsetMapParam(String out_trade_no) {
  574. Map<Object, Object> params = new HashMap<Object, Object>();
  575. params.put("appid", CommonWxPayPropertiesBuilder.instance().getAppId());//微信分配的公众账号ID(企业号corpid即为此appId)
  576. params.put("mch_id", CommonWxPayPropertiesBuilder.instance().getMchId());//微信支付分配的商户号
  577. params.put("out_trade_no", out_trade_no);//商户传给微信的订单号
  578. params.put("nonce_str", CharUtil.getRandomString(16));//随机字符串,不长于32位。推荐随机数生成算法
  579. //签名前必须要参数全部写在前面
  580. params.put("sign", arraySign(params, CommonWxPayPropertiesBuilder.instance().getPaySignKey()));//签名
  581. return params;
  582. }
  583. /**
  584. * 线下扫码支付请求微信退款
  585. **/
  586. private static String sendMicropaySSLPostToWx(String mapToXml) {
  587. logger.info("*******付款码支付(WX Request:" + mapToXml);
  588. String xmlStr = sendSSLPostToWx(mapToXml, null, CommonWxPayPropertiesBuilder.instance().getMicropayUrl());
  589. logger.info("*******付款码支付(WX Response:" + xmlStr);
  590. return xmlStr;
  591. }
  592. /**
  593. * 请求撤销订单微信
  594. **/
  595. private static String sendReverseSSLPostToWx(String mapToXml, SSLConnectionSocketFactory sslcsf) {
  596. logger.info("*******撤销订单(WX Request:" + mapToXml);
  597. String xmlStr = sendSSLPostToWx(mapToXml, sslcsf, CommonWxPayPropertiesBuilder.instance().getReverseUrl());
  598. logger.info("*******撤销订单(WX Response:" + xmlStr);
  599. return xmlStr;
  600. }
  601. /**
  602. * 请求查询订单微信
  603. **/
  604. private static String sendQuerySSLPostToWx(String mapToXml) {
  605. logger.info("*******查询订单(WX Request:" + mapToXml);
  606. String xmlStr = sendSSLPostToWx(mapToXml, null, CommonWxPayPropertiesBuilder.instance().getOrderquery());
  607. logger.info("*******查询订单(WX Response:" + xmlStr);
  608. return xmlStr;
  609. }
  610. public static void main(String[] args) throws Exception {
  611. Map<Object, Object> parame = new TreeMap<Object, Object>();
  612. parame.put("mch_id", ResourceUtil.getConfigByName("\\conf\\wx-mp", "wx.mchId"));//
  613. String randomStr = CharUtil.getRandomNum(18).toUpperCase();
  614. parame.put("nonce_str", randomStr);//
  615. String sign = WechatUtil.arraySign(parame, ResourceUtil.getConfigByName("\\conf\\wx-mp", "wx.paySignKey"));
  616. parame.put("sign", sign);// 数字签证
  617. String xml = MapUtils.convertMap2Xml(parame);
  618. logger.info("xml:" + xml);
  619. Map<String, Object> resultUn = XmlUtil.xmlStrToMap(
  620. WechatUtil.requestOnce("https://apitest.mch.weixin.qq.com/sandboxnew/pay/getsignkey", xml));
  621. System.out.print(resultUn);
  622. }
  623. }