前言:

现在的APP的离不开微信支付, 现在项目里接入微信支付 , 微信支付的官方文档是:https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_1 。 也很明了,这里是我的示例。

作为客户端, 需要接入的功能大概四个:

1  下预购单, 这里生成签名去请求微信, 返回预购单交易号。 再拼接客户端需要的对象,让客户端发起支付。

2  回调接口, 当APP完成支付, 微信会调用商户的回调接口, 告诉回调结果。

3  退款, 发起的支付 需要退款, 这里需要下载证书。

4   查询订单结果, 回调可能失败, 这时候需要商户服务端主动去查询 订单处理结果。

代码:

1.1 微信工具类 生成签名, 验签等

  1. package com.yupaopao.trade.api.gateway.utils;
  2.  
  3. import com.yupaopao.trade.api.gateway.code.SignType;
  4. import com.yupaopao.trade.api.gateway.code.WXPayConstants;
  5. import org.jdom2.Document;
  6. import org.jdom2.Element;
  7. import org.jdom2.input.SAXBuilder;
  8. import org.w3c.dom.Node;
  9. import org.w3c.dom.NodeList;
  10.  
  11. import javax.crypto.Mac;
  12. import javax.crypto.spec.SecretKeySpec;
  13. import javax.xml.parsers.DocumentBuilder;
  14. import javax.xml.parsers.DocumentBuilderFactory;
  15. import javax.xml.transform.OutputKeys;
  16. import javax.xml.transform.Transformer;
  17. import javax.xml.transform.TransformerFactory;
  18. import javax.xml.transform.dom.DOMSource;
  19. import javax.xml.transform.stream.StreamResult;
  20. import java.io.*;
  21. import java.net.ConnectException;
  22. import java.net.HttpURLConnection;
  23. import java.net.InetAddress;
  24. import java.net.URL;
  25. import java.security.MessageDigest;
  26. import java.util.*;
  27.  
  28. public class WxUtil {
  29.  
  30. /**
  31. * XML格式字符串转换为Map
  32. *
  33. * @param strXML XML字符串
  34. * @return XML数据转换后的Map
  35. * @throws Exception
  36. */
  37. public static Map<String, String> xmlToMap(String strXML) throws Exception {
  38. Map<String, String> data = new HashMap<String, String>();
  39. DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
  40. DocumentBuilder documentBuilder= documentBuilderFactory.newDocumentBuilder();
  41. InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
  42. org.w3c.dom.Document doc = documentBuilder.parse(stream);
  43. doc.getDocumentElement().normalize();
  44. NodeList nodeList = doc.getDocumentElement().getChildNodes();
  45. for (int idx=0; idx<nodeList.getLength(); ++idx) {
  46. Node node = nodeList.item(idx);
  47. if (node.getNodeType() == Node.ELEMENT_NODE) {
  48. org.w3c.dom.Element element = (org.w3c.dom.Element) node;
  49. data.put(element.getNodeName(), element.getTextContent());
  50. }
  51. }
  52. try {
  53. stream.close();
  54. }
  55. catch (Exception ex) {
  56.  
  57. }
  58. return data;
  59. }
  60.  
  61. /**
  62. * 将Map转换为XML格式的字符串
  63. *
  64. * @param data Map类型数据
  65. * @return XML格式的字符串
  66. * @throws Exception
  67. */
  68. public static String mapToXml(Map<String, String> data) throws Exception {
  69. DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
  70. DocumentBuilder documentBuilder= documentBuilderFactory.newDocumentBuilder();
  71. org.w3c.dom.Document document = documentBuilder.newDocument();
  72. org.w3c.dom.Element root = document.createElement("xml");
  73. document.appendChild(root);
  74. for (String key: data.keySet()) {
  75. String value = data.get(key);
  76. if (value == null) {
  77. value = "";
  78. }
  79. value = value.trim();
  80. org.w3c.dom.Element filed = document.createElement(key);
  81. filed.appendChild(document.createTextNode(value));
  82. root.appendChild(filed);
  83. }
  84. TransformerFactory tf = TransformerFactory.newInstance();
  85. Transformer transformer = tf.newTransformer();
  86. DOMSource source = new DOMSource(document);
  87. transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
  88. transformer.setOutputProperty(OutputKeys.INDENT, "yes");
  89. StringWriter writer = new StringWriter();
  90. StreamResult result = new StreamResult(writer);
  91. transformer.transform(source, result);
  92. String output = writer.getBuffer().toString(); //.replaceAll("\n|\r", "");
  93. try {
  94. writer.close();
  95. }
  96. catch (Exception ex) {
  97. }
  98. return output;
  99. }
  100.  
  101. /**
  102. * 生成带有 sign 的 XML 格式字符串
  103. *
  104. * @param data Map类型数据
  105. * @param key API密钥
  106. * @return 含有sign字段的XML
  107. */
  108. public static String generateSignedXml(final Map<String, String> data, String key) throws Exception {
  109. return generateSignedXml(data, key, SignType.MD5);
  110. }
  111.  
  112. /**
  113. * 生成带有 sign 的 XML 格式字符串
  114. *
  115. * @param data Map类型数据
  116. * @param key API密钥
  117. * @param signType 签名类型
  118. * @return 含有sign字段的XML
  119. */
  120. public static String generateSignedXml(final Map<String, String> data, String key, SignType signType) throws Exception {
  121. String sign = generateSignature(data, key, signType);
  122. data.put(WXPayConstants.FIELD_SIGN, sign);
  123. return mapToXml(data);
  124. }
  125.  
  126. /**
  127. * 判断签名是否正确
  128. *
  129. * @param xmlStr XML格式数据
  130. * @param key API密钥
  131. * @return 签名是否正确
  132. * @throws Exception
  133. */
  134. public static boolean isSignatureValid(String xmlStr, String key) throws Exception {
  135. Map<String, String> data = xmlToMap(xmlStr);
  136. if (!data.containsKey(WXPayConstants.FIELD_SIGN) ) {
  137. return false;
  138. }
  139. String sign = data.get(WXPayConstants.FIELD_SIGN);
  140. return generateSignature(data, key).equals(sign);
  141. }
  142.  
  143. /**
  144. * 判断签名是否正确,必须包含sign字段,否则返回false。使用MD5签名。
  145. *
  146. * @param data Map类型数据
  147. * @param key API密钥
  148. * @return 签名是否正确
  149. * @throws Exception
  150. */
  151. public static boolean isSignatureValid(Map<String, String> data, String key) throws Exception {
  152. return isSignatureValid(data, key, SignType.MD5);
  153. }
  154.  
  155. /**
  156. * 判断签名是否正确,必须包含sign字段,否则返回false。
  157. *
  158. * @param data Map类型数据
  159. * @param key API密钥
  160. * @param signType 签名方式
  161. * @return 签名是否正确
  162. * @throws Exception
  163. */
  164. public static boolean isSignatureValid(Map<String, String> data, String key, SignType signType) throws Exception {
  165. if (!data.containsKey(WXPayConstants.FIELD_SIGN) ) {
  166. return false;
  167. }
  168. String sign = data.get(WXPayConstants.FIELD_SIGN);
  169. return generateSignature(data, key, signType).equals(sign);
  170. }
  171.  
  172. /**
  173. * 生成签名
  174. *
  175. * @param data 待签名数据
  176. * @param key API密钥
  177. * @return 签名
  178. */
  179. public static String generateSignature(final Map<String, String> data, String key) throws Exception {
  180. return generateSignature(data, key, SignType.MD5);
  181. }
  182.  
  183. /**
  184. * 生成签名. 注意,若含有sign_type字段,必须和signType参数保持一致。
  185. *
  186. * @param data 待签名数据
  187. * @param key API密钥
  188. * @param signType 签名方式
  189. * @return 签名
  190. */
  191. public static String generateSignature(final Map<String, String> data, String key, SignType signType) throws Exception {
  192. Set<String> keySet = data.keySet();
  193. String[] keyArray = keySet.toArray(new String[keySet.size()]);
  194. Arrays.sort(keyArray);
  195. StringBuilder sb = new StringBuilder();
  196. for (String k : keyArray) {
  197. if (k.equals(WXPayConstants.FIELD_SIGN)) {
  198. continue;
  199. }
  200. if (data.get(k).trim().length() > 0) // 参数值为空,则不参与签名
  201. sb.append(k).append("=").append(data.get(k).trim()).append("&");
  202. }
  203. sb.append("key=").append(key);
  204. if (SignType.MD5.equals(signType)) {
  205. return MD5(sb.toString()).toUpperCase();
  206. }
  207. else if (SignType.HMACSHA256.equals(signType)) {
  208. return HMACSHA256(sb.toString(), key);
  209. }
  210. else {
  211. throw new Exception(String.format("Invalid sign_type: %s", signType));
  212. }
  213. }
  214.  
  215. /**
  216. * 获取随机字符串 Nonce Str
  217. *
  218. * @return String 随机字符串
  219. */
  220. public static String generateNonceStr() {
  221. return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
  222. }
  223.  
  224. /**
  225. * 生成 MD5
  226. *
  227. * @param data 待处理数据
  228. * @return MD5结果
  229. */
  230. public static String MD5(String data) throws Exception {
  231. MessageDigest md = MessageDigest.getInstance("MD5");
  232. byte[] array = md.digest(data.getBytes("UTF-8"));
  233. StringBuilder sb = new StringBuilder();
  234. for (byte item : array) {
  235. sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
  236. }
  237. return sb.toString().toUpperCase();
  238. }
  239.  
  240. /**
  241. * 生成 HMACSHA256
  242. * @param data 待处理数据
  243. * @param key 密钥
  244. * @return 加密结果
  245. * @throws Exception
  246. */
  247. public static String HMACSHA256(String data, String key) throws Exception {
  248. Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
  249. SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
  250. sha256_HMAC.init(secret_key);
  251. byte[] array = sha256_HMAC.doFinal(data.getBytes("UTF-8"));
  252. StringBuilder sb = new StringBuilder();
  253. for (byte item : array) {
  254. sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
  255. }
  256. return sb.toString().toUpperCase();
  257. }
  258.  
  259. /**
  260. * xml解析
  261. * @param strxml
  262. * @return
  263. * @throws Exception
  264. */
  265. public static Map<String, String> doXMLParse(String strxml) throws Exception {
  266. Map<String,String> m = new HashMap<String,String>();
  267. try {
  268. strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");
  269. if(null == strxml || "".equals(strxml)) {
  270. return null;
  271. }
  272. InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
  273. SAXBuilder builder = new SAXBuilder();
  274. Document doc = builder.build(in);
  275. Element root = doc.getRootElement();
  276. List list = root.getChildren();
  277. Iterator it = list.iterator();
  278. while(it.hasNext()) {
  279. Element e = (Element) it.next();
  280. String k = e.getName();
  281. String v = "";
  282. List children = e.getChildren();
  283. if(children.isEmpty()) {
  284. v = e.getTextNormalize();
  285. } else {
  286. v = getChildrenText(children);
  287. }
  288.  
  289. m.put(k, v);
  290. }
  291.  
  292. //关闭流
  293. in.close();
  294. } catch (Exception e) {
  295. e.printStackTrace();
  296. }
  297. return m;
  298.  
  299. }
  300.  
  301. /**
  302. * 获取子节点数据
  303. * @param children
  304. * @return
  305. */
  306. public static String getChildrenText(List children) {
  307. StringBuffer sb = new StringBuffer();
  308. if(!children.isEmpty()) {
  309. Iterator it = children.iterator();
  310. while(it.hasNext()) {
  311. Element e = (Element) it.next();
  312. String name = e.getName();
  313. String value = e.getTextNormalize();
  314. List list = e.getChildren();
  315. sb.append("<" + name + ">");
  316. if(!list.isEmpty()) {
  317. sb.append(getChildrenText(list));
  318. }
  319. sb.append(value);
  320. sb.append("</" + name + ">");
  321. }
  322. }
  323. return sb.toString();
  324. }
  325.  
  326. //发起微信支付请求
  327. public static String httpsRequest(String requestUrl, String requestMethod, String outputStr) {
  328. try {
  329. URL url = new URL(requestUrl);
  330. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  331.  
  332. conn.setDoOutput(true);
  333. conn.setDoInput(true);
  334. conn.setUseCaches(false);
  335. // 设置请求方式(GET/POST)
  336. conn.setRequestMethod(requestMethod);
  337. conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
  338. // 当outputStr不为null时向输出流写数据
  339. if (null != outputStr) {
  340. OutputStream outputStream = conn.getOutputStream();
  341. // 注意编码格式
  342. outputStream.write(outputStr.getBytes("UTF-8"));
  343. outputStream.close();
  344. }
  345. // 从输入流读取返回内容
  346. InputStream inputStream = conn.getInputStream();
  347. InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
  348. BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
  349. String str = null;
  350. StringBuffer buffer = new StringBuffer();
  351. while ((str = bufferedReader.readLine()) != null) {
  352. buffer.append(str);
  353. }
  354. // 释放资源
  355. bufferedReader.close();
  356. inputStreamReader.close();
  357. inputStream.close();
  358. inputStream = null;
  359. conn.disconnect();
  360. return buffer.toString();
  361. } catch (ConnectException ce) {
  362. ce.printStackTrace();
  363. } catch (Exception e) {
  364. e.printStackTrace();
  365. }
  366. return null;
  367. }
  368.  
  369. /**
  370. * 返回给微信服务端的xml
  371. * @param return_code
  372. * @return
  373. */
  374. public static String returnXML(String return_code) {
  375.  
  376. return "<xml><return_code><![CDATA["
  377.  
  378. + return_code
  379.  
  380. + "]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
  381. }
  382.  
  383. //Map转xml数据
  384. public static String GetMapToXML(Map<String,String> param){
  385. StringBuffer sb = new StringBuffer();
  386. sb.append("<xml>");
  387. for (Map.Entry<String,String> entry : param.entrySet()) {
  388. sb.append("<"+ entry.getKey() +">");
  389. sb.append(entry.getValue());
  390. sb.append("</"+ entry.getKey() +">");
  391. }
  392. sb.append("</xml>");
  393. return sb.toString();
  394. }
  395.  
  396. /**
  397. * 获取Ip
  398. * @return
  399. */
  400. public static String GetIp() {
  401. InetAddress ia=null;
  402. try {
  403. ia= InetAddress.getLocalHost();
  404. String localip=ia.getHostAddress();
  405. return localip;
  406. } catch (Exception e) {
  407. return null;
  408. }
  409. }
  410.  
  411. public static String getRequestXml(SortedMap<String,String> parameters){
  412. StringBuffer sb = new StringBuffer();
  413. sb.append("<xml>");
  414. Set es = parameters.entrySet();
  415. Iterator it = es.iterator();
  416. while(it.hasNext()) {
  417. Map.Entry entry = (Map.Entry)it.next();
  418. String k = (String)entry.getKey();
  419. String v = (String)entry.getValue();
  420. if ("attach".equalsIgnoreCase(k)||"body".equalsIgnoreCase(k)||"sign".equalsIgnoreCase(k)) {
  421. sb.append("<"+k+">"+"<![CDATA["+v+"]]></"+k+">");
  422. }else {
  423. sb.append("<"+k+">"+v+"</"+k+">");
  424. }
  425. }
  426. sb.append("</xml>");
  427. return sb.toString();
  428. }
  429.  
  430. }

