微信支付java版本之JSAPI支付+发送模板消息

来源:互联网 发布:js判断视频播放结束 编辑:程序博客网 时间:2024/06/13 18:55

目录(?)[-]

  1. 工具类
  2. 公众账号设置
  3. 代码实现
  4. weixin_jspay项目中代码实现
  5. 3其他接口

1.工具类

工具类见:微信支付JAVA版本之Native付款

2.公众账号设置






3.代码实现

openId:openId为用户与该公众账号之间代表用户的唯一标示
以下类中涉及到生成token,关闭订单接口调用,获取配置文件信息,和工具类,在其他文章中有具体代码实现
[java] view plaincopy
  1. package com.zhrd.bussinss.platform.controller.rest;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.InputStream;  
  6. import java.security.KeyStore;  
  7. import java.text.SimpleDateFormat;  
  8. import java.util.ArrayList;  
  9. import java.util.Date;  
  10. import java.util.HashMap;  
  11. import java.util.List;  
  12. import java.util.Map;  
  13.   
  14. import javax.net.ssl.SSLContext;  
  15. import javax.servlet.http.HttpServletRequest;  
  16. import javax.servlet.http.HttpServletResponse;  
  17.   
  18. import net.sf.json.JSONObject;  
  19.   
  20. import org.apache.http.HttpEntity;  
  21. import org.apache.http.client.methods.CloseableHttpResponse;  
  22. import org.apache.http.client.methods.HttpPost;  
  23. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;  
  24. import org.apache.http.conn.ssl.SSLContexts;  
  25. import org.apache.http.entity.StringEntity;  
  26. import org.apache.http.impl.client.CloseableHttpClient;  
  27. import org.apache.http.impl.client.HttpClients;  
  28. import org.apache.http.util.EntityUtils;  
  29. import org.dom4j.Document;  
  30. import org.dom4j.DocumentHelper;  
  31. import org.dom4j.Element;  
  32. import org.dom4j.io.SAXReader;  
  33. import org.springframework.beans.factory.annotation.Autowired;  
  34. import org.springframework.web.bind.annotation.RequestMapping;  
  35. import org.springframework.web.bind.annotation.RequestMethod;  
  36. import org.springframework.web.bind.annotation.ResponseBody;  
  37. import org.springframework.web.bind.annotation.RestController;  
  38.   
  39. import com.zhrd.bussinss.platform.bo.JsPay;  
  40. import com.zhrd.bussinss.platform.bo.PayHist;  
  41. import com.zhrd.bussinss.platform.constants.PayHistoryPayStatus;  
  42. import com.zhrd.bussinss.platform.constants.PayHistoryPayType;  
  43. import com.zhrd.bussinss.platform.service.GetWeiXinAccessTokenService;  
  44. import com.zhrd.bussinss.platform.service.WeiXinPayService;  
  45. import com.zhrd.bussinss.platform.utils.CloseWeiXinOrderUtils;  
  46. import com.zhrd.bussinss.platform.utils.CustomizedPropertyPlaceholderConfigurer;  
  47. import com.zhrd.bussinss.platform.weixinPayUtils.ClientCustomSSL;  
  48.   
  49. @RestController  
  50. @RequestMapping("/rest/weiXinSendMessage")  
  51. public class WeiXinSendMessageRESTFULController {  
  52.       
  53.       
  54.     @Autowired  
  55.     WeiXinPayService weiXinPayService;  
  56.     @Autowired  
  57.     GetWeiXinAccessTokenService getWeiXinAccessTokenService;  
  58.       
  59.     private static long standardTime = 1662652800000L;  
  60.       
  61.       
  62.       
  63.     /** 
  64.      * 微信发送消息 
  65.      * @param request 
  66.      * @param response 
  67.      * @return 
  68.      */  
  69.     @RequestMapping(value="/weiXinSend",method=RequestMethod.GET)  
  70.     @ResponseBody  
  71.     public Object weiXinSend(HttpServletRequest request,HttpServletResponse response,String orderNo,String openId){  
  72.         System.out.println("==========================微信发送消息开始========================"+getWeiXinAccessTokenService.accessToken());  
  73.         try{  
  74.           
  75.             KeyStore keyStore = KeyStore.getInstance("PKCS12");  
  76.             FileInputStream instream = new FileInputStream(new File(  
  77.                     CustomizedPropertyPlaceholderConfigurer.getContextProperty("wx.cert").toString()));  
  78.             try {  
  79.                 keyStore.load(instream, "见邮件".toCharArray());  
  80.             }finally {  
  81.                 instream.close();  
  82.             }  
  83.   
  84.             // Trust own CA and all self-signed certs  
  85.             SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore,  
  86.                     "10061401".toCharArray()).build();  
  87.             // Allow TLSv1 protocol only  
  88.             SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(  
  89.                     sslcontext, new String[] { "TLSv1" }, null,  
  90.                     SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);  
  91.             CloseableHttpClient httpclient = HttpClients.custom()  
  92.                     .setSSLSocketFactory(sslsf).build();  
  93.             // HttpGet httpget = new  
  94.             // HttpGet("https://api.mch.weixin.qq.com/secapi/pay/refund");  
[java] view plaincopy
  1.                      //获取token详见获取token的文章  
  2. HttpPost httppost = new HttpPost(  
  3.         "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+getWeiXinAccessTokenService.accessToken());  
  4.   
  5.   
  6.   
  7. PayHist ph = null;  
  8. List<Map<String,Object>> td = weiXinPayService.getTrade(orderNo);  
  9. Date dt = new Date();  
  10. SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");  
  11. String nonceStr = sdf.format(dt).toString();  
  12. Date now = new Date();  
  13.   
  14. String tradePayNo = orderNo+String.format("%10d",standardTime - now.getTime()).substring(010);  
  15. System.out.println("订单标号orderNo======="+orderNo);  
  16. System.out.println("10位随机数======="+String.format("%10d",standardTime - now.getTime()).substring(010));  
  17. String price = Math.round(Float.valueOf(td.get(0).get("price").toString())*100)+"";  
  18. Long timeExpireStrOld = dt.getTime();  
[java] view plaincopy
  1.                     //获取配置文件信息 详见获取配置文件信息的文章  
  2. Long timeNew = Long.parseLong(CustomizedPropertyPlaceholderConfigurer.getContextProperty("weixin.send2finish.overtime").toString());  
  3. Long timeExpireNew = timeExpireStrOld+timeNew;  
  4. Date dtTimeExpire = new Date(timeExpireNew);  
  5. SimpleDateFormat dtSdf = new SimpleDateFormat("yyyyMMddHHmmss");  
  6. String timeExpire = dtSdf.format(dtTimeExpire).toString();  
  7. System.out.println("nonceStr=="+nonceStr);  
  8. System.out.println("orderNo=="+orderNo);  
  9. System.out.println("price=="+price);  
  10. System.out.println("timeStart=="+nonceStr);  
  11. System.out.println("timeExpire=="+timeExpire);  
  12.   
  13.   
  14.   
  15. JSONObject resultJsPay = (JSONObject) getJsPay(nonceStr, "订单", tradePayNo, price, nonceStr,timeExpire,openId);  
  16. resultJsPay.getString("prepayId");  
  17.   
  18. System.out.println("================222prepay_id222========================="+resultJsPay.getString("prepayId").toString());  
  19.   
  20. List<Map<String,Map<String,String>>> data = new ArrayList<Map<String,Map<String,String>>>();  
  21. Map<String,Map<String,String>> firstparam = new HashMap<String, Map<String,String>>();  
  22. Map<String,String> valueParam = new HashMap<String, String>();  
  23. valueParam.put("value", td.get(0).get("buyerName")+"(先生/女士)的订单");  
  24. valueParam.put("color""#173177");  
  25. Map<String,String> valueParam1 = new HashMap<String, String>();  
  26. valueParam1.put("value", orderNo);  
  27. valueParam1.put("color""#173177");  
  28. Map<String,String> valueParam2 = new HashMap<String, String>();  
  29. valueParam2.put("value""智慧社区爱生鲜订单");  
  30. valueParam2.put("color""#173177");  
  31. Map<String,String> valueParam3 = new HashMap<String, String>();  
  32. valueParam3.put("value", td.get(0).get("price")+"元");  
  33. valueParam3.put("color""#173177");  
  34. Map<String,String> valueParam4 = new HashMap<String, String>();  
  35. valueParam4.put("value""等待支付");  
  36. valueParam4.put("color""#173177");  
  37. Map<String,String> valueParam5 = new HashMap<String, String>();  
  38. valueParam5.put("value""点击支付");  
  39. valueParam5.put("color""#173177");  
  40. firstparam.put("first", valueParam);  
  41. firstparam.put("keyword1", valueParam1);  
  42. firstparam.put("keyword2", valueParam2);  
  43. firstparam.put("keyword3", valueParam3);  
  44. firstparam.put("keyword4", valueParam4);  
  45. firstparam.put("remark", valueParam5);  
  46. data.add(firstparam);  
  47.   
  48. JsPay jp = new JsPay();  
  49. jp.setTouser(openId);  
  50. jp.setTemplate_id("MieXd4-4uqRFMdjnvqMjH0egFYpm16r5DPDT6P9gPgg");  
  51. jp.setTopcolor("#173177");  
  52. jp.setUrl("http://公众账号设置的链接/weixin_jspay/weixinJsPay/init.action?packageValue="+resultJsPay.getString("prepayId").toString());  
  53. jp.setData(data);  
  54. JSONObject jsonObject = JSONObject.fromObject(jp);  
  55. String str = new String(jsonObject.toString().getBytes("utf-8"), "iso8859-1");   
  56.   
  57.             String xml = ClientCustomSSL.RefundNativePackage(weiXinRefundService.getTradePayNo(orderNo),nonceStr,totalFee,refundFee,nonceStr);  
  58.     try {  
  59.         System.out.println("data=========="+str.toString());  
  60.         StringEntity se = new StringEntity(str.toString().replace("[""").replace("]""").toString());  
  61.           
  62.         httppost.setEntity(se);  
  63.   
  64.         System.out.println("executing request" + httppost.getRequestLine());  
  65.   
  66.         CloseableHttpResponse responseEntry = httpclient.execute(httppost);  
  67.         try {  
  68.             HttpEntity entity = responseEntry.getEntity();  
  69.               
  70.               
  71.             InputStream in = entity.getContent();     
  72.             byte b[] = new byte[1024];     
  73.             int len = 0;     
  74.             int temp=0;          //所有读取的内容都使用temp接收     
  75.             while((temp=in.read())!=-1){    //当没有读取完时,继续读取     
  76.                 b[len]=(byte)temp;     
  77.                 len++;     
  78.             }     
  79.             in.close();     
  80.             System.out.println(new String(b,0,len));   
  81.               
  82.               
  83.               
  84.             if (entity != null) {  
  85.                 System.out.println("Response content length: "  
  86.                         + entity.getContentLength());  
  87.                 System.out.println("==="+responseEntry.getEntity().toString());  
  88.                   
  89.                 JSONObject result = JSONObject.fromObject(new String(b,0,len));  
  90.                 if(result.getString("errmsg").equals("ok")){  
  91.                     ph = new PayHist();  
  92.                     ph.setTradePayUrl("");  
  93.                     ph.setPayTradeNo(orderNo);  
  94.                     ph.setTradePayNo(tradePayNo);  
  95.                     ph.setPayStatus(PayHistoryPayStatus.WECHAT_PAY_STATUS_WAIT);  
  96.                     ph.setPayType(PayHistoryPayType.WECHAT_JS_PAY);  
  97.                     List<PayHist> payHistList = weiXinPayService.getPayHist(orderNo,"wechat","");  
  98.                     if(payHistList == null || payHistList.size() == 0){  
  99.                         weiXinPayService.addPayHist(ph);  
  100.                     }else{  
[java] view plaincopy
  1.                                                                        //关闭订单详见取消订单的文章  
  2.                                 JSONObject strStatus = (JSONObject) CloseWeiXinOrderUtils.closeWeiXinOrder(payHistList.get(0).getTradePayNo());  
  3.                                 if(strStatus.getString("status").equals("success")){  
  4.                                     System.out.println(ph.getTradePayNo());  
  5.                                     weiXinPayService.updatePayHist(ph);  
  6.                                 }  
  7.                             }  
  8.                         }  
  9.                           
  10.                         return result;  
  11.   
  12.                     }  
  13.                     EntityUtils.consume(entity);  
  14.                 }  
  15.                 finally {  
  16.                     responseEntry.close();  
  17.                 }  
  18.             }  
  19.             finally {  
  20.                 httpclient.close();  
  21.             }  
  22.             return null;  
  23.               
  24.         }catch(Exception e){  
  25.             e.printStackTrace();  
  26.             JSONObject result = new JSONObject();  
  27.             result.put("status","error");  
  28.             result.put("msg",e.getMessage());  
  29.             return result;  
  30.         }  
  31.               
  32.               
  33.         }  
  34.   
  35. public static Object getJsPay(String nonceStr,String orderDescribe,String orderNo,String price,String timeStart,String timeExpire,String openId) {  
  36.     try{  
  37.           
  38.         KeyStore keyStore = KeyStore.getInstance("PKCS12");  
  39.         FileInputStream instream = new FileInputStream(new File(  
  40.                 CustomizedPropertyPlaceholderConfigurer.getContextProperty("wx.cert").toString()));  
  41.         try {  
  42.             keyStore.load(instream, "10061401".toCharArray());  
  43.         }finally {  
  44.             instream.close();  
  45.         }  
  46.   
  47.         // Trust own CA and all self-signed certs  
  48.         SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore,  
  49.                 "见邮件".toCharArray()).build();  
  50.         // Allow TLSv1 protocol only  
  51.         SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(  
  52.                 sslcontext, new String[] { "TLSv1" }, null,  
  53.                 SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);  
  54.         CloseableHttpClient httpclient = HttpClients.custom()  
  55.                 .setSSLSocketFactory(sslsf).build();  
  56.         // HttpGet httpget = new  
  57.         // HttpGet("https://api.mch.weixin.qq.com/secapi/pay/refund");  
  58.         HttpPost httppost = new HttpPost(  
  59.                 "https://api.mch.weixin.qq.com/pay/unifiedorder");  
  60.           
  61.         String xml = ClientCustomSSL.CreateJsApiPackage(nonceStr,orderDescribe,orderNo,price,timeStart,timeExpire,openId);  
  62.         try {  
  63.   
  64.               
  65.             StringEntity se = new StringEntity(xml);  
  66.               
  67.             httppost.setEntity(se);  
  68.   
  69.             System.out.println("executing request" + httppost.getRequestLine());  
  70.   
  71.             CloseableHttpResponse responseEntry = httpclient.execute(httppost);  
  72.             try {  
  73.                 HttpEntity entity = responseEntry.getEntity();  
  74.   
  75.                 System.out.println("----------------------------------------");  
  76.                 System.out.println(responseEntry.getStatusLine());  
  77.                 if (entity != null) {  
  78.                     System.out.println("Response content length: "  
  79.                             + entity.getContentLength());  
  80.                       
  81.                     SAXReader saxReader = new SAXReader();  
  82.                     Document document = saxReader.read(entity.getContent());  
  83.                     Element rootElt = document.getRootElement();  
  84.                       
  85.                     Document documentXml =DocumentHelper.parseText(xml);  
  86.                     Element rootEltXml = documentXml.getRootElement();  
  87.                       
  88.                       
  89.                     System.out.println("根节点:" + rootElt.getName());  
  90.                     System.out.println("==="+rootElt.elementText("result_code"));  
  91.                     System.out.println("==="+rootElt.elementText("return_msg"));  
  92.                     String resultCode = rootElt.elementText("result_code");  
  93.                     JSONObject result = new JSONObject();  
  94.                     if(resultCode.equals("SUCCESS")){  
  95.                         System.out.println("=================prepay_id===================="+ rootElt.elementText("prepay_id"));  
  96.                         result.put("prepayId",  rootElt.elementText("prepay_id"));  
  97.                         result.put("sign",rootEltXml.elementText("sign"));  
  98.                         result.put("status","success");  
  99.                         result.put("msg","success");  
  100.                     }else{  
  101.                         result.put("status","false");  
  102.                         result.put("msg",rootElt.elementText("err_code_des"));  
  103.                     }  
  104.                       
  105.                       
  106.                     return result;  
  107.   
  108.                 }  
  109.                 EntityUtils.consume(entity);  
  110.             }  
  111.             finally {  
  112.                 responseEntry.close();  
  113.             }  
  114.         }  
  115.         finally {  
  116.             httpclient.close();  
  117.         }  
  118.         return null;  
  119.           
  120.           
  121.     }catch(Exception e){  
  122.         e.printStackTrace();  
  123.         JSONObject result = new JSONObject();  
  124.         result.put("status","error");  
  125.         result.put("msg",e.getMessage());  
  126.         return result;  
  127.     }  
  128. }     
  129.       
  130. }  

