UDN-企业互联网技术人气社区

板块导航

浏览  : 1251
回复  : 3

[原生js] 微信支付java版本之JSAPI支付+发送模板消息

[复制链接]
饼干妹妹的头像 楼主
发表于 2017-1-16 13:20:27 | 显示全部楼层 |阅读模式
  这篇文章主要介绍了微信支付java版本之JSAPI支付,发送模板消息,感兴趣的小伙伴们可以参考一下

  本文为大家分享了java版本之JSAPI支付+发送模板消息的相关资料,供大家参考,具体内容如下
  
  1.工具类
  
  工具类见:微信支付JAVA版本之Native付款
  
  2.公众账号设置
 
201608041519537.png

201608041519538.png
 
  3.代码实现
  
  openId:openId为用户与该公众账号之间代表用户的唯一标示
  
  以下类中涉及到生成token,关闭订单接口调用,获取配置文件信息,和工具类,在其他文章中有具体代码实现
  1. package com.zhrd.bussinss.platform.controller.rest;

  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.InputStream;
  5. import java.security.KeyStore;
  6. import java.text.SimpleDateFormat;
  7. import java.util.ArrayList;
  8. import java.util.Date;
  9. import java.util.HashMap;
  10. import java.util.List;
  11. import java.util.Map;

  12. import javax.net.ssl.SSLContext;
  13. import javax.servlet.http.HttpServletRequest;
  14. import javax.servlet.http.HttpServletResponse;

  15. import net.sf.json.JSONObject;

  16. import org.apache.http.HttpEntity;
  17. import org.apache.http.client.methods.CloseableHttpResponse;
  18. import org.apache.http.client.methods.HttpPost;
  19. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
  20. import org.apache.http.conn.ssl.SSLContexts;
  21. import org.apache.http.entity.StringEntity;
  22. import org.apache.http.impl.client.CloseableHttpClient;
  23. import org.apache.http.impl.client.HttpClients;
  24. import org.apache.http.util.EntityUtils;
  25. import org.dom4j.Document;
  26. import org.dom4j.DocumentHelper;
  27. import org.dom4j.Element;
  28. import org.dom4j.io.SAXReader;
  29. import org.springframework.beans.factory.annotation.Autowired;
  30. import org.springframework.web.bind.annotation.RequestMapping;
  31. import org.springframework.web.bind.annotation.RequestMethod;
  32. import org.springframework.web.bind.annotation.ResponseBody;
  33. import org.springframework.web.bind.annotation.RestController;

  34. import com.zhrd.bussinss.platform.bo.JsPay;
  35. import com.zhrd.bussinss.platform.bo.PayHist;
  36. import com.zhrd.bussinss.platform.constants.PayHistoryPayStatus;
  37. import com.zhrd.bussinss.platform.constants.PayHistoryPayType;
  38. import com.zhrd.bussinss.platform.service.GetWeiXinAccessTokenService;
  39. import com.zhrd.bussinss.platform.service.WeiXinPayService;
  40. import com.zhrd.bussinss.platform.utils.CloseWeiXinOrderUtils;
  41. import com.zhrd.bussinss.platform.utils.CustomizedPropertyPlaceholderConfigurer;
  42. import com.zhrd.bussinss.platform.weixinPayUtils.ClientCustomSSL;

  43. @RestController
  44. @RequestMapping("/rest/weiXinSendMessage")
  45. public class WeiXinSendMessageRESTFULController {


  46. @Autowired
  47. WeiXinPayService weiXinPayService;
  48. @Autowired
  49. GetWeiXinAccessTokenService getWeiXinAccessTokenService;

  50. private static long standardTime = 1662652800000L;



  51. /**
  52. * 微信发送消息
  53. * @param request
  54. * @param response
  55. * @return
  56. */
  57. @RequestMapping(value="/weiXinSend",method=RequestMethod.GET)
  58. @ResponseBody
  59. public Object weiXinSend(HttpServletRequest request,HttpServletResponse response,String orderNo,String openId){
  60. System.out.println("==========================微信发送消息开始========================"+getWeiXinAccessTokenService.accessToken());
  61. try{

  62. KeyStore keyStore = KeyStore.getInstance("PKCS12");
  63. FileInputStream instream = new FileInputStream(new File(
  64. CustomizedPropertyPlaceholderConfigurer.getContextProperty("wx.cert").toString()));
  65. try {
  66. keyStore.load(instream, "见邮件".toCharArray());
  67. }finally {
  68. instream.close();
  69. }

  70. // Trust own CA and all self-signed certs
  71. SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore,
  72. "10061401".toCharArray()).build();
  73. // Allow TLSv1 protocol only
  74. SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
  75. sslcontext, new String[] { "TLSv1" }, null,
  76. SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
  77. CloseableHttpClient httpclient = HttpClients.custom()
  78. .setSSLSocketFactory(sslsf).build();
  79. // HttpGet httpget = new
  80. // HttpGet("https://api.mch.weixin.qq.com/secapi/pay/refund");   //获取token详见获取token的文章
  81. HttpPost httppost = new HttpPost(
  82. "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+getWeiXinAccessTokenService.accessToken());



  83. PayHist ph = null;
  84. List<Map<String,Object>> td = weiXinPayService.getTrade(orderNo);
  85. Date dt = new Date();
  86. SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
  87. String nonceStr = sdf.format(dt).toString();
  88. Date now = new Date();

  89. String tradePayNo = orderNo+String.format("%10d",standardTime - now.getTime()).substring(0, 10);
  90. System.out.println("订单标号orderNo======="+orderNo);
  91. System.out.println("10位随机数======="+String.format("%10d",standardTime - now.getTime()).substring(0, 10));
  92. String price = Math.round(Float.valueOf(td.get(0).get("price").toString())*100)+"";
  93. Long timeExpireStrOld = dt.getTime();   //获取配置文件信息 详见获取配置文件信息的文章
  94. Long timeNew = Long.parseLong(CustomizedPropertyPlaceholderConfigurer.getContextProperty("weixin.send2finish.overtime").toString());
  95. Long timeExpireNew = timeExpireStrOld+timeNew;
  96. Date dtTimeExpire = new Date(timeExpireNew);
  97. SimpleDateFormat dtSdf = new SimpleDateFormat("yyyyMMddHHmmss");
  98. String timeExpire = dtSdf.format(dtTimeExpire).toString();
  99. System.out.println("nonceStr=="+nonceStr);
  100. System.out.println("orderNo=="+orderNo);
  101. System.out.println("price=="+price);
  102. System.out.println("timeStart=="+nonceStr);
  103. System.out.println("timeExpire=="+timeExpire);



  104. JSONObject resultJsPay = (JSONObject) getJsPay(nonceStr, "订单", tradePayNo, price, nonceStr,timeExpire,openId);
  105. resultJsPay.getString("prepayId");

  106. System.out.println("================222prepay_id222========================="+resultJsPay.getString("prepayId").toString());

  107. List<Map<String,Map<String,String>>> data = new ArrayList<Map<String,Map<String,String>>>();
  108. Map<String,Map<String,String>> firstparam = new HashMap<String, Map<String,String>>();
  109. Map<String,String> valueParam = new HashMap<String, String>();
  110. valueParam.put("value", td.get(0).get("buyerName")+"(先生/女士)的订单");
  111. valueParam.put("color", "#173177");
  112. Map<String,String> valueParam1 = new HashMap<String, String>();
  113. valueParam1.put("value", orderNo);
  114. valueParam1.put("color", "#173177");
  115. Map<String,String> valueParam2 = new HashMap<String, String>();
  116. valueParam2.put("value", "智慧社区爱生鲜订单");
  117. valueParam2.put("color", "#173177");
  118. Map<String,String> valueParam3 = new HashMap<String, String>();
  119. valueParam3.put("value", td.get(0).get("price")+"元");
  120. valueParam3.put("color", "#173177");
  121. Map<String,String> valueParam4 = new HashMap<String, String>();
  122. valueParam4.put("value", "等待支付");
  123. valueParam4.put("color", "#173177");
  124. Map<String,String> valueParam5 = new HashMap<String, String>();
  125. valueParam5.put("value", "点击支付");
  126. valueParam5.put("color", "#173177");
  127. firstparam.put("first", valueParam);
  128. firstparam.put("keyword1", valueParam1);
  129. firstparam.put("keyword2", valueParam2);
  130. firstparam.put("keyword3", valueParam3);
  131. firstparam.put("keyword4", valueParam4);
  132. firstparam.put("remark", valueParam5);
  133. data.add(firstparam);

  134. JsPay jp = new JsPay();
  135. jp.setTouser(openId);
  136. jp.setTemplate_id("MieXd4-4uqRFMdjnvqMjH0egFYpm16r5DPDT6P9gPgg");
  137. jp.setTopcolor("#173177");
  138. jp.setUrl("http://公众账号设置的链接/weixin_jspay/weixinJsPay/init.action?packageValue="+resultJsPay.getString("prepayId").toString());
  139. jp.setData(data);
  140. JSONObject jsonObject = JSONObject.fromObject(jp);
  141. String str = new String(jsonObject.toString().getBytes("utf-8"), "iso8859-1");

  142. // String xml = ClientCustomSSL.RefundNativePackage(weiXinRefundService.getTradePayNo(orderNo),nonceStr,totalFee,refundFee,nonceStr);
  143. try {
  144. System.out.println("data=========="+str.toString());
  145. StringEntity se = new StringEntity(str.toString().replace("[", "").replace("]", "").toString());

  146. httppost.setEntity(se);

  147. System.out.println("executing request" + httppost.getRequestLine());

  148. CloseableHttpResponse responseEntry = httpclient.execute(httppost);
  149. try {
  150. HttpEntity entity = responseEntry.getEntity();


  151.   InputStream in = entity.getContent();
  152.   byte b[] = new byte[1024];
  153.   int len = 0;
  154.   int temp=0;  //所有读取的内容都使用temp接收
  155.   while((temp=in.read())!=-1){ //当没有读取完时,继续读取
  156.   b[len]=(byte)temp;
  157.   len++;
  158.   }
  159.   in.close();
  160.   System.out.println(new String(b,0,len));
  161.   
  162.   
  163.   
  164. if (entity != null) {
  165. System.out.println("Response content length: "
  166.   + entity.getContentLength());
  167. System.out.println("==="+responseEntry.getEntity().toString());

  168. JSONObject result = JSONObject.fromObject(new String(b,0,len));
  169. if(result.getString("errmsg").equals("ok")){
  170. ph = new PayHist();
  171. ph.setTradePayUrl("");
  172. ph.setPayTradeNo(orderNo);
  173. ph.setTradePayNo(tradePayNo);
  174. ph.setPayStatus(PayHistoryPayStatus.WECHAT_PAY_STATUS_WAIT);
  175. ph.setPayType(PayHistoryPayType.WECHAT_JS_PAY);
  176. List<PayHist> payHistList = weiXinPayService.getPayHist(orderNo,"wechat","");
  177. if(payHistList == null || payHistList.size() == 0){
  178.   weiXinPayService.addPayHist(ph);
  179. }else{         //关闭订单详见取消订单的文章
  180.   JSONObject strStatus = (JSONObject) CloseWeiXinOrderUtils.closeWeiXinOrder(payHistList.get(0).getTradePayNo());
  181.   if(strStatus.getString("status").equals("success")){
  182.   System.out.println(ph.getTradePayNo());
  183.   weiXinPayService.updatePayHist(ph);
  184.   }
  185. }
  186. }

  187. return result;

  188. }
  189. EntityUtils.consume(entity);
  190. }
  191. finally {
  192. responseEntry.close();
  193. }
  194. }
  195. finally {
  196. httpclient.close();
  197. }
  198. return null;

  199. }catch(Exception e){
  200. e.printStackTrace();
  201. JSONObject result = new JSONObject();
  202. result.put("status","error");
  203. result.put("msg",e.getMessage());
  204. return result;
  205. }


  206. }

  207. public static Object getJsPay(String nonceStr,String orderDescribe,String orderNo,String price,String timeStart,String timeExpire,String openId) {
  208. try{

  209. KeyStore keyStore = KeyStore.getInstance("PKCS12");
  210. FileInputStream instream = new FileInputStream(new File(
  211. CustomizedPropertyPlaceholderConfigurer.getContextProperty("wx.cert").toString()));
  212. try {
  213. keyStore.load(instream, "10061401".toCharArray());
  214. }finally {
  215. instream.close();
  216. }

  217. // Trust own CA and all self-signed certs
  218. SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore,
  219. "见邮件".toCharArray()).build();
  220. // Allow TLSv1 protocol only
  221. SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
  222. sslcontext, new String[] { "TLSv1" }, null,
  223. SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
  224. CloseableHttpClient httpclient = HttpClients.custom()
  225. .setSSLSocketFactory(sslsf).build();
  226. // HttpGet httpget = new
  227. // HttpGet("https://api.mch.weixin.qq.com/secapi/pay/refund");
  228. HttpPost httppost = new HttpPost(
  229. "https://api.mch.weixin.qq.com/pay/unifiedorder");

  230. String xml = ClientCustomSSL.CreateJsApiPackage(nonceStr,orderDescribe,orderNo,price,timeStart,timeExpire,openId);
  231. try {


  232. StringEntity se = new StringEntity(xml);

  233. httppost.setEntity(se);

  234. System.out.println("executing request" + httppost.getRequestLine());

  235. CloseableHttpResponse responseEntry = httpclient.execute(httppost);
  236. try {
  237. HttpEntity entity = responseEntry.getEntity();

  238. System.out.println("----------------------------------------");
  239. System.out.println(responseEntry.getStatusLine());
  240. if (entity != null) {
  241. System.out.println("Response content length: "
  242. + entity.getContentLength());

  243. SAXReader saxReader = new SAXReader();
  244. Document document = saxReader.read(entity.getContent());
  245. Element rootElt = document.getRootElement();

  246. Document documentXml =DocumentHelper.parseText(xml);
  247. Element rootEltXml = documentXml.getRootElement();


  248. System.out.println("根节点:" + rootElt.getName());
  249. System.out.println("==="+rootElt.elementText("result_code"));
  250. System.out.println("==="+rootElt.elementText("return_msg"));
  251. String resultCode = rootElt.elementText("result_code");
  252. JSONObject result = new JSONObject();
  253. if(resultCode.equals("SUCCESS")){
  254. System.out.println("=================prepay_id===================="+ rootElt.elementText("prepay_id"));
  255. result.put("prepayId", rootElt.elementText("prepay_id"));
  256. result.put("sign",rootEltXml.elementText("sign"));
  257. result.put("status","success");
  258. result.put("msg","success");
  259. }else{
  260. result.put("status","false");
  261. result.put("msg",rootElt.elementText("err_code_des"));
  262. }


  263. return result;

  264. }
  265. EntityUtils.consume(entity);
  266. }
  267. finally {
  268. responseEntry.close();
  269. }
  270. }
  271. finally {
  272. httpclient.close();
  273. }
  274. return null;


  275. }catch(Exception e){
  276. e.printStackTrace();
  277. JSONObject result = new JSONObject();
  278. result.put("status","error");
  279. result.put("msg",e.getMessage());
  280. return result;
  281. }
  282. }

  283. }