2 service实现类

  1. package com.yupaopao.trade.gateway.service.impl;
  2.  
  3. import com.yupaopao.trade.api.account.response.WXGzhResponse;
  4. import com.yupaopao.trade.api.account.response.WXPayResponse;
  5. import com.yupaopao.trade.api.gateway.code.*;
  6. import com.yupaopao.trade.api.gateway.request.PayRequest;
  7. import com.yupaopao.trade.api.gateway.request.RefundRequest;
  8. import com.yupaopao.trade.api.gateway.request.WeixinOrderFindRequest;
  9. import com.yupaopao.trade.api.gateway.sdk.qqpay.config.ClientCustomSSL;
  10. import com.yupaopao.trade.api.gateway.utils.WxUtil;
  11. import com.yupaopao.trade.api.payment.code.PaymentConstant;
  12. import com.yupaopao.trade.api.payment.dto.YppException;
  13. import com.yupaopao.trade.api.utils.IdWorker;
  14. import com.yupaopao.trade.common.config.ThirdUrlConfig;
  15. import com.yupaopao.trade.common.exception.TradeException;
  16. import com.yupaopao.trade.domain.mapper.PayMapper;
  17. import com.yupaopao.trade.domain.mapper.PaymentDetailMapper;
  18. import com.yupaopao.trade.domain.mapper.RefundDetailMapper;
  19. import com.yupaopao.trade.domain.model.PaymentDetail;
  20. import com.yupaopao.trade.domain.model.RefundDetail;
  21. import com.yupaopao.trade.gateway.service.WxPayService;
  22. import com.yupaopao.trade.payment.service.TradeService;
  23. import org.apache.http.HttpEntity;
  24. import org.apache.http.client.methods.CloseableHttpResponse;
  25. import org.apache.http.client.methods.HttpPost;
  26. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
  27. import org.apache.http.entity.StringEntity;
  28. import org.apache.http.impl.client.CloseableHttpClient;
  29. import org.apache.http.impl.client.HttpClients;
  30. import org.apache.http.ssl.SSLContexts;
  31. import org.apache.http.util.EntityUtils;
  32. import org.slf4j.Logger;
  33. import org.slf4j.LoggerFactory;
  34. import org.springframework.beans.factory.annotation.Autowired;
  35. import org.springframework.beans.factory.annotation.Value;
  36. import org.springframework.stereotype.Service;
  37. import org.springframework.util.ResourceUtils;
  38.  
  39. import javax.net.ssl.SSLContext;
  40. import javax.servlet.http.HttpServletRequest;
  41. import java.io.BufferedReader;
  42. import java.io.File;
  43. import java.io.FileInputStream;
  44. import java.io.InputStreamReader;
  45. import java.security.KeyStore;
  46. import java.util.HashMap;
  47. import java.util.Map;
  48. import java.util.SortedMap;
  49. import java.util.TreeMap;
  50.  
  51. /**
  52. * Created by zhuliangxing on 2017/4/21.
  53. */
  54. @Service
  55. public class WxpayServiceImpl implements WxPayService {
  56.  
  57. private static final Logger LOGGER = LoggerFactory.getLogger(WxpayServiceImpl.class);
  58.  
  59. @Autowired
  60. private PayMapper payMapper;
  61.  
  62. @Autowired
  63. private TradeService tradeService;
  64.  
  65. @Value("${third.callback.net_url}")
  66. private String notifyUrl;
  67.  
  68. @Autowired
  69. private PaymentDetailMapper paymentDetailsMapper;
  70.  
  71. @Autowired
  72. private RefundDetailMapper refundDetailMapper;
  73.  
  74. /**
  75. * 统一下单
  76. *
  77. * @param request
  78. * @return
  79. */
  80. public WXPayResponse wxPay(PayRequest request) {
  81. WXPayResponse response = new WXPayResponse();
  82.  
  83. PaymentDetail detail = null;
  84. Map<String, String> data = null;
  85. try {
  86. // 组装XML
  87. String xml = WXParamGenerate(request.getSubject(), request.getOutTradeNo(), request.getTotalFee());
  88. // 发送http请求到微信服务端,获取返回的参数
  89. String res = WxUtil.httpsRequest(WXPayConstants.WX_PAYURL, "POST", xml);
  90. data = WxUtil.doXMLParse(res);
  91. detail = new PaymentDetail();
  92. detail.setCallbackStatus(CallbackType.unCall.getStatusValue());
  93. detail.setUserId(request.getUserId());
  94. detail.setType(PayType.wxPay.getStatusValue());
  95. detail.setPaymentId(request.getPaymentId());
  96. detail.setOrderType(request.getOrderType());
  97. detail.setTotalFee(request.getTotalFee());
  98. detail.setStatus(PayStatus.unPay.getStatusValue());
  99. detail.setOutTradeNo(request.getOutTradeNo());
  100. detail.setSubject(request.getSubject());
  101.  
  102. Map<String, String> param = new HashMap<String, String>();
  103. param.put("appid", WXPayConstants.APP_ID);
  104.  
  105. param.put("partnerid", WXPayConstants.MCH_ID);
  106. param.put("prepayid", data.get("prepay_id"));
  107. param.put("noncestr", data.get("nonce_str"));
  108.  
  109. String timeStamp = System.currentTimeMillis() / 1000 + "";
  110. param.put("timestamp", timeStamp);
  111. param.put("package", "Sign=WXPay");
  112. String sign = WxUtil.generateSignature(param, WXPayConstants.WX_PARTNERKEY, SignType.MD5);
  113. response.setAppId(WXPayConstants.APP_ID);
  114. response.setPartnerId(WXPayConstants.MCH_ID);
  115. response.setTimestamp(timeStamp);
  116. response.setNoncestr(data.get("nonce_str"));
  117. response.setSign(sign);
  118. response.setPrepayId(data.get("prepay_id"));
  119. paymentDetailsMapper.insertPayment(detail);
  120. return response;
  121. } catch (Exception e) {
  122. throw new YppException(PayException.xmlParseError);
  123. }
  124. }
  125.  
  126. /**
  127. * 微信统一下单参数设置
  128. *
  129. * @param description
  130. * @param orderOutId
  131. * @param totalFee
  132. * @return
  133. * @throws Exception
  134. */
  135. public String WXParamGenerate(String description, String orderOutId, Long totalFee) throws Exception {
  136. Map<String, String> param = new HashMap<String, String>();
  137. param.put("appid", WXPayConstants.APP_ID);
  138. param.put("mch_id", WXPayConstants.MCH_ID);
  139. param.put("nonce_str", WxUtil.generateNonceStr());
  140. param.put("body", description);
  141. param.put("out_trade_no", orderOutId);
  142. param.put("total_fee", totalFee + "");
  143. param.put("spbill_create_ip", WxUtil.GetIp());
  144. param.put("notify_url", notifyUrl + WXPayConstants.NOTIFU_URL);
  145. param.put("trade_type", "APP");
  146. String sign = WxUtil.generateSignature(param, WXPayConstants.WX_PARTNERKEY, SignType.MD5);
  147. param.put("sign", sign);
  148. return WxUtil.GetMapToXML(param);
  149. }
  150.  
  151. /**
  152. * 拼接微信退款XML
  153. *
  154. * @param request
  155. * @return
  156. * @throws Exception
  157. */
  158. public static SortedMap<String, String> WXRefundParamGenerate(RefundRequest request) {
  159.  
  160. SortedMap<String, String> param = new TreeMap<String, String>();
  161. try {
  162. param.put("appid", WXPayConstants.APP_ID);
  163. param.put("mch_id", WXPayConstants.MCH_ID);
  164. param.put("nonce_str", WxUtil.generateNonceStr());
  165. param.put("out_trade_no", request.getOutTradeNo());
  166. // 支付网关生成订单流水
  167. param.put("out_refund_no", String.valueOf(IdWorker.nextId()));
  168. param.put("total_fee", String.valueOf(request.getTotalFee()));// 单位为分
  169. param.put("refund_fee", String.valueOf(request.getRefundFee()));// 单位为分
  170. param.put("op_user_id", WXPayConstants.MCH_ID);// 操作人员,默认为商户账号
  171. String sign = WxUtil.generateSignature(param, WXPayConstants.WX_PARTNERKEY, SignType.MD5);
  172. param.put("sign", sign);
  173. } catch (Exception e) {
  174. throw new YppException(PayException.signError);
  175. }
  176. return param;
  177. }
  178.  
  179. /**
  180. * 解析微信返回的xml 参数
  181. *
  182. * @param request
  183. */
  184. public Map<String, String> xmlParserCallback(HttpServletRequest request) {
  185. Map<String, String> map = null;
  186. BufferedReader reader = null;
  187. String line = "";
  188. String xmlString = null;
  189. try {
  190. reader = request.getReader();
  191. StringBuffer inputString = new StringBuffer();
  192.  
  193. while ((line = reader.readLine()) != null) {
  194. inputString.append(line);
  195. }
  196. xmlString = inputString.toString();
  197. request.getReader().close();
  198. LOGGER.info("----接收到的数据如下:---" + xmlString);
  199. map = WxUtil.doXMLParse(xmlString);
  200. } catch (Exception e) {
  201. throw new YppException(PayException.xmlParseError);
  202. }
  203. return map;
  204. }
  205.  
  206. /**
  207. * IO解析获取微信的数据
  208. *
  209. * @param request
  210. * @return
  211. */
  212. public String getXmlString(HttpServletRequest request) {
  213. BufferedReader reader = null;
  214. String line = "";
  215. String xmlString = null;
  216. try {
  217. reader = request.getReader();
  218. StringBuffer inputString = new StringBuffer();
  219.  
  220. while ((line = reader.readLine()) != null) {
  221. inputString.append(line);
  222. }
  223. xmlString = inputString.toString();
  224. } catch (Exception e) {
  225. throw new YppException(PayException.xmlParseError);
  226. }
  227.  
  228. return xmlString;
  229. }
  230.  
  231. /**
  232. * 微信回调
  233. *
  234. * @param request
  235. * @return
  236. */
  237. public String wxNotify(HttpServletRequest request) {
  238. LOGGER.info("微信正在回调》》》》》》》》》");
  239. PaymentDetail detail = null;
  240. String xmlString = "";
  241. String lastXml = "";
  242.  
  243. try {
  244. xmlString = getXmlString(request);
  245. LOGGER.info("微信返回的回调结果是:::::::" + xmlString);
  246. // 先解析返回的数据
  247. Map<String, String> dataMap = WxUtil.xmlToMap(xmlString);
  248. String returnCode = dataMap.get("return_code");
  249. // 通信成功
  250. if (ReturnStatus.success.getStatusValue().equals(returnCode)) {
  251. LOGGER.info("通信成功++++++++++++");
  252.  
  253. // 验证通过才能记到流水表中,否则不计入
  254. if (WxUtil.isSignatureValid(xmlString, WXPayConstants.WX_PARTNERKEY)) {
  255.  
  256. try {
  257. detail = new PaymentDetail();
  258. detail.setTradeNo(dataMap.get("transaction_id"));
  259. detail.setOutTradeNo(dataMap.get("out_trade_no"));
  260. if (dataMap.get("result_code").equals(ReturnStatus.success)) {
  261. detail.setStatus(PayStatus.paySuccess.getStatusValue());
  262. } else {
  263. detail.setStatus(PayStatus.payFail.getStatusValue());
  264. }
  265. detail.setType(PayType.wxPay.getStatusValue());
  266. // 设置为已经回调
  267. detail.setCallbackStatus(CallbackType.callable.getStatusValue());
  268. paymentDetailsMapper.updatePayment(detail);
  269. } catch (Exception e) {
  270. e.printStackTrace();
  271. }
  272.  
  273. }
  274. tradeService.dealWithPayCallBack(dataMap.get("out_trade_no").toString(),
  275. dataMap.get("transaction_id").toString(), PaymentConstant.PayCallBackStatus.SUCCESS,
  276. PaymentConstant.TradeAction.WEIXIN_ACCOUNT);
  277. lastXml = WxUtil.returnXML(ReturnStatus.success.getStatusValue());
  278. } else {
  279.  
  280. lastXml = WxUtil.returnXML(ReturnStatus.fail.getStatusValue());
  281. }
  282. } catch (Exception e) {
  283.  
  284. throw new TradeException(GatewayCode.PayBackError);
  285. }
  286. LOGGER.info("最终给微信的结果是:" + lastXml);
  287. return lastXml;
  288.  
  289. }
  290.  
  291. /**
  292. * 微信退款
  293. *
  294. * @param request
  295. * @return
  296. */
  297. public String wxRefund(RefundRequest request) {
  298.  
  299. RefundDetail detail = null;
  300. // 拼装Map
  301. SortedMap<String, String> map = WXRefundParamGenerate(request);
  302. // 拼装XML
  303. String requestXml = WxUtil.getRequestXml(map);
  304. // 获取返回数据
  305. String refundResult = "";
  306. try {
  307. refundResult = ClientCustomSSL.doRefund(WXPayConstants.WX_REFUND, requestXml);
  308. } catch (Exception e) {
  309. throw new TradeException(GatewayCode.RefundBackXmlError);
  310. }
  311. System.out.println("退款产生的json字符串:" + refundResult);
  312. // 转换为Map
  313. Map<String, String> responseMap = new HashMap<>();
  314. try {
  315. responseMap = WxUtil.doXMLParse(refundResult);
  316. } catch (Exception e) {
  317. throw new TradeException(GatewayCode.RefundBackXmlError);
  318. }
  319. String returnCode = responseMap.get("return_code");
  320. // 通信正常
  321. if (returnCode.equals(ReturnStatus.success.getStatusValue())) {
  322. String resultCode = responseMap.get("result_code");
  323. detail = new RefundDetail();
  324. // 微信生成的退款ID
  325. String tradeNo = responseMap.get("out_refund_no");
  326.  
  327. detail.setTradeNo(tradeNo);
  328. detail.setRefundId(IdWorker.unique());
  329. detail.setType(PayType.wxPay.getStatusValue());
  330. detail.setUserId(request.getUserId());
  331. detail.setSubject(responseMap.get("err_code_des"));
  332. detail.setorderOutId(request.getOutTradeNo());
  333. detail.setRefundFee(request.getRefundFee());
  334. detail.setTotalFee(request.getTotalFee());
  335. detail.setOriginTradeNo(tradeNo);
  336. // 退款成功
  337. if (resultCode.equals(ReturnStatus.success)) {
  338. detail.setStatus(PayStatus.paySuccess.getStatusValue());
  339. payMapper.saveRefund(detail);
  340. return ReturnStatus.success.getStatusValue();
  341.  
  342. } else {
  343. detail.setStatus(PayStatus.payFail.getStatusValue());
  344. refundDetailMapper.insertRefund(detail);
  345. return ReturnStatus.fail.getStatusValue();
  346.  
  347. }
  348.  
  349. } else {
  350. throw new TradeException(GatewayCode.RefundHasGone);
  351. }
  352.  
  353. }
  354.  
  355. /**
  356. * 微信公众号支付下单
  357. */
  358. @Override
  359. public WXGzhResponse wxGZHPay(PayRequest request) {
  360. WXGzhResponse response = new WXGzhResponse();
  361. PaymentDetail detail = null;
  362. Map<String, String> data = null;
  363. try {
  364. // 组装XML
  365. String xml = WXGZHParamGenerate(request.getSubject(), request.getOutTradeNo(), request.getTotalFee(),
  366. request.getPayExt().get("openId").toString());
  367. // 发送http请求到微信服务端,获取返回的参数
  368. String res = WxUtil.httpsRequest(WXPayConstants.WX_PAYURL, "POST", xml);
  369. data = WxUtil.doXMLParse(res);
  370. detail = new PaymentDetail();
  371. detail.setCallbackStatus(CallbackType.unCall.getStatusValue());
  372. detail.setUserId(request.getUserId());
  373. detail.setType(PayType.wxPay.getStatusValue());
  374. detail.setPaymentId(request.getPaymentId());
  375. detail.setOrderType(request.getOrderType());
  376. detail.setTotalFee(request.getTotalFee());
  377. detail.setStatus(PayStatus.unPay.getStatusValue());
  378. detail.setOutTradeNo(request.getOutTradeNo());
  379. detail.setSubject(request.getSubject());
  380.  
  381. String timeStamp = System.currentTimeMillis() / 1000 + "";
  382. Map<String, String> param = new HashMap<String, String>();
  383. param.put("appId", WXPayConstants.WEIXIN_GZH_APPID);
  384.  
  385. param.put("signType", "MD5");
  386. param.put("nonceStr", data.get("nonce_str"));
  387.  
  388. param.put("timeStamp", timeStamp);
  389. param.put("package", "prepay_id=" + data.get("prepay_id"));
  390.  
  391. String sign = WxUtil.generateSignature(param, WXPayConstants.WEIXIN_GZH_KEY, SignType.MD5);
  392.  
  393. response.setAppId(WXPayConstants.WEIXIN_GZH_APPID);
  394. response.setNonceStr(data.get("nonce_str"));
  395. response.setPaySign(sign);
  396. response.setTimeStamp(timeStamp);
  397. response.setWxpackage("prepay_id=" + data.get("prepay_id"));
  398. response.setSignType("MD5");
  399. payMapper.saveDetail(detail);
  400. return response;
  401. } catch (Exception e) {
  402. e.printStackTrace();
  403. throw new YppException(PayException.xmlParseError);
  404. }
  405. }
  406.  
  407. /**
  408. * 微信公众号统一下单
  409. *
  410. * @param description
  411. * @param orderOutId
  412. * @param totalFee
  413. * @return
  414. * @throws Exception
  415. */
  416. public String WXGZHParamGenerate(String description, String orderOutId, Long totalFee, String openId)
  417. throws Exception {
  418. Map<String, String> param = new HashMap<String, String>();
  419. param.put("appid", WXPayConstants.WEIXIN_GZH_APPID);
  420. param.put("mch_id", WXPayConstants.WEIXIN_GZH_MACHID);
  421. param.put("nonce_str", WxUtil.generateNonceStr());
  422. param.put("body", description);
  423. param.put("out_trade_no", orderOutId);
  424. param.put("openid", openId);
  425. param.put("total_fee", totalFee + "");
  426. param.put("spbill_create_ip", WxUtil.GetIp());
  427. param.put("notify_url", notifyUrl + WXPayConstants.NOTIFU_URL);
  428. param.put("trade_type", "JSAPI");
  429. String sign = WxUtil.generateSignature(param, WXPayConstants.WEIXIN_GZH_KEY, SignType.MD5);
  430. param.put("sign", sign);
  431. return WxUtil.GetMapToXML(param);
  432. }
  433.  
  434. /**
  435. * 微信公众号账单查询
  436. */
  437. @Override
  438. public void wxGZHOrderFind(WeixinOrderFindRequest request) {
  439. Map<String, String> data = null;
  440. try {
  441. String xml = WXGZHOrderGenerate(request.getOutTradeNo());
  442. String res = WxUtil.httpsRequest(WXPayConstants.WEIXIN_ORDER_FIND_URL, "POST", xml);
  443. data = WxUtil.doXMLParse(res);
  444. // 通信异常
  445. if (!data.get("return_code").equals("SUCCESS")) {
  446. throw new TradeException(GatewayCode.CommunicationError);
  447. }
  448. if (!data.get("result_code").equals("SUCCESS")) {
  449. throw new TradeException(GatewayCode.OrderFindErrror);
  450. }
  451. if (!data.get("trade_state").equals("SUCCESS")) {
  452. throw new TradeException(GatewayCode.OrderPayError);
  453. }
  454.  
  455. } catch (Exception e) {
  456. throw new TradeException(GatewayCode.PayXmlError);
  457. }
  458.  
  459. }
  460.  
  461. /**
  462. * 微信公众号生成订单。
  463. *
  464. * @param orderOutId
  465. * @return
  466. * @throws Exception
  467. */
  468. public String WXGZHOrderGenerate(String orderOutId) throws Exception {
  469. Map<String, String> param = new HashMap<String, String>();
  470. param.put("appid", WXPayConstants.WEIXIN_GZH_APPID);
  471. param.put("mch_id", WXPayConstants.WEIXIN_GZH_MACHID);
  472. param.put("nonce_str", WxUtil.generateNonceStr());
  473. param.put("out_trade_no", orderOutId);
  474. String sign = WxUtil.generateSignature(param, WXPayConstants.WEIXIN_GZH_KEY, SignType.MD5);
  475. param.put("sign", sign);
  476. return WxUtil.GetMapToXML(param);
  477. }
  478. }