4.weixin_jspay项目中代码实现

控制层代码
[java] view plaincopy
  1. package com.weixin.jspay.controller;  
  2.   
  3.   
  4.   
  5. import javax.servlet.http.HttpServletRequest;  
  6. import javax.servlet.http.HttpServletResponse;  
  7.   
  8.   
  9. import org.springframework.stereotype.Controller;  
  10. import org.springframework.web.bind.annotation.RequestMapping;  
  11. import org.springframework.web.bind.annotation.RequestMethod;  
  12.   
  13.   
  14.   
  15. @Controller  
  16. @RequestMapping("/weixinJsPay")  
  17. public class WeiXinJsPayController {  
  18.       
  19.   
  20.     @RequestMapping(value = "/init", method = RequestMethod.GET)  
  21.     public String init( HttpServletRequest request,HttpServletResponse response,String packageValue,String paySign) {  
  22.         System.out.println("===================微信jsPay开始=================");  
  23.         System.out.println("packageValue==============="+packageValue);  
  24.         System.out.println("paySign====================="+paySign);  
  25.         request.setAttribute("packageValue""prepay_id=" + packageValue);  
  26.         request.setAttribute("paySign", paySign);  
  27.         System.out.println("===================微信jsPay页面跳转开始=================");  
  28.     return "weixin";  
  29.     }  
  30.       
  31.       
  32.   
  33. }  
