调用微信和支付宝第三方接口方法总结

调用微信和支付宝第三方接口方法总结[CDATA[报文为空]]></return_msg>” + “</xml> “;

大家好,欢迎来到IT知识分享网。

最近项目上用到了调用微信和支付宝的第三方支付接口,因为以前没用过,所以这次用到了之后总结一下分享给大家,这里介绍两种支付方式,即app支付和扫码支付方式。

一、app支付(这里只介绍java端调用支付,安卓或ios端自己参考相关的调用文档)

首先可以看一看项目支付流程(图解)

1. 在页面上选择支付方式(微信或支付宝)

2. 由相应的客户端调用相应的支付方式进入相应的支付页面(安卓或ios调用支付接口并进入微信或支付宝支付页面,显示支付的信息)

3. 输入密码进行支付

4. 调用支付结果接口,来返回支付成功与否

调用微信和支付宝第三方接口方法总结

调用微信和支付宝第三方接口方法总结

调用微信和支付宝第三方接口方法总结

调用微信和支付宝第三方接口方法总结

四图分别是选择支付方式、微信支付页面、支付宝支付页面、微信支付结果(成功)页面

也是基本的支付三个步骤。

一、先看微信支付:

在调用微信支付之前你应该已经下单成功(即订单信息入库成功),这里需要几个值:

OrderName(订单名称),orderNumber(订单编号,唯一),amount(金额), prepayId(交易会话id)

前三个参数直接从数据库里获取。prepayid是什么?可以具体看微信支付文档,我们可以从下单接口中返回获得这个会话id并且需要入库,这个参数最重要的作用是用于第一次我们没有支付,但已经生成了一个待支付的订单。这种情况下我们不需要再次去调用下单接口返回prepayId,因为我们已经生成过了这个值

下面看手机端页面的js代码:

  1. //微信支付
  2. function wxPay(outTradeNo){
  3. var orderType=”0″; //路线 订单
  4. $.ajax({
  5. url :'<%=basePath%>client/travel/getWXClientPayInfo.do?outTradeNo=’+outTradeNo+’&orderType=’+orderType,
  6. cache : false,
  7. type : “get”,
  8. success : function(data)
  9. {
  10. if(data!=null){
  11. data = jQuery.parseJSON(data);
  12. var u = navigator.userAgent;
  13. var isAndroid = u.indexOf(‘Android’) > -1 || u.indexOf(‘Adr’) > -1; //android终端
  14. var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
  15. if(isAndroid){
  16. ClientInterface.pay(outTradeNo,data.prepayid,data.noncestr,data.timestamp,data.sign,orderType);
  17. }else if(isiOS){
  18. window.location.href=’http://localhost/pay/’+outTradeNo+’;’+data.prepayid+”;”+data.noncestr+”;”+data.timestamp+”;”+data.sign+”;”+orderType;
  19. }
  20. }
  21. }
  22. });
  23. }

这里outTradeNo即是唯一的订单编号,orderType是自己定义的订单类型,这里的ajax就是根据这两个参数去后台去操作下单,然后返回必要的参数给安卓或ios调用

然后看后台的这个方法:

  1. /**获取微信客户端支付信息 如 签名 随机数等
  2. * @param page
  3. * @throws Exception
  4. */
  5. @RequestMapping(value=”/getWXClientPayInfo”)
  6. @ResponseBody
  7. public String getWeixinPayInfo(HttpServletRequest request) throws Exception{
  8. String orderNumber = request.getParameter(“outTradeNo”);
  9. String orderType = request.getParameter(“orderType”);
  10. Map<String, Object> map=new HashMap<String, Object>();
  11. map.put(“orderNumber”, orderNumber);
  12. map.put(“type”, orderType);
  13. //获取订单信息
  14. Map<String, Object> orderMap=travelOrderService.getOrderInfoByOrderType(map);
  15. String amount=””;
  16. String prepayId=””;
  17. if(null!=orderMap&&orderMap.size()>0){
  18. if(orderMap.containsKey(“amount”)){
  19. amount=orderMap.get(“amount”).toString();
  20. }
  21. if(orderMap.containsKey(“prepayId”)){
  22. prepayId=orderMap.get(“prepayId”).toString();
  23. }
  24. }
  25. //获取微信支付会话id
  26. if(“”.equals(prepayId)){
  27. Float totalMoney=Float.valueOf(amount);
  28. totalMoney=totalMoney*100;
  29. int totalFee=totalMoney.intValue();
  30. String money=String.valueOf(totalFee);
  31. String xmlStr=WeixinPayUtil.add(orderNumber,money,orderType); //获得会话ID
  32. Map<String, Object> m=new HashMap<String, Object>();
  33. Document doc = DocumentHelper.parseText(xmlStr);
  34. Element rootElement = doc.getRootElement();
  35. XmlToBean.ele2map(m,rootElement);
  36. String str=””;
  37. if(m.containsKey(“prepay_id”)){
  38. str=m.get(“prepay_id”).toString();
  39. str=str.replace(“{prepay_id=”, “”);
  40. str=str.substring(0,str.length()-1);
  41. }
  42. prepayId=str;
  43. map.put(“prepayId”, prepayId);
  44. travelOrderService.updateOrderInfoByType(map);
  45. }
  46. //转成sortedMap,微信支付后台生成sign需要排序过的map
  47. SortedMap<String,Object> sort=new TreeMap<String,Object>();
  48. String partnerid = sysparam.getStringParamByKey(“c.wxpay.partnerid”);
  49. //相关参数,可以定义一个Map做成动态的
  50. sort.put(“appid”, sysparam.getStringParamByKey(“c.wxpay.appid”));
  51. sort.put(“partnerid”, partnerid);
  52. sort.put(“prepayid”,prepayId);
  53. sort.put(“package”, “Sign=WXPay”);
  54. String noncestr = RandomUtil.CreateRandom(32);
  55. sort.put(“noncestr”, noncestr);
  56. String timestamp = String.valueOf(System.currentTimeMillis());
  57. timestamp = timestamp.substring(0,timestamp.length()-3);
  58. sort.put(“timestamp”, timestamp);
  59. String securit = sysparam.getStringParamByKey(“c.wxpay.secret”);
  60. //生成sign
  61. String sign=WeixinSignUtil.createSign(“UTF-8”, sort,securit);
  62. Map<String,Object> resultParam = new HashMap<String, Object>();
  63. resultParam.put(“timestamp”, timestamp);
  64. resultParam.put(“noncestr”, noncestr);
  65. resultParam.put(“sign”, sign);
  66. resultParam.put(“prepayid”, prepayId);
  67. return JsonUtil.Object2JsonSting(resultParam);
  68. }

这里需要注意的是

StringxmlStr=WeixinPayUtil.add(orderNumber,money,orderType); //获得会话ID

这个add方法即微信的下单接口,返回的xmlStr是xml格式的字符串,进行解析后,得出来perpayid入库。这里的money即金额,必须以分为单位!

依次参考下单接口:

  1. public static String add(String orderNo,String TotalMoney,String orderType) throws Exception {
  2. URL postUrl = new URL(“https://api.mch.weixin..com/pay/unifiedorder”);
  3. SysParamServiceImpl systemParam = (SysParamServiceImpl)SpringContextHolder.getBean(SysParamServiceImpl.class);
  4. HttpsURLConnection con = (HttpsURLConnection) postUrl.openConnection();//打开连接
  5. con.setRequestMethod(“POST”);//post方式提交
  6. con.setDoOutput(true);//打开读写属性,默认均为false
  7. con.setDoInput(true);
  8. con.setUseCaches(false);//Post请求不能使用缓存
  9. con.setInstanceFollowRedirects(true);
  10. DataOutputStream out = new DataOutputStream(con.getOutputStream());
  11. Map<String, Object> vo = new HashMap<String, Object>();
  12. //相关参数,可以定义一个Map做成动态的
  13. vo.put(“appid”, systemParam.getStringParamByKey(“c.wxpay.appid”));
  14. vo.put(“attach”, “支付测试”);
  15. vo.put(“body”, “APP应用支付”);
  16. vo.put(“mch_id”, systemParam.getStringParamByKey(“c.wxpay.partnerid”));
  17. vo.put(“nonce_str”, RandomUtil.CreateRandom(32));
  18. String notifyUrl=systemParam.getStringParamByKey(“sys.domain”);
  19. notifyUrl=notifyUrl+”/interface/wxpay/”+orderType; //调用微信下发通知的接口
  20. vo.put(“notify_url”, notifyUrl);
  21. vo.put(“out_trade_no”, orderNo);
  22. vo.put(“spbill_create_ip”, “14.23.150.211”);
  23. vo.put(“total_fee”, TotalMoney);
  24. vo.put(“trade_type”, “APP”);
  25. //转成sortedMap,微信支付后台生成sign需要排序过的map
  26. SortedMap<String,Object> sort=new TreeMap<String,Object>(vo);
  27. String secrit = systemParam.getStringParamByKey(“c.wxpay.secret”);
  28. //生成sign
  29. String sign=WeixinSignUtil.createSign(“UTF-8”, sort,secrit);
  30. //把sign放入map中
  31. vo.put(“sign”, sign);
  32. org.dom4j.Document doc = DocumentHelper.createDocument();
  33. Element body = DocumentHelper.createElement(“xml”);
  34. XmlUtil.buildMap2xmlBody(body,vo);
  35. doc.add(body);
  36. //发送请求
  37. out.writeUTF(doc.asXML());
  38. System.out.println(doc.asXML());
  39. out.flush();
  40. out.close();
  41. //接收数据
  42. BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(), “UTF-8”));
  43. String line;
  44. StringBuffer responseText = new StringBuffer();
  45. while ((line = reader.readLine()) != null) {
  46. responseText.append(line).append(“\r\n”);
  47. }
  48. reader.close();
  49. con.disconnect();
  50. return responseText.toString()+””;
  51. }