3下单返回的参数model 给 APP

  1. package com.yupaopao.trade.api.account.response;
  2.  
  3. import com.alibaba.fastjson.JSONObject;
  4.  
  5. public class WXPayResponse {
  6.  
  7. private String appId;
  8.  
  9. private String partnerId;
  10.  
  11. private String wxpackage="Sign=WXPay";
  12.  
  13. private String noncestr;
  14.  
  15. private String timestamp;
  16.  
  17. private String sign;
  18.  
  19. private String prepayId;
  20.  
  21. public String getAppId() {
  22. return appId;
  23. }
  24.  
  25. public void setAppId(String appId) {
  26. this.appId = appId;
  27. }
  28.  
  29. public String getPartnerId() {
  30. return partnerId;
  31. }
  32.  
  33. public void setPartnerId(String partnerId) {
  34. this.partnerId = partnerId;
  35. }
  36.  
  37. public String getWxpackage() {
  38. return wxpackage;
  39. }
  40.  
  41. public void setWxpackage(String wxpackage) {
  42. this.wxpackage = wxpackage;
  43. }
  44.  
  45. public String getNoncestr() {
  46. return noncestr;
  47. }
  48.  
  49. public void setNoncestr(String noncestr) {
  50. this.noncestr = noncestr;
  51. }
  52.  
  53. public String getTimestamp() {
  54. return timestamp;
  55. }
  56.  
  57. public void setTimestamp(String timestamp) {
  58. this.timestamp = timestamp;
  59. }
  60.  
  61. public String getSign() {
  62. return sign;
  63. }
  64.  
  65. public void setSign(String sign) {
  66. this.sign = sign;
  67. }
  68.  
  69. public String getPrepayId() {
  70. return prepayId;
  71. }
  72.  
  73. public void setPrepayId(String prepayId) {
  74. this.prepayId = prepayId;
  75. }
  76.  
  77. @Override
  78. public String toString() {
  79.  
  80. JSONObject json = new JSONObject();
  81. json.put("appId", appId);
  82. json.put("partnerId", partnerId);
  83. json.put("wxpackage", wxpackage);
  84. json.put("noncestr", noncestr);
  85. json.put("timestamp", timestamp);
  86. json.put("sign", sign);
  87. json.put("prepayId", prepayId);
  88.  
  89. return json.toString();
  90. }
  91.  
  92. }
  1. /**
  2. * 微信支付回调
  3. *
  4. * @param request
  5. * @param response
  6. * @return
  7. * @throws Exception
  8. */
  9. @RequestMapping(method = RequestMethod.POST, value = "/wx/wxCallback")
  10. public YppResponse wxCallback(HttpServletRequest request, HttpServletResponse response) throws Exception {
  11. return YppResponse.success(wxPayService.wxNotify(request));
  12. }