jsp代码
[html] view plaincopy
  1. <%@ page language="java" contentType="text/html; charset=utf-8"  
  2.     pageEncoding="utf-8"%>  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  4. <html>  
  5. <head>  
  6. <script type="text/javascript" src="/weixin_jspay/js/md5.js"></script>  
  7.   
  8.           
  9.   
  10.         <script language="javascript">  
  11.         window.onload=function(){  
  12.             var packageValue = '${packageValue}';  
  13.             var paySign = '${paySign}';  
  14.             alert("packageValue======"+packageValue);  
  15.             alert("paySign======"+paySign);  
  16.             var signString ="appId=见公共账号&nonceStr=随机字符串&package="+packageValue+"&paySign="+paySign+"&signType=MD5&timeStamp=时间";          
  17.             //alert(signString);  
  18.             var md5SignValue= ("" + CryptoJS.MD5(signString)).toUpperCase();  
  19.               
  20.             //alert(md5SignValue);  
  21.                   
  22.                  WeixinJSBridge.invoke('getBrandWCPayRequest',{  
  23.                         "appId" : "<span style="font-family: Arial, Helvetica, sans-serif;">见公共账号</span>",  
  24.                         "timeStamp" : "1395712654",  
  25.                         "nonceStr" : "123456",  
  26.                         "package" : packageValue,  
  27.                         "signType" : "MD5",   
  28.                         "paySign" : md5SignValue  
  29.                  },function(res){  
  30.                             alert(res.err_msg);  
  31.                             WeixinJSBridge.log(res.err_msg);    
  32.                             if(res.err_msg == "get_brand_wcpay_request:ok"){    
  33.                                 alert("微信支付成功");    
  34.                             }else if(res.err_msg == "get_brand_wcpay_request:cancel"){    
  35.                                 alert("用户取消支付");    
  36.                             }else{    
  37.                                 alert("支付失败");    
  38.                             }    
  39.                 })  
  40.         }  
  41.           
  42.           
  43.           
  44.         </script>  
  45.     </head>  
  46.   <body>  
  47.     <button type="button" onclick="callpay('${packageValue}','${paySign}')" >微信jsPay</button>   
  48.   </body>  
  49. </html>  

微信支付MD5.js:md5.js
微信支付开发文档:http://download.csdn.net/detail/wangxuewei111/8460215

3.其他接口

微信获取access_token:http://blog.csdn.net/wangxuewei111/article/details/44020571

微信支付native支付+工具类:http://blog.csdn.net/wangxuewei111/article/details/43954857

微信退款申请:http://blog.csdn.net/wangxuewei111/article/details/44021035

微信关闭订单:http://blog.csdn.net/wangxuewei111/article/details/44020881

微信查询订单:http://blog.csdn.net/wangxuewei111/article/details/44037267


版权声明:本文为博主原创文章,未经博主允许不得转载。

0 0
原创粉丝点击