这里需要几个微信支付所需要的开发者账号信息,包括appid,微信支付商户号:partnerid,微信支付密码:secret这些是商户申请微信app支付的信息提供给我们开发者,还有nonce_str参数需要配置我们自己定义的一个请求

该请求会在支付完成后,微信会主动根据这个请求来返回结果给我们。而且必须是外网,内网调不通

最后一步就是支付之后,微信会调用我们配置的nonce_str这个请求返回xml格式的结果给我们

  1. @RequestMapping(value = “/interface/wxpay/{orderType}”, produces = “text/html;charset=UTF-8”)
  2. @ResponseBody
  3. public String getWeixinPayResult(HttpServletRequest request,
  4. HttpServletResponse response)
  5. throws IOException
  6. {
  7. try
  8. {
  9. String reqcontent = getRequestContent(request);
  10. interfaceLogger
  11. .info(“################### ################# WeiXinPayResultInterface::getWeixinPayResult,request msg:”
  12. + reqcontent);
  13. ResponseHandler resHandler = new ResponseHandler(request, response);
  14. // 创建请求对象
  15. // RequestHandler queryReq = new RequestHandler(request, response);
  16. String type = request.getParameter(“orderType”); // 获取订单类型
  17. // queryReq.init();
  18. String securit = sysParam.getStringParamByKey(“c.wxpay.secret”);
  19. //判断证书
  20. if (resHandler.getParameter(“sign”).equals(
  21. WeixinSignUtil.createSign(“utf-8”,
  22. resHandler.getAllParameters(), securit)))
  23. {
  24. // 商户订单号
  25. String out_trade_no = resHandler.getParameter(“out_trade_no”);
  26. String totalFee = resHandler.getParameter(“total_fee”);
  27. System.out.println(“out_trade_no:” + out_trade_no);
  28. Map<String, Object> map = new HashMap<String, Object>();
  29. String result_code = resHandler.getParameter(“result_code”);
  30. if (result_code.equals(“SUCCESS”))
  31. {
  32. // 金额,以分为单位

String total_fee = resHandler.getParameter(“total_fee”);

//进行支付后操作…

} else { return resHandler.getParameter(“err_code_des”); } // 给微信服务器返回success 否则30分钟通知8次 return “success”; } else { System.out.println(“通知签名验证失败”); resHandler.sendToCFT(“fail”); response.setCharacterEncoding(“utf-8”); return “FAIL”; } } catch (Exception e) { return “FAIL”; } }这是微信调用我们定义的请求来主动返回支付结果,但我们也可以写接口主动调用微信来获取订单信息这里需要ios或者安卓调用我们java后台写的接口来获取支付结果:

接口如下:

  1. /**
  2. * 客户端微信支付成功后查询后台支付结果接口
  3. *
  4. * @param req
  5. * @param rsp
  6. * @return String 返回json字符串 如果有违例,请使用@exception/throws [违例类型]
  7. * [违例说明:异常的注释必须说明该异常的含义及什么条件下抛出该
  8. * @throws Exception
  9. * @see [类、类#方法、类#成员]
  10. */
  11. @RequestMapping(value = “/interface/payStatus”, method = RequestMethod.POST, produces = “text/html;charset=UTF-8”)
  12. @ResponseBody
  13. public String getPayStatus(HttpServletRequest req, HttpServletResponse rsp)
  14. throws Exception
  15. {
  16. Map<String, Object> resultMap = new HashMap<String, Object>();
  17. try
  18. {
  19. URL postUrl = new URL(
  20. “https://api.mch.weixin..com/pay/orderquery”);
  21. // 获取请求内容
  22. String requestContent = getRequestContent(req);
  23. // 日志
  24. interfaceLogger.info(“request payStatus:” + requestContent);
  25. // 解析参数
  26. requestParam = parseAndCheckParam(requestContent, resultMap,
  27. requestParam, systemParam.getSystemKey());
  28. // 校验参数
  29. checkStatusParam(resultMap);
  30. // 校验token及获取用户信息
  31. Map<String, Object> userInfo = checkTokenAndGetUserInfo(
  32. tokenService, appuserManager, requestParam, resultMap);
  33. String user_id = (String)userInfo.get(“userId”);
  34. String totalFee = (String)requestParam.get(“totalFee”);
  35. String type = (String)requestParam.get(“orderType”); // 获取订单类型参数
  36. if (null == user_id)
  37. {
  38. resultMap.put(“resultCode”,
  39. ErrorCodeConstants.INVALID_TOKEN_ERROR);
  40. }
  41. SysParamServiceImpl sysParam = (SysParamServiceImpl)SpringContextHolder
  42. .getBean(SysParamServiceImpl.class);
  43. HttpsURLConnection con = (HttpsURLConnection)postUrl
  44. .openConnection();// 打开连接
  45. con.setRequestMethod(“POST”);// post方式提交
  46. con.setDoOutput(true);// 打开读写属性,默认均为false
  47. con.setDoInput(true);
  48. con.setUseCaches(false);// Post请求不能使用缓存
  49. con.setInstanceFollowRedirects(true);
  50. // DataOutputStream out = new
  51. // DataOutputStream(con.getOutputStream());
  52. PrintWriter out = new PrintWriter(con.getOutputStream());
  53. Map<String, Object> map = new HashMap<String, Object>();
  54. // 相关参数,可以定义一个Map做成动态的
  55. map.put(“appid”, sysParam.getStringParamByKey(“c.wxpay.appid”)); // appID
  56. map.put(“mch_id”, sysParam.getStringParamByKey(“c.wxpay.partnerid”)); // 商户号
  57. map.put(“nonce_str”, RandomUtil.CreateRandom(32)); // 随机数
  58. String orderId = requestParam.get(“outTradeNo”).toString();
  59. map.put(“out_trade_no”, orderId); // 订单号
  60. // String mo=”3000″;
  61. // insertMoneyAccounting(orderId,mo); //利润分配
  62. // 转成sortedMap,微信支付后台生成sign需要排序过的map
  63. SortedMap<String, Object> sort = new TreeMap<String, Object>(map);
  64. String secrit = sysParam.getStringParamByKey(“c.wxpay.secret”);
  65. // 生成sign
  66. String sign = WeixinSignUtil.createSign(“UTF-8”, sort, secrit);
  67. // 把sign放入map中
  68. map.put(“sign”, sign); // 签名
  69. Document doc = DocumentHelper.createDocument();
  70. Element body = DocumentHelper.createElement(“xml”);
  71. buildMap2xmlBody(body, map);
  72. doc.add(body);
  73. // 发送请求
  74. // out.writeUTF(doc.asXML());
  75. String outStr = doc.asXML();
  76. out.print(outStr);
  77. System.out.println(doc.asXML());
  78. out.flush();
  79. out.close();
  80. // 接收数据
  81. BufferedReader reader = new BufferedReader(new InputStreamReader(
  82. con.getInputStream(), “UTF-8”));
  83. String line;
  84. StringBuffer responseText = new StringBuffer();
  85. while ( (line = reader.readLine()) != null)
  86. {
  87. responseText.append(line).append(“\r\n”);
  88. }
  89. reader.close();
  90. con.disconnect();
  91. String resXml = responseText.toString() + “”; // 获取从微信付款的结果
  92. // ,以String类型的xml格式返回
  93. System.out.println(“result:” + resXml);
  94. // 解析xml
  95. Map<String, Object> m = new HashMap<String, Object>();
  96. Document d = DocumentHelper.parseText(resXml);
  97. Element rootElement = d.getRootElement();
  98. XmlToBean.ele2map(m, rootElement);
  99. String str = “”;
  100. if (m.containsKey(“trade_state”))
  101. {
  102. str = m.get(“trade_state”).toString();
  103. str = str.replace(“{trade_state=”, “”);
  104. str = str.substring(0, str.length() – 1);
  105. if (“SUCCESS” == str || “SUCCESS”.equals(str))
  106. {
  107. if (“0”.equals(type)) {
  108. //支付成功后操作…
  109. }
  110. }
  111. else if (“REFUND” == str || “REFUND”.equals(str))
  112. {
  113. str = “1”; // 转入退款
  114. }
  115. else if (“NOTPAY” == str || “NOTPAY”.equals(str))
  116. {
  117. str = “2”; // 未支付
  118. }
  119. else if (“CLOSED” == str || “CLOSED”.equals(str))
  120. {
  121. str = “3”; // 已关闭
  122. }
  123. else if (“REVOKED” == str || “REVOKED”.equals(str))
  124. {
  125. str = “4”; // 已撤销
  126. }
  127. else if (“USERPAYING” == str || “USERPAYING”.equals(str))
  128. {
  129. str = “5”; // 用户支付中
  130. }
  131. else if (“PAYERROR” == str || “PAYERROR”.equals(str))
  132. {
  133. str = “6”; // 支付失败
  134. }
  135. resultMap.put(“status”, str);
  136. resultMap.put(“resultCode”,
  137. ErrorCodeConstants.RESULT_CODE_SUCCESS);
  138. }
  139. }
  140. catch (Exception e)
  141. {
  142. logger.error(“loginOut:system exception!”, e);
  143. resultMap.clear();
  144. resultMap.put(“resultCode”, ErrorCodeConstants.SYSTEM_ERROR);
  145. }
  146. interfaceLogger.info(“response payStatus:” + resultMap.toString());
  147. return JsonUtil.Object2EncodeJsonSting(resultMap,
  148. systemParam.getSystemKey());
  149. }

requestParam.get(“XXX”),XXX是客户端调用我们接口给我们传的参数,需要给我们totalFee(金额),orderType(订单类型)等

然后我们返回支付结果给客户端

二、支付宝支付:

支付宝支付流程上和微信支付稍微有所差别,支付宝不需要调用下单结果,但是也需要一个类似于微信prepayId的字段来入库,作用上跟prepayId差不多,名称可以自己定义,我这边暂时为aliPayInfo:

首先看js代码:

  1. //支付宝支付
  2. function aliPay(outTradeNo){
  3. var orderType=”0″;
  4. var info = $(“#aliPayInfo”).val();//订单信息
  5. var totalAmount = $(“#moeny”).val();//总金额
  6. var orderName = $(“#orderName”).val();//订单名称
  7. //type 0:线路 1:景点 2:酒店 3:商城 4:VIP
  8. var prams = {
  9. aliPayInfo : info,
  10. type : orderType,
  11. orderNumber : outTradeNo,
  12. money : totalAmount,
  13. orderName : orderName
  14. };
  15. //先调支付宝确定是否下单 否则返回支付宝会话信息
  16. $.ajax({
  17. url : ‘<%=basePath%>client/hotel/foundZFBOrder.do’,
  18. type : “post”,
  19. data : prams,
  20. cache : false,
  21. dataType : “json”,
  22. success : function(data)
  23. {
  24. //alert(“info +====”+data.info);
  25. if(data.isSuccess){
  26. if(isAndroid){
  27. ClientInterface.aliPay(data.info,outTradeNo,orderType,totalAmount);
  28. }else if(isiOS){
  29. window.location.href=’http://localhost/aliPay/’+data.info+’;’+outTradeNo+”;”+orderType+”;”+totalAmount;
  30. }
  31. }else{
  32. var title = “支付宝下单失败”;
  33. prompt(title);
  34. }
  35. },
  36. error : function(data){
  37. var title = “支付宝下单失败”;
  38. prompt(title);
  39. }
  40. });
  41. }

页面上的aliPayInfo可以为空,因为第一次去调用支付宝时这个为空,如果不支付,但是还是入库了,需要去数据库里查一下,那么共用这个页面的话aliPayInfo就不为空然后去后台写这个ajax请求

[java] view plain copy

  1. <code class=”language-javascript”>@RequestMapping(value=”/foundZFBOrder”, produces = “application/json;charset=UTF-8”)
  2. @ResponseBody
  3. public Map<String, Object> foundZFBOrder(HttpServletRequest request){
  4. //支付宝信息
  5. String aliPayInfo = request.getParameter(“aliPayInfo”);
  6. //金额
  7. String money = request.getParameter(“money”);
  8. //订单名称
  9. String orderName = request.getParameter(“orderName”);
  10. //订单编号
  11. String orderNumber = request.getParameter(“orderNumber”);
  12. //订单类型(0:线路 1:景点 2:酒店 3:商城 4:VIP)
  13. String type = request.getParameter(“type”);
  14. boolean isSuccess = false;
  15. //判断是否生成过支付宝信息
  16. if(StringUtils.isBlank(aliPayInfo)){
  17. //生成支付宝信息
  18. aliPayInfo = AliPayUtil.orderInfo(money, orderName, orderNumber, type);
  19. //修改表中支付宝信息
  20. if(StringUtils.isNotBlank(aliPayInfo)){
  21. isSuccess = true;
  22. Map<String, Object> map = new HashMap<String, Object>();
  23. map.put(“aliPayInfo”, aliPayInfo);
  24. map.put(“type”, type);
  25. map.put(“orderNumber”, orderNumber);
  26. try {
  27. travelOrderService.updateOrderInfoByType(map);
  28. }
  29. catch (Exception e) {
  30. e.printStackTrace();
  31. }
  32. }
  33. /** 打印支付宝响应日志 */
  34. if (interfaceLogger.isInfoEnabled()) {
  35. interfaceLogger.info(“[HotelController][foundZFBOrder]ZFB ” + table + ” result :[”
  36. + JSON.toJSONString(aliPayInfo) + “]”);
  37. }
  38. }
  39. Map<String, Object> map = new HashMap<String, Object>();
  40. map.put(“info”, aliPayInfo);
  41. map.put(“isSuccess”, isSuccess);
  42. return map;
  43. }</code>

这里的 aliPayInfo = AliPayUtil.orderInfo(money, orderName, orderNumber, type);类似于微信的下单接口(aliPayInfo 需要入库),但不是下单接口,因为支付宝支付没有下单接口,详情可以查看支付宝支付文档

下面继续写orderInfo方法:

[java] view plain copy

  1. <code class=”language-java”>/**
  2. *
  3. * @param amount 订单金额
  4. * @param subject 订单标题
  5. * @param body 订单描述
  6. * @param outTradeNo订单号
  7. * @return
  8. */
  9. public static String orderInfo(String amount,String subject,String outTradeNo,String type) {
  10. //获取appid
  11. String appId=Const.APPID;
  12. Map<String, String> authInfoMap = OrderInfoUtil.buildOrderParamMap(appId,amount,subject,outTradeNo,type);
  13. String info = OrderInfoUtil.buildOrderParam(authInfoMap);
  14. String rsaPrivate =Const.RSAPRIVATE; //获取商户密钥
  15. String sign = OrderInfoUtil.getSign(authInfoMap, rsaPrivate);
  16. final String orderInfo = info + “&” + sign;
  17. return orderInfo;
  18. }</code>

这里和微信一样需要支付宝商户的appid和RSAPRIVATE提供给我们开发者,

然后编写支付宝支付工具类:

  1. public class OrderInfoUtil {
  2. /**
  3. * 构造授权参数列表
  4. *
  5. * @param pid
  6. * @param app_id
  7. * @param target_id
  8. * @return
  9. */
  10. public static Map<String, String> buildAuthInfoMap(String pid, String app_id, String target_id) {
  11. Map<String, String> keyValues = new HashMap<String, String>();
  12. // 商户签约拿到的app_id,如:24223
  13. keyValues.put(“app_id”, app_id);
  14. // 商户签约拿到的pid,如:16631
  15. keyValues.put(“pid”, pid);
  16. // 服务接口名称, 固定值
  17. keyValues.put(“apiname”, “com.alipay.account.auth”);
  18. // 商户类型标识, 固定值
  19. keyValues.put(“app_name”, “mc”);
  20. // 业务类型, 固定值
  21. keyValues.put(“biz_type”, “openservice”);
  22. // 产品码, 固定值
  23. keyValues.put(“product_id”, “APP_FAST_LOGIN”);
  24. // 授权范围, 固定值
  25. keyValues.put(“scope”, “kuaijie”);
  26. // 商户唯一标识,如:kkkkk091125
  27. keyValues.put(“target_id”, target_id);
  28. // 授权类型, 固定值
  29. keyValues.put(“auth_type”, “AUTHACCOUNT”);
  30. // 签名类型
  31. keyValues.put(“sign_type”, “RSA”);
  32. return keyValues;
  33. }
  34. /**
  35. * 构造支付订单参数列表
  36. * @param pid
  37. * @param app_id
  38. * @param target_id
  39. * @return
  40. */
  41. public static Map<String, String> buildOrderParamMap(String appId,String amount,String subject,String outTradeNo,String type) {
  42. Map<String, String> keyValues = new HashMap<String, String>();
  43. keyValues.put(“app_id”, appId);
  44. keyValues.put(“biz_content”, “{\”timeout_express\”:\”30m\”,\”product_code\”:\”QUICK_MSECURITY_PAY\”,\”total_amount\”:\””+amount+”\”,\”subject\”:\””+subject+”\”,\”out_trade_no\”:\”” +outTradeNo + “\”}”);
  45. keyValues.put(“charset”, “utf-8”);
  46. keyValues.put(“method”, “alipay.trade.app.pay”);
  47. keyValues.put(“sign_type”, “RSA”);
  48. //获取域名
  49. SysParamServiceImpl systemParam = (SysParamServiceImpl)SpringContextHolder.getBean(SysParamServiceImpl.class);
  50. //String notifyUrl=”http://180.96.11.10:8080/tourism”;
  51. String notifyUrl=systemParam.getStringParamByKey(“sys.domain”);
  52. notifyUrl=notifyUrl+”/interface/alipay/”+type;
  53. keyValues.put(“notify_url”, notifyUrl);
  54. String timestamp = “”;
  55. Date date=new Date();
  56. SimpleDateFormat sdf=new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”); //设置时间格式
  57. timestamp=sdf.format(date);
  58. keyValues.put(“timestamp”, timestamp);
  59. keyValues.put(“version”, “1.0”);
  60. return keyValues;
  61. }
  62. /**
  63. * 构造支付订单参数信息
  64. *
  65. * @param map
  66. * 支付订单参数
  67. * @return
  68. */
  69. public static String buildOrderParam(Map<String, String> map) {
  70. List<String> keys = new ArrayList<String>(map.keySet());
  71. StringBuilder sb = new StringBuilder();
  72. for (int i = 0; i < keys.size() – 1; i++) {
  73. String key = keys.get(i);
  74. String value = map.get(key);
  75. sb.append(buildKeyValue(key, value, true));
  76. sb.append(“&”);
  77. }
  78. String tailKey = keys.get(keys.size() – 1);
  79. String tailValue = map.get(tailKey);
  80. sb.append(buildKeyValue(tailKey, tailValue, true));
  81. return sb.toString();
  82. }
  83. /**
  84. * 拼接键值对
  85. *
  86. * @param key
  87. * @param value
  88. * @param isEncode
  89. * @return
  90. */
  91. private static String buildKeyValue(String key, String value, boolean isEncode) {
  92. StringBuilder sb = new StringBuilder();
  93. sb.append(key);
  94. sb.append(“=”);
  95. if (isEncode) {
  96. try {
  97. sb.append(URLEncoder.encode(value, “UTF-8”));
  98. } catch (UnsupportedEncodingException e) {
  99. sb.append(value);
  100. }
  101. } else {
  102. sb.append(value);
  103. }
  104. return sb.toString();
  105. }
  106. /**
  107. * 对支付参数信息进行签名
  108. *
  109. * @param map
  110. * 待签名授权信息
  111. *
  112. * @return
  113. */
  114. public static String getSign(Map<String, String> map, String rsaKey) {
  115. List<String> keys = new ArrayList<String>(map.keySet());
  116. // key排序
  117. Collections.sort(keys);
  118. StringBuilder authInfo = new StringBuilder();
  119. for (int i = 0; i < keys.size() – 1; i++) {
  120. String key = keys.get(i);
  121. String value = map.get(key).toString();
  122. authInfo.append(buildKeyValue(key, value, false));
  123. authInfo.append(“&”);
  124. }
  125. String tailKey = keys.get(keys.size() – 1);
  126. String tailValue =map.get(tailKey).toString();
  127. authInfo.append(buildKeyValue(tailKey, tailValue, false));
  128. String oriSign = SignUtils.sign(authInfo.toString(), rsaKey);
  129. String encodedSign = “”;
  130. try {
  131. encodedSign = URLEncoder.encode(oriSign, “UTF-8”);
  132. } catch (UnsupportedEncodingException e) {
  133. e.printStackTrace();
  134. }
  135. return “sign=” + encodedSign;
  136. }
  137. /**
  138. * 要求外部订单号必须唯一。
  139. * @return
  140. */
  141. private static String getOutTradeNo() {
  142. SimpleDateFormat format = new SimpleDateFormat(“MMddHHmmss”, Locale.getDefault());
  143. Date date = new Date();
  144. String key = format.format(date);
  145. Random r = new Random();
  146. key = key + r.nextInt();
  147. key = key.substring(0, 15);
  148. return key;
  149. }
  150. }

keyValues.put(“notify_url”, notifyUrl);这个和微信一样,需要设置一个供支付宝支付后返回给我们的支付结果通知的请求,需自己定义,可带参数,必须在外网下才能调用

最后根据我们定义的请求,来写接收支付宝返回给我们的结果:

  1. @RequestMapping(value = “/interface/alipay/{type}”, produces = “text/html;charset=UTF-8”)
  2. @ResponseBody
  3. public String getzfbPayResult(HttpServletRequest request,HttpServletResponse response){
  4. try{
  5. String reqcontent = getRequestContent(request);
  6. interfaceLogger.info(“################### ################# WeiXinPayResultInterface::alipay,request msg:”+reqcontent);
  7. //解析url
  8. //reqcontent=stringFarmat(reqcontent);
  9. try {
  10. reqcontent= URLDecoder.decode(reqcontent, “UTF-8”);
  11. } catch (UnsupportedEncodingException e) {
  12. e.printStackTrace();
  13. }
  14. interfaceLogger.info(“###########获取参数解析url:$@@@@@@@@@@@@@@@@@@@@@@@@@=========”+reqcontent);
  15. //转换为map
  16. Map<String, String> paramMap=stringtoArray(reqcontent);
  17. //获取orderType
  18. String orderType=request.getRequestURI();
  19. int i=orderType.lastIndexOf(“/”);
  20. orderType=orderType.substring(i+1, orderType.length());
  21. //验证签名
  22. //支付宝公钥
  23. String publicKey=Const.PUBLICKEY; //支付宝公钥
  24. //字符集
  25. String charsetType=”UTF-8″;
  26. //验证签名
  27. boolean signVerified = AlipaySignature.rsaCheckV1(paramMap, publicKey, charsetType); //调用SDK验证签名
  28. interfaceLogger.info(“###########验证签名结果:$@@@@@@@@@@@@@@@@@@@@@@@@@=========”+signVerified);
  29. if(signVerified){
  30. //验证金额订单号
  31. interfaceLogger.info(“*****************验证签名成功:&&&&&&&&&&&&&&&&&&&&&&&&&&&&”);
  32. if(paramMap.containsKey(“trade_status”)){
  33. String resultStr=paramMap.get(“trade_status”);
  34. if(resultStr.equals(“TRADE_SUCCESS”)||resultStr.equals(“TRADE_FINISHED”)){
  35. //支付成功后操作…
  36. }
  37. return “success”;
  38. }else{
  39. interfaceLogger.info(“&&&&&&&&&&&&&&&&验证签名失败:***************************”);
  40. return “failure”;
  41. }
  42. }catch (Exception e){
  43. interfaceLogger.info(“###########待签名字符串str:$@@@@@@@@@@@@@@@@@@@@@@@@@=========”,e);
  44. e.printStackTrace();
  45. return “failure”;
  46. }
  47. }

这一步需要商户提供给我们的PUBLICKEY支付宝公钥来进行证书验证。

————————————————————————————————————————————-

这里介绍了app上面的两种支付方式。下面介绍下微信和支付宝的二维码支付先看java后台代码:

  1. /**
  2. *去支付界面(支付订单)
  3. * @param request
  4. * @return
  5. * @throws Exception
  6. */
  7. @RequestMapping(value=”/payOrder”)
  8. public ModelAndView payOrder(HttpServletRequest request) throws Exception{
  9. ModelAndView mv = this.getModelAndView();
  10. PageData pd = new PageData();
  11. String type=request.getParameter(“type”);
  12. String orderId=request.getParameter(“orderId”);
  13. pd = this.getPageData();
  14. User user=SessionUtil.getUser(request);
  15. /* User user=new User();
  16. user.setUserId(“wang”);*/
  17. String userId=””;
  18. if(null!=user){
  19. userId=user.getUserId();
  20. }
  21. pd.put(“userId”, userId);
  22. pd=travelOrderService.getAllOrderDetail(pd);
  23. String orderNumber=””;
  24. String amount=”0.01″;//测试金额
  25. String orderName=””;
  26. if(pd.containsKey(“orderName”)){
  27. if(!StringUtils.isBlank(pd.get(“orderName”)))
  28. orderName=pd.get(“orderName”).toString();
  29. }
  30. if(pd.containsKey(“orderNumber”)){
  31. if(!StringUtils.isBlank(pd.get(“orderNumber”)))
  32. orderNumber=pd.get(“orderNumber”).toString();
  33. }
  34. //元转成分
  35. String flag = sysparam.getStringParamByKey(“system.flag”);
  36. if(flag==”1″||flag.equals(“1”)){
  37. //type为0,3,4时取amount,type为1,2时取js_amount
  38. if(type.equals(“0”)||type.equals(“3”)||type.equals(“4”)){
  39. if(pd.containsKey(“amount”)){
  40. if(!StringUtils.isBlank(pd.get(“amount”)))
  41. amount=pd.get(“amount”).toString();
  42. }
  43. }else if(type.equals(“1”)||type.equals(“2”)){
  44. if(pd.containsKey(“js_amount”)){
  45. if(!StringUtils.isBlank(pd.get(“js_amount”)))
  46. amount=pd.get(“js_amount”).toString();
  47. }
  48. }
  49. }
  50. if (logger.isInfoEnabled())
  51. {
  52. logger.info(“PayController:payOrder:amount:[” + amount + “]==>”);
  53. }
  54. //以分为单位
  55. amount=floatToString(amount);
  56. //获取生成微信二维码的url和prepayId
  57. Map<String, Object> map=weChatPay(orderNumber,amount,type);
  58. String imageUrl=””;
  59. f(map.containsKey(“urlCode”)){
  60. if(!StringUtils.isBlank(map.get(“urlCode”))){
  61. imageUrl=map.get(“urlCode”).toString();
  62. }
  63. }
  64. //获取生成支付宝二维码的url(金额要改成元!)
  65. amount=stringToFloat(amount);
  66. String aliPayCodeUrl=AliPayUtil.aliPay(orderNumber, orderName, amount, type);
  67. map.put(“type”, type);
  68. map.put(“orderNumber”, orderNumber);
  69. map.put(“aliPayCodeUrl”, aliPayCodeUrl);
  70. //将二维码入库
  71. travelOrderService.updateOrderInfoByType(map);
  72. //订单编号
  73. pd.put(“type”, type);
  74. pd.put(“orderId”, orderId);
  75. mv.addObject(“pd”, pd);
  76. mv.addObject(“productId”, orderNumber);
  77. mv.addObject(“imageUrl”, imageUrl);
  78. mv.addObject(“aliPayCodeUrl”, aliPayCodeUrl);
  79. mv.setViewName(“/pay/pay-4”);
  80. return mv;
  81. }

这里我把微信和支付宝支付前生成的二维码写在同一个方法里,imageURL是微信二维码url,aliPayCodeUrl是支付宝的二维码,和app支付不同的是,扫码支付需要事先生成二维码,并且二维码需要入库,并带到页面去用于显示(下面会讲)

微信下单并生成urlCode

  1. /**
  2. * 微信下单并返回生成二维码的url
  3. * 〈一句话功能简述〉
  4. * 〈功能详细描述〉
  5. * @param orderNo
  6. * @param TotalMoney
  7. * @param orderType
  8. * @return
  9. * @throws Exception String
  10. * 如果有违例,请使用@exception/throws [违例类型] [违例说明:异常的注释必须说明该异常的含义及什么条件下抛出该
  11. * @see [类、类#方法、类#成员]
  12. */
  13. @SuppressWarnings(“rawtypes”)
  14. public Map<String, Object> weChatPay(String orderNo,String TotalMoney,String orderType) throws Exception{
  15. URL postUrl = new URL(“https://api.mch.weixin..com/pay/unifiedorder”);
  16. HttpsURLConnection con = (HttpsURLConnection) postUrl.openConnection();//打开连接
  17. con.setRequestMethod(“POST”);//post方式提交
  18. con.setDoOutput(true);//打开读写属性,默认均为false
  19. con.setDoInput(true);
  20. con.setUseCaches(false);//Post请求不能使用缓存
  21. con.setInstanceFollowRedirects(true);
  22. DataOutputStream out = new DataOutputStream(con.getOutputStream());
  23. Map<String, Object> vo = new HashMap<String, Object>();
  24. //相关参数,可以定义一个Map做成动态的
  25. String appid = sysparam.getStringParamByKey(“c.wxpay.appid”);
  26. vo.put(“appid”, appid);
  27. vo.put(“attach”, “支付测试”);
  28. vo.put(“body”, “PC端支付测试”);
  29. String mchid = sysparam.getStringParamByKey(“c.wxpay.partnerid”);
  30. vo.put(“mch_id”,mchid);
  31. vo.put(“nonce_str”, RandomUtil.CreateRandom(32));
  32. /String notifyUrl=sysparam.getStringParamByKey(“sys.pc.domain”);
  33. if (logger.isInfoEnabled())
  34. {
  35. logger.info(“微信支付回调地址设置:notifyUrl:[” + notifyUrl + “]==>”);
  36. }
  37. notifyUrl=notifyUrl+”/travelWeb/pay/getWeChatPayResult/”+orderType; //调用微信下发通知的接口
  38. vo.put(“notify_url”, notifyUrl);
  39. vo.put(“out_trade_no”, orderNo);
  40. vo.put(“spbill_create_ip”, “14.23.150.211”);
  41. vo.put(“total_fee”, TotalMoney);
  42. vo.put(“trade_type”, “NATIVE”);
  43. //转成sortedMap,微信支付后台生成sign需要排序过的map
  44. SortedMap<String,Object> sort=new TreeMap<String,Object>(vo);
  45. //String secrit = “YNKSK648KG70j1085YYolajdfYUI7865”;
  46. String secrit =sysparam.getStringParamByKey(“c.wxpay.secret”);
  47. //生成sign
  48. String sign=WeixinSignUtil.createSign(“UTF-8”, sort,secrit);
  49. //把sign放入map中
  50. vo.put(“sign”, sign);
  51. org.dom4j.Document doc = DocumentHelper.createDocument();
  52. Element body = DocumentHelper.createElement(“xml”);
  53. XmlUtil.buildMap2xmlBody(body,vo);
  54. doc.add(body);
  55. //发送请求
  56. out.writeUTF(doc.asXML());
  57. System.out.println(doc.asXML());
  58. out.flush();
  59. out.close();
  60. //接收数据
  61. BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(), “UTF-8”));
  62. String line;
  63. StringBuffer responseText = new StringBuffer();
  64. while ((line = reader.readLine()) != null) {
  65. responseText.append(line).append(“\r\n”);
  66. }
  67. reader.close();
  68. con.disconnect();
  69. String requestXML = responseText.toString()+””;
  70. if (logger.isInfoEnabled())
  71. {
  72. logger.info(“weChatPay:输出参数列表:[” + requestXML + “]==>”);
  73. }
  74. //xml转换为map
  75. Map map = XMLUtil.doXMLParse(requestXML);
  76. String urlCode = (String) map.get(“code_url”);
  77. String prepayId = (String) map.get(“prepay_id”);
  78. //返回生成二维码的url和预支付交易会话id
  79. Map<String, Object> resultMap=new HashMap<String, Object>();
  80. resultMap.put(“urlCode”, urlCode);
  81. resultMap.put(“prepayId”, prepayId);
  82. return resultMap;
  83. }

支付宝生成urlCode

  1. /**
  2. *
  3. * 〈一句话功能简述〉
  4. * 〈功能详细描述〉
  5. * @param orderNo
  6. * 订单号
  7. * @param orderTitle
  8. * 订单标题
  9. * @param orderPrice
  10. * 订单总额
  11. * 如果有违例,请使用@exception/throws [违例类型] [违例说明:异常的注释必须说明该异常的含义及什么条件下抛出该
  12. * @see [类、类#方法、类#成员]
  13. */
  14. public static String aliPay(String orderNo, String orderTitle,
  15. String orderPrice,String type)
  16. {
  17. String aliPayCodeUrl=””;
  18. // 支付超时,定义为120分钟
  19. String timeoutExpress = “120m”;
  20. // 创建扫码支付请求builder,设置请求参数
  21. String notifyUrl=sysParamService.getStringParamByKey(“sys.pc.domain”);
  22. notifyUrl=notifyUrl+”/travelWeb/pay/getAliPayResult/”+type; //调用支付宝下发通知的接口
  23. AlipayTradePrecreateRequestBuilder builder = new AlipayTradePrecreateRequestBuilder()
  24. .setSubject(orderTitle)
  25. .setTotalAmount(orderPrice)
  26. .setOutTradeNo(orderNo)
  27. .setStoreId(storeId)
  28. .setTimeoutExpress(timeoutExpress)
  29. .setNotifyUrl(notifyUrl);//支付宝服务器主动通知商户服务器里指定的页面http路径,根据需要设置
  30. AlipayF2FPrecreateResult result = tradeService.tradePrecreate(builder);
  31. switch (result.getTradeStatus())
  32. {
  33. case SUCCESS:
  34. logger.info(“支付宝预下单成功: )”);
  35. AlipayTradePrecreateResponse response = result.getResponse();
  36. System.out.println(“response.getQrCode()=====”
  37. + response.getQrCode());
  38. aliPayCodeUrl=response.getQrCode();
  39. break;
  40. case FAILED:
  41. logger.error(“支付宝预下单失败!!!”);
  42. break;
  43. case UNKNOWN:
  44. logger.error(“系统异常,预下单状态未知!!!”);
  45. break;
  46. default:
  47. logger.error(“不支持的交易状态,交易返回异常!!!”);
  48. break;
  49. }
  50. return aliPayCodeUrl;
  51. }

这个方法和app一样,只是多返回了一个urlcode(urlcode生成二维码,这两个方法必须都要配置回调地址

  1. 下一步需要编写生成两种二维码的方法:
  2. /**
  3. * 生成支付宝二维码
  4. * 〈一句话功能简述〉
  5. * 〈功能详细描述〉
  6. * @param response
  7. * @param req void
  8. * 如果有违例,请使用@exception/throws [违例类型] [违例说明:异常的注释必须说明该异常的含义及什么条件下抛出该
  9. * @see [类、类#方法、类#成员]
  10. */
  11. @RequestMapping(value = “/createAliPayCode.do”, method = RequestMethod.GET)
  12. public void createAliPayCode(HttpServletResponse response,HttpServletRequest req)
  13. {
  14. String imageUrl=req.getParameter(“aliPayCodeUrl”);
  15. //传入二维码连接,图片高度和宽带
  16. BufferedImage image=ImageUtil.createImage(imageUrl,1000,1000);
  17. try
  18. {
  19. ImageIO.write(image, “gif”, response.getOutputStream());
  20. }
  21. catch (IOException e)
  22. {
  23. e.printStackTrace();
  24. }
  25. }
  26. /**
  27. * 微信支付二维码
  28. * 〈一句话功能简述〉
  29. * 〈功能详细描述〉
  30. * @param response
  31. * @param req void
  32. * 如果有违例,请使用@exception/throws [违例类型] [违例说明:异常的注释必须说明该异常的含义及什么条件下抛出该
  33. * @throws IOException
  34. * @throws JDOMException
  35. * @see [类、类#方法、类#成员]
  36. */
  37. @RequestMapping(value = “/createWXPayCode.do”, method = RequestMethod.GET)
  38. public void createWXPayCode(HttpServletResponse response,HttpServletRequest req) throws IOException, JDOMException
  39. {
  40. String imageUrl=req.getParameter(“imageUrl”);
  41. //传入二维码连接,图片高度和宽带
  42. BufferedImage image=ImageUtil.createImage(imageUrl,1000,1000);
  43. try
  44. {
  45. ImageIO.write(image, “gif”, response.getOutputStream());
  46. }
  47. catch (IOException e)
  48. {
  49. e.printStackTrace();
  50. }
  51. }

这里生成二维码的方法是用谷歌zhongxin(需要导入jar包)

  1. /**
  2. * 生成二维码图片方法
  3. * 〈一句话功能简述〉
  4. * 〈功能详细描述〉
  5. * @param text
  6. * @return BufferedImage
  7. * 如果有违例,请使用@exception/throws [违例类型] [违例说明:异常的注释必须说明该异常的含义及什么条件下抛出该
  8. * @see [类、类#方法、类#成员]
  9. */
  10. @SuppressWarnings({“rawtypes”, “unchecked”})
  11. public static BufferedImage createImage(String text,int width2,int height2)
  12. {
  13. //二维码的图片格式
  14. // String format = “gif”;
  15. Hashtable hints = new Hashtable();
  16. //内容所使用编码
  17. hints.put(EncodeHintType.CHARACTER_SET, “utf-8”);
  18. BufferedImage image = null;
  19. try
  20. {
  21. BitMatrix bitMatrix = new MultiFormatWriter().encode(text,
  22. BarcodeFormat.QR_CODE, width2, height2, hints);
  23. int width = bitMatrix.getWidth();
  24. int height = bitMatrix.getHeight();
  25. image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
  26. for (int x = 0; x < width; x++ )
  27. {
  28. for (int y = 0; y < height; y++ )
  29. {
  30. image.setRGB(x, y,
  31. bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF); //二维码图片为黑白两色
  32. }
  33. }
  34. }
  35. catch (WriterException e)
  36. {
  37. e.printStackTrace();
  38. }
  39. return image;
  40. }
  1. 这里吧之前传来的两个值在面里调用即可(img标签配置src)
  2. <div class=”boder-line”>
  3. <img src=”<%=basePath%>/XX/pay/createWXPayCode.do?imageUrl=${imageUrl}”/>
  4. </div>
  5. <div class=”boder-line”>
  6. <img src=”<%=basePath%>/XX/pay/createAliPayCode.do?aliPayCodeUrl=${aliPayCodeUrl}”/>
  7. </div>

这样打开扫码支付页面就会有生成好的支付宝和微信支付二维码图片然后发起支付,最后根据配置的回调地址返回支付结果

微信如下:

  1. /**
  2. * 微信支付结果回调地址
  3. * 〈一句话功能简述〉
  4. * 〈功能详细描述〉
  5. * @param request
  6. * @param response
  7. * @throws Exception
  8. * @see [类、类#方法、类#成员]
  9. */
  10. @SuppressWarnings({“unchecked”, “rawtypes”})
  11. @RequestMapping(value = “/getWeChatPayResult/{orderType}”, produces = “text/html;charset=UTF-8”)
  12. @ResponseBody
  13. public void getWeixinPayResult(HttpServletRequest request,
  14. HttpServletResponse response)
  15. throws Exception
  16. {
  17. //读取参数
  18. InputStream inputStream ;
  19. StringBuffer sb = new StringBuffer();
  20. inputStream = request.getInputStream();
  21. String s ;
  22. BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, “UTF-8”));
  23. while ((s = in.readLine()) != null){
  24. sb.append(s);
  25. }
  26. in.close();
  27. inputStream.close();
  28. //解析xml成map
  29. Map<String, String> m = new HashMap<String, String>();
  30. m = XMLUtil.doXMLParse(sb.toString());
  31. //获取orderType
  32. String orderType=request.getRequestURI();
  33. int i=orderType.lastIndexOf(“/”);
  34. orderType=orderType.substring(i+1, orderType.length());
  35. logger.info(“[PayController][getWeChatPayResult]:orderType:”+orderType);
  36. //过滤空 设置 TreeMap
  37. SortedMap<Object,Object> packageParams = new TreeMap<Object,Object>();
  38. Iterator it = m.keySet().iterator();
  39. while (it.hasNext()) {
  40. String parameter = (String) it.next();
  41. String parameterValue = m.get(parameter);
  42. String v = “”;
  43. if(null != parameterValue) {
  44. v = parameterValue.trim();
  45. }
  46. packageParams.put(parameter, v);
  47. }
  48. String key =sysparam.getStringParamByKey(“c.wxpay.secret”);
  49. logger.info(“[PayController][getWeChatPayResult]:packageParams:”+packageParams.toString());
  50. //判断签名是否正确
  51. if(PayCommonUtil.isTenpaySign(“UTF-8”, packageParams,key)) {
  52. String resXml = “”;
  53. if(“SUCCESS”.equals((String)packageParams.get(“result_code”))){
  54. // 这里是支付成功
  55. //////////执行自己的业务逻辑////////////////
  56. String mch_id = (String)packageParams.get(“mch_id”);
  57. String openid = (String)packageParams.get(“openid”);
  58. String is_subscribe = (String)packageParams.get(“is_subscribe”);
  59. String out_trade_no = (String)packageParams.get(“out_trade_no”);
  60. String total_fee = (String)packageParams.get(“total_fee”);
  61. logger.info(“[PayController][getWeChatPayResult]:mch_id:”+mch_id+”,openid:”+openid+”,is_subscribe:”+is_subscribe+”,out_trade_no:”+out_trade_no+”,total_fee:”+total_fee);
  62. //////////执行自己的业务逻辑////////////////
  63. //支付成功后操作….
  64. //通知微信.异步确认成功.必写.不然会一直通知后台.八次之后就认为交易失败了.
  65. resXml = “<xml>” + “<return_code><![CDATA[SUCCESS]]></return_code>”
  66. + “<return_msg><![CDATA[OK]]></return_msg>” + “</xml> “;
  67. } else {
  68. logger.info(“支付失败,错误信息:” + packageParams.get(“err_code”));
  69. resXml = “<xml>” + “<return_code><![CDATA[FAIL]]></return_code>”
  70. + “<return_msg><![CDATA[报文为空]]></return_msg>” + “</xml> “;
  71. }
  72. //——————————
  73. //处理业务完毕
  74. //——————————
  75. BufferedOutputStream out = new BufferedOutputStream(
  76. response.getOutputStream());
  77. out.write(resXml.getBytes());
  78. out.flush();
  79. out.close();
  80. } else{
  81. logger.info(“[WeiXinPayResultInterface][getWeChatPayResult]:通知签名验证失败”);
  82. }
  83. }

支付宝如下:

  1. /**
  2. * 支付宝支付回调接口
  3. * 〈一句话功能简述〉
  4. * 〈功能详细描述〉
  5. * @param request
  6. * @param response
  7. * @return String
  8. * 如果有违例,请使用@exception/throws [违例类型] [违例说明:异常的注释必须说明该异常的含义及什么条件下抛出该
  9. * @throws Exception
  10. * @see [类、类#方法、类#成员]
  11. */
  12. @RequestMapping(value = “/getAliPayResult/{type}”, method = RequestMethod.POST)
  13. public void getAliPayResult(HttpServletRequest request, HttpServletResponse response) throws Exception {
  14. logger.info(“[PayController][getAliPayResult]: 收到支付宝异步通知!”);
  15. Map<String, String> params = new HashMap<String, String>();
  16. //取出所有参数是为了验证签名
  17. @SuppressWarnings(“unchecked”)
  18. Enumeration<String> parameterNames = request.getParameterNames();
  19. while (parameterNames.hasMoreElements()) {
  20. String parameterName = parameterNames.nextElement();
  21. params.put(parameterName, request.getParameter(parameterName));
  22. }
  23. //获取orderType
  24. String orderType=request.getRequestURI();
  25. int i=orderType.lastIndexOf(“/”);
  26. orderType=orderType.substring(i+1, orderType.length());
  27. logger.info(“[PayController][getAliPayResult]:orderType:”+orderType);
  28. logger.info(“[PayController][getAliPayResult]:支付宝返回参数 params:”+params.toString());
  29. logger.info(“[PayController][getAliPayResult]:配置文件中取出公钥:”+Const.ALIPAYPUBLICKEY);
  30. boolean signVerified = false;
  31. try {
  32. signVerified = AlipaySignature.rsaCheckV1(params, Const.ALIPAYPUBLICKEY, “UTF-8”);
  33. logger.info(“[PayController][getAliPayResult]signVerified:”+signVerified);
  34. } catch (AlipayApiException e) {
  35. logger.info(“[PayController][getAliPayResult]:验证签名失败!”);
  36. e.printStackTrace();
  37. }
  38. if (signVerified) {
  39. String outtradeno = params.get(“out_trade_no”);
  40. logger.info(“[PayController][getAliPayResult]:”+outtradeno + “号订单回调通知。”);
  41. logger.info(“[PayController][getAliPayResult]:验证签名成功!”);
  42. logger.info(“[PayController][getWeChatPayResult]:params”+params.toString());
  43. //若参数中的appid和填入的appid不相同,则为异常通知
  44. if (!Const.APPID.equals(params.get(“app_id”))) {
  45. logger.info(“[PayController][getAliPayResult]:与付款时的appid不同,此为异常通知,应忽略!”);
  46. }
  47. String status = params.get(“trade_status”);
  48. //如果状态是已经支付成功
  49. if (status.equals(“TRADE_SUCCESS”) || status.equals(“TRADE_FINISHED”)) {
  50. //支付宝支付成功后操作…
  51. }
  52. logger.info(“[PayController][getAliPayResult]:”+outtradeno + “订单的状态已经修改为 :” + status);
  53. } else { //如果验证签名没有通过
  54. logger.info(“[PayController][getAliPayResult]:如果验证签名没有通过”);
  55. }
  56. }

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/74671.html

(0)

相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注微信