Java+微信支付(下预购单+回调+退款+查询账单)的更多相关文章

  1. JAVA微信支付~

    1,简单说明 现在好多项目上都需要用到微信支付接口,官方文档上也是简单的描述了下,技术不高深的真的难以理解(我自己看官方文档就看不懂),还是需要自己收集,总结, 网上看了好多 有些照着弄最后还是没法成 ...

  2. 通知url必须为直接可访问的url,不能携带参数 异步接收微信支付结果通知的回调地址 不能携带参数。 回调地址后是否可以加自定义参数 同步回调地址 异步回调地址 return_url和notify_url的区别

    [微信支付]微信小程序支付开发者文档 https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=9_7 通知url必须为直接可访问的 ...

  3. 微信支付重复回调,java微信支付回调问题

    这几天一直在研究微信支付回调这个问题,发现之前微信支付回调都是正常的也没怎么在意,今天在自己项目上测试的时候发现相同的代码在我这个项目上微信支付回调老是重复执行导致支付成功之后的回调逻辑一直在执行,很 ...

  4. JAVA微信支付多次回调方法解决方案

    @WebServlet("/ActionServlet")public class PayWxOrderingReqCBS extends HttpServlet { public ...

  5. Java 微信支付分对接记录 (先享后付)

    微信支付分(先享后付)对接记录: 微信支付分对接步骤 填写开通支付分的申请表格 此步骤大概需要审核 1-3 个工作日; (模板-服务信息配置表-[先享后付免确认]-[商户名].xls) 填写商户信息 ...

  6. JAVA微信支付——微信公众号内支付 代码

    官方文档:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1 微信PC二维码支付方式参考:https://www.cnblogs. ...

  7. JAVA微信支付——企业付款(企业向微信用户个人付款、转账)

    本地开发环境支付回调调试方法可以参考:https://www.cnblogs.com/pxblog/p/11623053.html 需要自行引入相关依赖 官方文档地址:https://pay.weix ...

  8. JAVA微信支付接口开发——支付

    微信支付接口开发--支付 这几天在做支付服务,系统接入了支付宝.微信.银联三方支付接口.个人感觉支付宝的接口开发较为简单,并且易于测试. 关于数据传输,微信是用xml,所以需要对xml进行解析. 1. ...

  9. JAVA微信支付代码(WeChatPay.java 才是调用类)

    微信官方文档:https://pay.weixin.qq.com/wiki/doc/api/index.html MD5Util.java package weixin; import java.se ...

随机推荐

  1. js中不同类型作比较

    示例: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <met ...

  2. Linux系统搭建Red5服务器

    Linux系统搭建Red5服务器 Red5 是 支持Windows,Linux等多平台的RTMP流媒体服务器,Windows下搭建相对容易,图形界面操作比较简单,Linux服务器的环境下没有图形界面, ...

  3. java oop第09章_JDBC02(CRUD操作)

    第09章_JDBC02(CRUD操作) CRUD(CREATE . RETIVE . UPDATE . DELETE)增删改查. DAO中会提供一些CRUD操作方法,调用者可以通过调用这些方法完成相应 ...

  4. android的webView内部https/http混合以及自适应屏幕

    两种请求都有的情况下,会导致WebView加载不出来. //自适应屏幕 settings.setUseWideViewPort(true); settings.setLoadWithOverviewM ...

  5. Virtualenv开发文档

    virtualenv是创建孤立的Python环境的工具.正在解决的基本问题是依赖和版本之一以及间接权限.想象一下,您有一个需要LibFoo版本1的应用程序,但另一个应用程序需要版本2.如何使用这两个应 ...

  6. log4j2 按日期分割,自动清理历史文件

    方式一:定义CronTriggeringPolicy <?xml version="1.0" encoding="UTF-8"?> <Conf ...

  7. 网络攻击之代理IP

    1.通过代理IP的好处: (1)隐藏自己真实上网地址 (2)突破宽带商访问限制

  8. thinkphp present标签

    present标签用于判断某个变量是否已经定义,用法: 大理石平台精度等级 <present name="name"> name已经赋值 </present> ...

  9. Map按键排序(sort by key)

    1.需求:已知有如下map,要求按照key倒序排列遍历. Map<String, Integer> map = new HashMap<>(); map.put("1 ...

  10. c# 中Linq Lambda 的ToLookup方法的使用

    同样直接上代码: List<Student> ss = new List<Student>(); Student ss1 = , Age = , Name = " } ...