复制代码

  4.weixin_jspay项目中代码实现
  
  控制层代码
  1. package com.weixin.jspay.controller;



  2. import javax.servlet.http.HttpServletRequest;
  3. import javax.servlet.http.HttpServletResponse;


  4. import org.springframework.stereotype.Controller;
  5. import org.springframework.web.bind.annotation.RequestMapping;
  6. import org.springframework.web.bind.annotation.RequestMethod;



  7. @Controller
  8. @RequestMapping("/weixinJsPay")
  9. public class WeiXinJsPayController {


  10. @RequestMapping(value = "/init", method = RequestMethod.GET)
  11. public String init( HttpServletRequest request,HttpServletResponse response,String packageValue,String paySign) {
  12. System.out.println("===================微信jsPay开始=================");
  13. System.out.println("packageValue==============="+packageValue);
  14. System.out.println("paySign====================="+paySign);
  15. request.setAttribute("packageValue", "prepay_id=" + packageValue);
  16. request.setAttribute("paySign", paySign);
  17. System.out.println("===================微信jsPay页面跳转开始=================");
  18. return "weixin";
  19. }



  20. }



  21.   jsp代码


  22. <%@ page language="java" contentType="text/html; charset=utf-8"
  23. pageEncoding="utf-8"%>
  24. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  25. <html>
  26. <head>
  27. <script type="text/JavaScript" src="/weixin_jspay/js/md5.js"></script>



  28. <script language="JavaScript">
  29. window.onload=function(){
  30. var packageValue = '${packageValue}';
  31. var paySign = '${paySign}';
  32. alert("packageValue======"+packageValue);
  33. alert("paySign======"+paySign);
  34. var signString ="appId=见公共账号&nonceStr=随机字符串&package="+packageValue+"&paySign="+paySign+"&signType=MD5&timeStamp=时间";
  35.   //alert(signString);
  36.   var md5SignValue= ("" + CryptoJS.MD5(signString)).toUpperCase();

  37. //alert(md5SignValue);

  38. WeixinJSBridge.invoke('getBrandWCPayRequest',{
  39.   "appId" : "<span style="font-family: Arial, Helvetica, sans-serif;">见公共账号</span>",
  40.   "timeStamp" : "1395712654",
  41.   "nonceStr" : "123456",
  42.   "package" : packageValue,
  43.   "signType" : "MD5",
  44.   "paySign" : md5SignValue
  45. },function(res){
  46. alert(res.err_msg);
  47. WeixinJSBridge.log(res.err_msg);
  48.   if(res.err_msg == "get_brand_wcpay_request:ok"){
  49.    alert("微信支付成功");
  50.   }else if(res.err_msg == "get_brand_wcpay_request:cancel"){
  51.    alert("用户取消支付");
  52.   }else{
  53.    alert("支付失败");
  54.   }
  55. })
  56. }



  57. </script>
  58. </head>
  59. <body>
  60. <button type="button" onclick="callpay('${packageValue}','${paySign}')" >微信jsPay</button>
  61. </body>
  62. </html>
复制代码

  微信支付MD5.js:md5.js 和微信支付开发文档:下载地址
  
  以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

相关帖子

发表于 2017-1-16 13:21:02 | 显示全部楼层
js太强大了,好多工作前端都可以做了…
使用道具 举报

回复

发表于 2017-1-16 14:22:30 来自手机 | 显示全部楼层
又见楼主分享帖子
使用道具 举报

回复

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关于我们
联系我们
  • 电话:010-86393388
  • 邮件:udn@yonyou.com
  • 地址:北京市海淀区北清路68号
移动客户端下载
关注我们
  • 微信公众号:yonyouudn
  • 扫描右侧二维码关注我们
  • 专注企业互联网的技术社区
版权所有:用友网络科技股份有限公司82041 京ICP备05007539号-11 京公网网备安1101080209224 Powered by Discuz!
快速回复 返回列表 返回顶部