WechatUtil.java 28 KB

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