微信支付java版本之Native付款



一、前期准备

做微信开发首先要申请一个公共账号,申请成功后会以邮件形式发给你一些必要信息,公共账号中有开发文档以及开发中必要信息,以及测试的数据查询。



二、工具类

1.MD5加密工具类

[java]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. package com.pay.utils.weixin;  
  2. import java.security.MessageDigest;  
  3. public class MD5Util {  
  4.     public final static String MD5(String s) {  
  5.         char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};         
  6.         try {  
  7.             byte[] btInput = s.getBytes();  
  8.             // 获得MD5摘要算法的 MessageDigest 对象  
  9.             MessageDigest mdInst = MessageDigest.getInstance("MD5");  
  10.             // 使用指定的字节更新摘要  
  11.             mdInst.update(btInput);  
  12.             // 获得密文  
  13.             byte[] md = mdInst.digest();  
  14.             // 把密文转换成十六进制的字符串形式  
  15.             int j = md.length;  
  16.             char str[] = new char[j * 2];  
  17.             int k = 0;  
  18.             for (int i = 0; i < j; i++) {  
  19.                 byte byte0 = md[i];  
  20.                 str[k++] = hexDigits[byte0 >>> 4 & 0xf];  
  21.                 str[k++] = hexDigits[byte0 & 0xf];  
  22.             }  
  23.             return new String(str);  
  24.         } catch (Exception e) {  
  25.             e.printStackTrace();  
  26.             return null;  
  27.        }  
  28.     }  
  29. }  

2.CommonUtil工具类,用于装换成微信所需XML。以下return new String(xml.toString().getBytes(),"ISO8859-1");将工具类中的utf-8改成iso8859-1,否则微信订单中的中文会出现乱码,改后可以正确显示。

[java]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. package com.pay.utils.weixin;  
  2.   
  3. import java.io.UnsupportedEncodingException;  
  4. import java.net.URLEncoder;  
  5. import java.util.*;  
  6. import java.util.Map.Entry;  
  7.   
  8. public class CommonUtil {  
  9.   
  10.     public static String CreateNoncestr(int length) {  
  11.         String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";  
  12.         String res = "";  
  13.         for (int i = 0; i < length; i++) {  
  14.             Random rd = new Random();  
  15.             res += chars.indexOf(rd.nextInt(chars.length() - 1));  
  16.         }  
  17.         return res;  
  18.     }  
  19.   
  20.     public static String CreateNoncestr() {  
  21.         String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";  
  22.         String res = "";  
  23.         for (int i = 0; i < 16; i++) {  
  24.             Random rd = new Random();  
  25.             res += chars.charAt(rd.nextInt(chars.length() - 1));  
  26.         }  
  27.         return res;  
  28.     }  
  29.   
  30.     public static String FormatQueryParaMap(HashMap<String, String> parameters)  
  31.             throws SDKRuntimeException {  
  32.   
  33.         String buff = "";  
  34.         try {  
  35.             List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(  
  36.                     parameters.entrySet());  
  37.   
  38.             Collections.sort(infoIds,  
  39.                     new Comparator<Map.Entry<String, String>>() {  
  40.                         public int compare(Map.Entry<String, String> o1,  
  41.                                 Map.Entry<String, String> o2) {  
  42.                             return (o1.getKey()).toString().compareTo(  
  43.                                     o2.getKey());  
  44.                         }  
  45.                     });  
  46.   
  47.             for (int i = 0; i < infoIds.size(); i++) {  
  48.                 Map.Entry<String, String> item = infoIds.get(i);  
  49.                 if (item.getKey() != "") {  
  50.                     buff += item.getKey() + "="  
  51.                             + URLEncoder.encode(item.getValue(), "utf-8") + "&";  
  52.                 }  
  53.             }  
  54.             if (buff.isEmpty() == false) {  
  55.                 buff = buff.substring(0, buff.length() - 1);  
  56.             }  
  57.         } catch (Exception e) {  
  58.             throw new SDKRuntimeException(e.getMessage());  
  59.         }  
  60.   
  61.         return buff;  
  62.     }  
  63.   
  64.     public static String FormatBizQueryParaMap(HashMap<String, String> paraMap,  
  65.             boolean urlencode) throws SDKRuntimeException {  
  66.   
  67.         String buff = "";  
  68.         try {  
  69.             List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(  
  70.                     paraMap.entrySet());  
  71.   
  72.             Collections.sort(infoIds,  
  73.                     new Comparator<Map.Entry<String, String>>() {  
  74.                         public int compare(Map.Entry<String, String> o1,  
  75.                                 Map.Entry<String, String> o2) {  
  76.                             return (o1.getKey()).toString().compareTo(  
  77.                                     o2.getKey());  
  78.                         }  
  79.                     });  
  80.   
  81.             for (int i = 0; i < infoIds.size(); i++) {  
  82.                 Map.Entry<String, String> item = infoIds.get(i);  
  83.                 //System.out.println(item.getKey());  
  84.                 if (item.getKey() != "") {  
  85.                       
  86.                     String key = item.getKey();  
  87.                     String val = item.getValue();  
  88.                     if (urlencode) {  
  89.                         val = URLEncoder.encode(val, "utf-8");  
  90.   
  91.                     }  
  92.                     buff += key.toLowerCase() + "=" + val + "&";  
  93.   
  94.                 }  
  95.             }  
  96.   
  97.             if (buff.isEmpty() == false) {  
  98.                 buff = buff.substring(0, buff.length() - 1);  
  99.             }  
  100.         } catch (Exception e) {  
  101.             throw new SDKRuntimeException(e.getMessage());  
  102.         }  
  103.         return buff;  
  104.     }  
  105.   
  106.     public static boolean IsNumeric(String str) {  
  107.         if (str.matches("\\d *")) {  
  108.             return true;  
  109.         } else {  
  110.             return false;  
  111.         }  
  112.     }  
  113.   
  114.     public static String ArrayToXml(HashMap<String, String> arr) {  
  115.         String xml = "<xml>";  
  116.           
  117.         Iterator<Entry<String, String>> iter = arr.entrySet().iterator();  
  118.         while (iter.hasNext()) {  
  119.             Entry<String, String> entry = iter.next();  
  120.             String key = entry.getKey();  
  121.             String val = entry.getValue();  
  122.             if (IsNumeric(val)) {  
  123.                 xml += "<" + key + ">" + val + "</" + key + ">";  
  124.   
  125.             } else  
  126.                 xml += "<" + key + "><![CDATA[" + val + "]]></" + key + ">";  
  127.         }  
  128.   
  129.         xml += "</xml>";  
  130.          try {  
  131.             return new String(xml.toString().getBytes(),"ISO8859-1");  
  132.         } catch (UnsupportedEncodingException e) {  
  133.             // TODO Auto-generated catch block  
  134.             e.printStackTrace();  
  135.         }    
  136.          return "";  
  137.     }  
  138.   
  139. }  


3.ClientCustomSSL工具类,用于生成sign以及创建微信订单
[java]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. package com.pay.utils.weixin;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.Collections;  
  5. import java.util.Comparator;  
  6. import java.util.HashMap;  
  7. import java.util.List;  
  8. import java.util.Map;  
  9.   
  10. import org.springframework.util.StringUtils;  
  11.   
  12.   
  13.   
  14. /** 
  15.  * This example demonstrates how to create secure connections with a custom SSL 
  16.  * context. 
  17.  */  
  18. public class ClientCustomSSL {  
  19.   
  20.      public static String GetBizSign(HashMap<String, String> bizObj)  
  21.             throws SDKRuntimeException {  
  22.         HashMap<String, String> bizParameters = new HashMap<String, String>();  
  23.   
  24.         List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(  
  25.                 bizObj.entrySet());  
  26.         System.out.println(infoIds);  
  27.         Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>() {  
  28.             public int compare(Map.Entry<String, String> o1,  
  29.                     Map.Entry<String, String> o2) {  
  30.                 return (o1.getKey()).toString().compareTo(o2.getKey());  
  31.             }  
  32.         });  
  33. System.out.println("--------------------");  
  34.         System.out.println(infoIds);  
  35.         for (int i = 0; i < infoIds.size(); i++) {  
  36.             Map.Entry<String, String> item = infoIds.get(i);  
  37.             if (item.getKey() != "") {  
  38.                 bizParameters.put(item.getKey().toLowerCase(), item.getValue());  
  39.             }  
  40.         }  
  41.         //bizParameters.put("key", "12345678123456781234567812345671");  
  42.         String bizString = CommonUtil.FormatBizQueryParaMap(bizParameters,  
  43.                 false);  
  44.         bizString += "&key=12345678123456781234567812345671";  
  45.         System.out.println("***************");  
  46.           
  47.         System.out.println(bizString);  
  48.   
  49. //      return SHA1Util.Sha1(bizString);  
  50.         return MD5Util.MD5(bizString);  
  51.   
  52.     }  
  53.     /** 
  54.      * 微信创建订单 
  55.      * @param nonceStr 
  56.      * @param orderDescribe 
  57.      * @param orderNo 
  58.      * @param price 
  59.      * @param timeStart 
  60.      * @param timeExpire 
  61.      * @return 
  62.      * @throws SDKRuntimeException 
  63.      */  
  64.      public static String CreateNativePackage(String nonceStr,String orderDescribe,String orderNo,String price,String timeStart,String timeExpire) throws SDKRuntimeException {  
  65.         HashMap<String, String> nativeObj = new HashMap<String, String>();  
  66.         nativeObj.put("appid""见公众账号");                            //公众账号Id  
  67.         nativeObj.put("mch_id""见邮件");                 //商户号  
  68.         nativeObj.put("nonce_str", nonceStr);                       //随机字符串  
  69.         nativeObj.put("body", orderDescribe);                   //商品描述  
  70.         nativeObj.put("attach""tradeno");                 //附加数据  
  71.         nativeObj.put("out_trade_no", orderNo);                         //商户订单号(全局唯一)  
  72.         nativeObj.put("total_fee", price);                  //总金额(单位为分,不能带小数点)  
  73.         nativeObj.put("spbill_create_ip","192.168.0.144");              //终端Ip  
  74.         nativeObj.put("time_start", timeStart);                         //交易起始时间  
  75.         nativeObj.put("time_expire", timeExpire);                   //交易结束时间  
  76.         nativeObj.put("notify_url", CustomizedPropertyPlaceholderConfigurer.getContextProperty("wxurl")+"/weixin_callback/weixinCallback/init.action");                                                 //回调通知地址  
  77.         nativeObj.put("trade_type""NATIVE");                  //交易类型  
  78.           
  79.         String sign = GetBizSign(nativeObj);  
  80.           
  81.         nativeObj.put("sign", sign.toUpperCase());  
  82.           
  83.         return CommonUtil.ArrayToXml(nativeObj);  
  84.   
  85.     }      
[java]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1.           /** 
  2. * 微信订单支付查询 
  3. * @param nonceStr 
  4. * @param orderDescribe 
  5. * @param orderNo 
  6. * @param price 
  7. * @param timeStart 
  8. * @param timeExpire 
  9. * @return 
  10. * @throws SDKRuntimeException 
  11. */  
  12. public static String SearchNativePackage(String transactionId,String outTradeNo,String nonceStr) throws SDKRuntimeException {  
  13. HashMap<String, String> nativeObj = new HashMap<String, String>();  
  14. nativeObj.put("appid""见公众共账号"); //公众账号Id  
  15. nativeObj.put("mch_id""见邮件");//商户号  
  16. nativeObj.put("nonce_str", nonceStr);//随机字符串  
  17. if(!StringUtils.isEmpty(transactionId)){  
  18. nativeObj.put("transaction_id", transactionId);   
  19. }  
  20. if(!StringUtils.isEmpty(outTradeNo)){  
  21. nativeObj.put("out_trade_no", outTradeNo);//随机字符串  
  22. }  
  23. String sign = GetBizSign(nativeObj);  
  24. nativeObj.put("sign", sign.toUpperCase());    
  25. return CommonUtil.ArrayToXml(nativeObj);  
  26.  /** 
  27. * 微信退款 
  28. * @param outTradeNo 
  29. * @param outRefundNo 
  30.  * @param totalFee 
  31. * @param refundFee 
  32. * @return 
  33. * @throws SDKRuntimeException 
  34. */  
  35. public static String RefundNativePackage(String outTradeNo,String outRefundNo,String totalFee,String refundFee,String nonceStr) throws SDKRuntimeException {  
  36. HashMap<String, String> nativeObj = new HashMap<String, String>();  
  37. nativeObj.put("appid""见公众账号");//公众账号Id  
  38. nativeObj.put("mch_id""见邮件");//商户号  
  39. nativeObj.put("nonce_str", nonceStr);//随机字符串  
  40. nativeObj.put("out_trade_no", outTradeNo);//商户订单号(全局唯一)  
  41. nativeObj.put("out_refund_no", outRefundNo);//商户退款单号(全局唯一)  
  42. nativeObj.put("total_fee", totalFee);//总金额(单位为分,不能带小数点)  
  43. nativeObj.put("refund_fee", refundFee);//退款金额(单位为分,不能带小数点)  
  44. nativeObj.put("op_user_id""邮件");  
  45. String sign = GetBizSign(nativeObj);  
  46. nativeObj.put("sign", sign.toUpperCase());  
  47. return CommonUtil.ArrayToXml(nativeObj);  
  48. }  
  49.   
  50. /** 
  51. * 微信待支付 
  52.  * @param nonceStr 
  53. * @param orderDescribe 
  54. * @param orderNo 
  55. * @param price 
  56. * @param timeStart 
  57. * @param timeExpire 
  58. * @return 
  59. * @throws SDKRuntimeException 
  60. */  
  61. public static String CreateJsApiPackage(String nonceStr,String orderDescribe,String orderNo,String price,String timeStart,String timeExpire,String openId) throws SDKRuntimeException {  
  62. HashMap<String, String> nativeObj = new HashMap<String, String>();  
  63. nativeObj.put("appid""见公众账号");//公众账号Id  
  64. nativeObj.put("openid", openId);//公众账号Id  
  65. nativeObj.put("mch_id""见邮件")//商户号  
  66. nativeObj.put("nonce_str", nonceStr);//随机字符串  
  67. nativeObj.put("body", orderDescribe);//商品描述  
  68. nativeObj.put("attach""tradeno");//附加数据  
  69. nativeObj.put("out_trade_no", orderNo);//商户订单号(全局唯一)  
  70. nativeObj.put("total_fee", price);//总金额(单位为分,不能带小数点)  
  71. nativeObj.put("spbill_create_ip","192.168.0.144");//终端Ip  
  72. nativeObj.put("time_start", timeStart);//交易起始时间  
  73. nativeObj.put("time_expire", timeExpire)//交易结束时间  
  74. nativeObj.put("notify_url",CustomizedPropertyPlaceholderConfigurer.getContextProperty("wxurl")+"/weixin_callback/weixinCallback/init.action");//通知地址  
  75. nativeObj.put("trade_type""JSAPI");//交易类型  
  76. String sign = GetBizSign(nativeObj);  
  77. nativeObj.put("sign", sign.toUpperCase());  
  78. return CommonUtil.ArrayToXml(nativeObj);  
  79. }  
  80. /** 
  81. * 微信关闭订单 
  82. * @param nonceStr 
  83. * @param orderDescribe 
  84. * @param orderNo 
  85. * @param price 
  86. * @param timeStart 
  87. * @param timeExpire 
  88. * @param openId 
  89. * @return 
  90. * @throws SDKRuntimeException 
  91. */  
  92. public static String CreateCloseOrder(String outTradeNo,String nonceStr) throws SDKRuntimeException {  
  93. HashMap<String, String> nativeObj = new HashMap<String, String>();  
  94. nativeObj.put("appid""见公众账号");//公众账号Id  
  95. nativeObj.put("mch_id""见邮件");//商户号  
  96. nativeObj.put("out_trade_no", outTradeNo);//商户订单号(全局唯一)  
  97. nativeObj.put("nonce_str", nonceStr);//随机字符串  
  98.  String sign = GetBizSign(nativeObj);  
  99. nativeObj.put("sign", sign.toUpperCase());  
  100.  return CommonUtil.ArrayToXml(nativeObj);  
  101. }  
  102. }  

4.调用微信支付接口

[java]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. package com.pay.controller.weixin;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.security.KeyStore;  
  6. import java.text.SimpleDateFormat;  
  7. import java.util.Date;  
  8. import java.util.List;  
  9.   
  10. import javax.net.ssl.SSLContext;  
  11. import javax.servlet.http.HttpServletRequest;  
  12. import javax.servlet.http.HttpServletResponse;  
  13.   
  14. import net.sf.json.JSONArray;  
  15. import net.sf.json.JSONObject;  
  16.   
  17. import org.apache.http.HttpEntity;  
  18. import org.apache.http.client.methods.CloseableHttpResponse;  
  19. import org.apache.http.client.methods.HttpPost;  
  20. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;  
  21. import org.apache.http.conn.ssl.SSLContexts;  
  22. import org.apache.http.entity.StringEntity;  
  23. import org.apache.http.impl.client.CloseableHttpClient;  
  24. import org.apache.http.impl.client.HttpClients;  
  25. import org.apache.http.util.EntityUtils;  
  26. import org.dom4j.Document;  
  27. import org.dom4j.DocumentHelper;  
  28. import org.dom4j.Element;  
  29. import org.dom4j.io.SAXReader;  
  30. import org.springframework.beans.factory.annotation.Autowired;  
  31. import org.springframework.http.HttpStatus;  
  32. import org.springframework.web.bind.annotation.RequestBody;  
  33. import org.springframework.web.bind.annotation.RequestMapping;  
  34. import org.springframework.web.bind.annotation.RequestMethod;  
  35. import org.springframework.web.bind.annotation.ResponseStatus;  
  36. import org.springframework.web.bind.annotation.RestController;  
  37.   
  38. import com.pay.bo.PayHist;  
  39. import com.pay.constants.PayHistoryPayStatus;  
  40. import com.pay.constants.PayHistoryPayType;  
  41. import com.pay.service.WeiXinPayService;  
  42. import com.pay.utils.weixin.ClientCustomSSL;  
  43. import com.pay.utils.weixin.CloseWeiXinOrderUtils;  
  44. import com.pay.utils.weixin.CustomizedPropertyPlaceholderConfigurer;  
  45.   
  46.   
  47. @RestController  
  48. @RequestMapping("/Pay")  
  49. public class WeiXinPayController {  
  50.       
  51.       
  52.     @Autowired  
  53.     WeiXinPayService weiXinPayService;  
  54.     private static long standardTime = 1662652800000L;  
  55.       
  56.     /** 
  57.      * 返回生成二维码的url 
  58.      * @param request 
  59.      * @param response 
  60.      * @return 
  61.      */  
  62.     @RequestMapping(value="/getUrl",method=RequestMethod.POST)  
  63.     @ResponseStatus(HttpStatus.OK)  
  64.     public Object getUrl(HttpServletResponse response,@RequestBody String body){  
  65.         try{  
  66.             JSONObject jsonO = JSONObject.fromObject(body);  
  67.             PayHist ph = null;  
  68. //          List<Map<String,Object>> td = weiXinPayService.getTrade(orderNo);  
  69.             Date dt = new Date();  
  70.             SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");  
  71.             String nonceStr = sdf.format(dt).toString();  
  72.             Date now = new Date();  
  73.               
  74.             String tradePayNo = jsonO.get("orderNo").toString()+String.format("%10d",standardTime - now.getTime()).substring(010);  
  75.             System.out.println("订单标号orderNo======="+jsonO.get("orderNo").toString());  
  76.             System.out.println("10位随机数======="+String.format("%10d",standardTime - now.getTime()).substring(010));  
  77.             String price = Math.round(Float.valueOf(jsonO.get("price").toString())*100)+"";  
  78.             Long timeExpireStrOld = dt.getTime();  
  79.             Long timeNew = Long.parseLong(CustomizedPropertyPlaceholderConfigurer.getContextProperty("weixin.send2finish.overtime").toString());  
  80.             Long timeExpireNew = timeExpireStrOld+timeNew;  
  81.             Date dtTimeExpire = new Date(timeExpireNew);  
  82.             SimpleDateFormat dtSdf = new SimpleDateFormat("yyyyMMddHHmmss");  
  83.             String timeExpire = dtSdf.format(dtTimeExpire).toString();  
  84.             System.out.println("nonceStr=="+nonceStr);  
  85.             System.out.println("orderNo=="+jsonO.get("orderNo").toString());  
  86.             System.out.println("price=="+price);  
  87.             System.out.println("timeStart=="+nonceStr);  
  88.             System.out.println("timeExpire=="+timeExpire);  
  89.               
  90.               
  91.             JSONObject result = (JSONObject) setUrl(nonceStr,"订单",tradePayNo,price,nonceStr,timeExpire);  
  92.               
  93.             if(result.get("status").toString().equals("success")){  
  94.                 ph = new PayHist();  
  95.                 ph.setTradePayUrl(result.getString("weixinPayUrl"));//此字段为支付链接,可以此链接生成二维码扫码支付  
  96.                 ph.setPayTradeNo(jsonO.get("orderNo").toString());  
  97.                 ph.setTradePayNo(tradePayNo);  
  98.                 ph.setPayStatus(PayHistoryPayStatus.WECHAT_PAY_STATUS_WAIT);  
  99.                 ph.setPayType(PayHistoryPayType.WECHAT);  
  100.                 ph.setAppKey(jsonO.getString("appKey").toString());  
  101.                 ph.setPayAmount(price);  
  102.                   
  103.                 result.put("payTradeNo", ph.getPayTradeNo());  
  104.                 result.put("tradePayNo", ph.getTradePayNo());  
  105.                 result.put("payStatus", ph.getPayStatus());  
  106.                 result.put("payType", ph.getPayType());  
  107.                   
  108.             }             
  109.             return result;  
  110.               
  111.               
  112.         }catch(Exception e){  
  113.             e.printStackTrace();  
  114.             JSONObject result = new JSONObject();  
  115.             result.put("status","error");  
  116.             result.put("msg",e.getMessage());  
  117. //          return result.toString();  
  118.         }  
  119.         return null;  
  120.       
  121.           
  122.     }  
  123.   
  124.     public Object setUrl(String nonceStr,String orderDescribe,String orderNo,String price,String timeStart,String timeExpire) {  
  125.         try{  
  126.               
  127.             KeyStore keyStore = KeyStore.getInstance("PKCS12");  
  128.             FileInputStream instream = new FileInputStream(new File(微信证书绝对路径));  
  129.             try {  
  130.                 keyStore.load(instream, "商户ID".toCharArray());  
  131.             }finally {  
  132.                 instream.close();  
  133.             }  
  134.   
  135.             // Trust own CA and all self-signed certs  
  136.             SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore,<span style="font-family: Arial, Helvetica, sans-serif;">商户ID</span>.toCharArray()).build();  
  137.             // Allow TLSv1 protocol only  
  138.             SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(  
  139.                     sslcontext, new String[] { "TLSv1" }, null,  
  140.                     SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);  
  141.             CloseableHttpClient httpclient = HttpClients.custom()  
  142.                     .setSSLSocketFactory(sslsf).build();  
  143.             // HttpGet httpget = new  
  144.             // HttpGet("https://api.mch.weixin.qq.com/secapi/pay/refund");  
  145.             HttpPost httppost = new HttpPost(  
  146.                     "https://api.mch.weixin.qq.com/pay/unifiedorder");  
  147.               
  148.             String xml = ClientCustomSSL.CreateNativePackage(nonceStr,orderDescribe,orderNo,price,timeStart,timeExpire);  
  149.             try {  
  150.   
  151.                   
  152.                 StringEntity se = new StringEntity(xml);  
  153.                   
  154.                 httppost.setEntity(se);  
  155.   
  156.                 System.out.println("executing request" + httppost.getRequestLine());  
  157.   
  158.                 CloseableHttpResponse responseEntry = httpclient.execute(httppost);  
  159.                 try {  
  160.                     HttpEntity entity = responseEntry.getEntity();  
  161.   
  162.                     System.out.println("----------------------------------------");  
  163.                     System.out.println(responseEntry.getStatusLine());  
  164.                     if (entity != null) {  
  165.                         System.out.println("Response content length: "  
  166.                                 + entity.getContentLength());  
  167.                 /*  BufferedReader bufferedReader = new BufferedReader( 
  168.                                 new InputStreamReader(entity.getContent())); 
  169.                         String text; 
  170.                         while ((text = bufferedReader.readLine()) != null) { 
  171.                             System.out.println("======="+text); 
  172.                         }*/       
  173.                                                   
  174.                         SAXReader saxReader = new SAXReader();  
  175.                         Document document = saxReader.read(entity.getContent());  
  176.                         Element rootElt = document.getRootElement();  
  177.                         System.out.println("根节点:" + rootElt.getName());  
  178.                         System.out.println("==="+rootElt.elementText("result_code"));  
  179.                         System.out.println("==="+rootElt.elementText("return_msg"));  
  180.                         String resultCode = rootElt.elementText("result_code");  
  181.                         JSONObject result = new JSONObject();                 
  182.                           
  183.                         Document documentXml =DocumentHelper.parseText(xml);  
  184.                         Element rootEltXml = documentXml.getRootElement();  
  185.                           
  186.                         if(resultCode.equals("SUCCESS")){  
  187.                             System.out.println("=================prepay_id===================="+ rootElt.elementText("prepay_id"));  
  188.                             System.out.println("=================sign===================="+ rootEltXml.elementText("sign"));  
  189.                             result.put("weixinPayUrl",  rootElt.elementText("code_url"));  
  190.                             result.put("prepayId",  rootElt.elementText("prepay_id"));  
  191.                             result.put("status","success");  
  192.                             result.put("msg","success");  
  193.                         }else{  
  194.                             result.put("status","false");  
  195.                             result.put("msg",rootElt.elementText("err_code_des"));  
  196.                         }  
  197.                           
  198.                           
  199.                         return result;  
  200.   
  201.                     }  
  202.                     EntityUtils.consume(entity);  
  203.                 }  
  204.                 finally {  
  205.                     responseEntry.close();  
  206.                 }  
  207.             }  
  208.             finally {  
  209.                 httpclient.close();  
  210.             }  
  211.             return null;  
  212.               
  213.               
  214.         }catch(Exception e){  
  215.             e.printStackTrace();  
  216.             JSONObject result = new JSONObject();  
  217.             result.put("status","error");  
  218.             result.put("msg",e.getMessage());  
  219.             return result;  
  220.         }  
  221.     }  
  222.       
  223. }  

httpclient  jar包下载地址:http://download.csdn.net/detail/wangxuewei111/8460181

json jar包现在地址:http://download.csdn.net/detail/wangxuewei111/8460185


一、前期准备

做微信开发首先要申请一个公共账号,申请成功后会以邮件形式发给你一些必要信息,公共账号中有开发文档以及开发中必要信息,以及测试的数据查询。



二、工具类

1.MD5加密工具类

[java]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. package com.pay.utils.weixin;  
  2. import java.security.MessageDigest;  
  3. public class MD5Util {  
  4.     public final static String MD5(String s) {  
  5.         char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};         
  6.         try {  
  7.             byte[] btInput = s.getBytes();  
  8.             // 获得MD5摘要算法的 MessageDigest 对象  
  9.             MessageDigest mdInst = MessageDigest.getInstance("MD5");  
  10.             // 使用指定的字节更新摘要  
  11.             mdInst.update(btInput);  
  12.             // 获得密文  
  13.             byte[] md = mdInst.digest();  
  14.             // 把密文转换成十六进制的字符串形式  
  15.             int j = md.length;  
  16.             char str[] = new char[j * 2];  
  17.             int k = 0;  
  18.             for (int i = 0; i < j; i++) {  
  19.                 byte byte0 = md[i];  
  20.                 str[k++] = hexDigits[byte0 >>> 4 & 0xf];  
  21.                 str[k++] = hexDigits[byte0 & 0xf];  
  22.             }  
  23.             return new String(str);  
  24.         } catch (Exception e) {  
  25.             e.printStackTrace();  
  26.             return null;  
  27.        }  
  28.     }  
  29. }  

2.CommonUtil工具类,用于装换成微信所需XML。以下return new String(xml.toString().getBytes(),"ISO8859-1");将工具类中的utf-8改成iso8859-1,否则微信订单中的中文会出现乱码,改后可以正确显示。

[java]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. package com.pay.utils.weixin;  
  2.   
  3. import java.io.UnsupportedEncodingException;  
  4. import java.net.URLEncoder;  
  5. import java.util.*;  
  6. import java.util.Map.Entry;  
  7.   
  8. public class CommonUtil {  
  9.   
  10.     public static String CreateNoncestr(int length) {  
  11.         String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";  
  12.         String res = "";  
  13.         for (int i = 0; i < length; i++) {  
  14.             Random rd = new Random();  
  15.             res += chars.indexOf(rd.nextInt(chars.length() - 1));  
  16.         }  
  17.         return res;  
  18.     }  
  19.   
  20.     public static String CreateNoncestr() {  
  21.         String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";  
  22.         String res = "";  
  23.         for (int i = 0; i < 16; i++) {  
  24.             Random rd = new Random();  
  25.             res += chars.charAt(rd.nextInt(chars.length() - 1));  
  26.         }  
  27.         return res;  
  28.     }  
  29.   
  30.     public static String FormatQueryParaMap(HashMap<String, String> parameters)  
  31.             throws SDKRuntimeException {  
  32.   
  33.         String buff = "";  
  34.         try {  
  35.             List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(  
  36.                     parameters.entrySet());  
  37.   
  38.             Collections.sort(infoIds,  
  39.                     new Comparator<Map.Entry<String, String>>() {  
  40.                         public int compare(Map.Entry<String, String> o1,  
  41.                                 Map.Entry<String, String> o2) {  
  42.                             return (o1.getKey()).toString().compareTo(  
  43.                                     o2.getKey());  
  44.                         }  
  45.                     });  
  46.   
  47.             for (int i = 0; i < infoIds.size(); i++) {  
  48.                 Map.Entry<String, String> item = infoIds.get(i);  
  49.                 if (item.getKey() != "") {  
  50.                     buff += item.getKey() + "="  
  51.                             + URLEncoder.encode(item.getValue(), "utf-8") + "&";  
  52.                 }  
  53.             }  
  54.             if (buff.isEmpty() == false) {  
  55.                 buff = buff.substring(0, buff.length() - 1);  
  56.             }  
  57.         } catch (Exception e) {  
  58.             throw new SDKRuntimeException(e.getMessage());  
  59.         }  
  60.   
  61.         return buff;  
  62.     }  
  63.   
  64.     public static String FormatBizQueryParaMap(HashMap<String, String> paraMap,  
  65.             boolean urlencode) throws SDKRuntimeException {  
  66.   
  67.         String buff = "";  
  68.         try {  
  69.             List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(  
  70.                     paraMap.entrySet());  
  71.   
  72.             Collections.sort(infoIds,  
  73.                     new Comparator<Map.Entry<String, String>>() {  
  74.                         public int compare(Map.Entry<String, String> o1,  
  75.                                 Map.Entry<String, String> o2) {  
  76.                             return (o1.getKey()).toString().compareTo(  
  77.                                     o2.getKey());  
  78.                         }  
  79.                     });  
  80.   
  81.             for (int i = 0; i < infoIds.size(); i++) {  
  82.                 Map.Entry<String, String> item = infoIds.get(i);  
  83.                 //System.out.println(item.getKey());  
  84.                 if (item.getKey() != "") {  
  85.                       
  86.                     String key = item.getKey();  
  87.                     String val = item.getValue();  
  88.                     if (urlencode) {  
  89.                         val = URLEncoder.encode(val, "utf-8");  
  90.   
  91.                     }  
  92.                     buff += key.toLowerCase() + "=" + val + "&";  
  93.   
  94.                 }  
  95.             }  
  96.   
  97.             if (buff.isEmpty() == false) {  
  98.                 buff = buff.substring(0, buff.length() - 1);  
  99.             }  
  100.         } catch (Exception e) {  
  101.             throw new SDKRuntimeException(e.getMessage());  
  102.         }  
  103.         return buff;  
  104.     }  
  105.   
  106.     public static boolean IsNumeric(String str) {  
  107.         if (str.matches("\\d *")) {  
  108.             return true;  
  109.         } else {  
  110.             return false;  
  111.         }  
  112.     }  
  113.   
  114.     public static String ArrayToXml(HashMap<String, String> arr) {  
  115.         String xml = "<xml>";  
  116.           
  117.         Iterator<Entry<String, String>> iter = arr.entrySet().iterator();  
  118.         while (iter.hasNext()) {  
  119.             Entry<String, String> entry = iter.next();  
  120.             String key = entry.getKey();  
  121.             String val = entry.getValue();  
  122.             if (IsNumeric(val)) {  
  123.                 xml += "<" + key + ">" + val + "</" + key + ">";  
  124.   
  125.             } else  
  126.                 xml += "<" + key + "><![CDATA[" + val + "]]></" + key + ">";  
  127.         }  
  128.   
  129.         xml += "</xml>";  
  130.          try {  
  131.             return new String(xml.toString().getBytes(),"ISO8859-1");  
  132.         } catch (UnsupportedEncodingException e) {  
  133.             // TODO Auto-generated catch block  
  134.             e.printStackTrace();  
  135.         }    
  136.          return "";  
  137.     }  
  138.   
  139. }  


3.ClientCustomSSL工具类,用于生成sign以及创建微信订单
[java]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. package com.pay.utils.weixin;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.Collections;  
  5. import java.util.Comparator;  
  6. import java.util.HashMap;  
  7. import java.util.List;  
  8. import java.util.Map;  
  9.   
  10. import org.springframework.util.StringUtils;  
  11.   
  12.   
  13.   
  14. /** 
  15.  * This example demonstrates how to create secure connections with a custom SSL 
  16.  * context. 
  17.  */  
  18. public class ClientCustomSSL {  
  19.   
  20.      public static String GetBizSign(HashMap<String, String> bizObj)  
  21.             throws SDKRuntimeException {  
  22.         HashMap<String, String> bizParameters = new HashMap<String, String>();  
  23.   
  24.         List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(  
  25.                 bizObj.entrySet());  
  26.         System.out.println(infoIds);  
  27.         Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>() {  
  28.             public int compare(Map.Entry<String, String> o1,  
  29.                     Map.Entry<String, String> o2) {  
  30.                 return (o1.getKey()).toString().compareTo(o2.getKey());  
  31.             }  
  32.         });  
  33. System.out.println("--------------------");  
  34.         System.out.println(infoIds);  
  35.         for (int i = 0; i < infoIds.size(); i++) {  
  36.             Map.Entry<String, String> item = infoIds.get(i);  
  37.             if (item.getKey() != "") {  
  38.                 bizParameters.put(item.getKey().toLowerCase(), item.getValue());  
  39.             }  
  40.         }  
  41.         //bizParameters.put("key", "12345678123456781234567812345671");  
  42.         String bizString = CommonUtil.FormatBizQueryParaMap(bizParameters,  
  43.                 false);  
  44.         bizString += "&key=12345678123456781234567812345671";  
  45.         System.out.println("***************");  
  46.           
  47.         System.out.println(bizString);  
  48.   
  49. //      return SHA1Util.Sha1(bizString);  
  50.         return MD5Util.MD5(bizString);  
  51.   
  52.     }  
  53.     /** 
  54.      * 微信创建订单 
  55.      * @param nonceStr 
  56.      * @param orderDescribe 
  57.      * @param orderNo 
  58.      * @param price 
  59.      * @param timeStart 
  60.      * @param timeExpire 
  61.      * @return 
  62.      * @throws SDKRuntimeException 
  63.      */  
  64.      public static String CreateNativePackage(String nonceStr,String orderDescribe,String orderNo,String price,String timeStart,String timeExpire) throws SDKRuntimeException {  
  65.         HashMap<String, String> nativeObj = new HashMap<String, String>();  
  66.         nativeObj.put("appid""见公众账号");                            //公众账号Id  
  67.         nativeObj.put("mch_id""见邮件");                 //商户号  
  68.         nativeObj.put("nonce_str", nonceStr);                       //随机字符串  
  69.         nativeObj.put("body", orderDescribe);                   //商品描述  
  70.         nativeObj.put("attach""tradeno");                 //附加数据  
  71.         nativeObj.put("out_trade_no", orderNo);                         //商户订单号(全局唯一)  
  72.         nativeObj.put("total_fee", price);                  //总金额(单位为分,不能带小数点)  
  73.         nativeObj.put("spbill_create_ip","192.168.0.144");              //终端Ip  
  74.         nativeObj.put("time_start", timeStart);                         //交易起始时间  
  75.         nativeObj.put("time_expire", timeExpire);                   //交易结束时间  
  76.         nativeObj.put("notify_url", CustomizedPropertyPlaceholderConfigurer.getContextProperty("wxurl")+"/weixin_callback/weixinCallback/init.action");                                                 //回调通知地址  
  77.         nativeObj.put("trade_type""NATIVE");                  //交易类型  
  78.           
  79.         String sign = GetBizSign(nativeObj);  
  80.           
  81.         nativeObj.put("sign", sign.toUpperCase());  
  82.           
  83.         return CommonUtil.ArrayToXml(nativeObj);  
  84.   
  85.     }      
[java]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1.           /** 
  2. * 微信订单支付查询 
  3. * @param nonceStr 
  4. * @param orderDescribe 
  5. * @param orderNo 
  6. * @param price 
  7. * @param timeStart 
  8. * @param timeExpire 
  9. * @return 
  10. * @throws SDKRuntimeException 
  11. */  
  12. public static String SearchNativePackage(String transactionId,String outTradeNo,String nonceStr) throws SDKRuntimeException {  
  13. HashMap<String, String> nativeObj = new HashMap<String, String>();  
  14. nativeObj.put("appid""见公众共账号"); //公众账号Id  
  15. nativeObj.put("mch_id""见邮件");//商户号  
  16. nativeObj.put("nonce_str", nonceStr);//随机字符串  
  17. if(!StringUtils.isEmpty(transactionId)){  
  18. nativeObj.put("transaction_id", transactionId);   
  19. }  
  20. if(!StringUtils.isEmpty(outTradeNo)){  
  21. nativeObj.put("out_trade_no", outTradeNo);//随机字符串  
  22. }  
  23. String sign = GetBizSign(nativeObj);  
  24. nativeObj.put("sign", sign.toUpperCase());    
  25. return CommonUtil.ArrayToXml(nativeObj);  
  26.  /** 
  27. * 微信退款 
  28. * @param outTradeNo 
  29. * @param outRefundNo 
  30.  * @param totalFee 
  31. * @param refundFee 
  32. * @return 
  33. * @throws SDKRuntimeException 
  34. */  
  35. public static String RefundNativePackage(String outTradeNo,String outRefundNo,String totalFee,String refundFee,String nonceStr) throws SDKRuntimeException {  
  36. HashMap<String, String> nativeObj = new HashMap<String, String>();  
  37. nativeObj.put("appid""见公众账号");//公众账号Id  
  38. nativeObj.put("mch_id""见邮件");//商户号  
  39. nativeObj.put("nonce_str", nonceStr);//随机字符串  
  40. nativeObj.put("out_trade_no", outTradeNo);//商户订单号(全局唯一)  
  41. nativeObj.put("out_refund_no", outRefundNo);//商户退款单号(全局唯一)  
  42. nativeObj.put("total_fee", totalFee);//总金额(单位为分,不能带小数点)  
  43. nativeObj.put("refund_fee", refundFee);//退款金额(单位为分,不能带小数点)  
  44. nativeObj.put("op_user_id""邮件");  
  45. String sign = GetBizSign(nativeObj);  
  46. nativeObj.put("sign", sign.toUpperCase());  
  47. return CommonUtil.ArrayToXml(nativeObj);  
  48. }  
  49.   
  50. /** 
  51. * 微信待支付 
  52.  * @param nonceStr 
  53. * @param orderDescribe 
  54. * @param orderNo 
  55. * @param price 
  56. * @param timeStart 
  57. * @param timeExpire 
  58. * @return 
  59. * @throws SDKRuntimeException 
  60. */  
  61. public static String CreateJsApiPackage(String nonceStr,String orderDescribe,String orderNo,String price,String timeStart,String timeExpire,String openId) throws SDKRuntimeException {  
  62. HashMap<String, String> nativeObj = new HashMap<String, String>();  
  63. nativeObj.put("appid""见公众账号");//公众账号Id  
  64. nativeObj.put("openid", openId);//公众账号Id  
  65. nativeObj.put("mch_id""见邮件")//商户号  
  66. nativeObj.put("nonce_str", nonceStr);//随机字符串  
  67. nativeObj.put("body", orderDescribe);//商品描述  
  68. nativeObj.put("attach""tradeno");//附加数据  
  69. nativeObj.put("out_trade_no", orderNo);//商户订单号(全局唯一)  
  70. nativeObj.put("total_fee", price);//总金额(单位为分,不能带小数点)  
  71. nativeObj.put("spbill_create_ip","192.168.0.144");//终端Ip  
  72. nativeObj.put("time_start", timeStart);//交易起始时间  
  73. nativeObj.put("time_expire", timeExpire)//交易结束时间  
  74. nativeObj.put("notify_url",CustomizedPropertyPlaceholderConfigurer.getContextProperty("wxurl")+"/weixin_callback/weixinCallback/init.action");//通知地址  
  75. nativeObj.put("trade_type""JSAPI");//交易类型  
  76. String sign = GetBizSign(nativeObj);  
  77. nativeObj.put("sign", sign.toUpperCase());  
  78. return CommonUtil.ArrayToXml(nativeObj);  
  79. }  
  80. /** 
  81. * 微信关闭订单 
  82. * @param nonceStr 
  83. * @param orderDescribe 
  84. * @param orderNo 
  85. * @param price 
  86. * @param timeStart 
  87. * @param timeExpire 
  88. * @param openId 
  89. * @return 
  90. * @throws SDKRuntimeException 
  91. */  
  92. public static String CreateCloseOrder(String outTradeNo,String nonceStr) throws SDKRuntimeException {  
  93. HashMap<String, String> nativeObj = new HashMap<String, String>();  
  94. nativeObj.put("appid""见公众账号");//公众账号Id  
  95. nativeObj.put("mch_id""见邮件");//商户号  
  96. nativeObj.put("out_trade_no", outTradeNo);//商户订单号(全局唯一)  
  97. nativeObj.put("nonce_str", nonceStr);//随机字符串  
  98.  String sign = GetBizSign(nativeObj);  
  99. nativeObj.put("sign", sign.toUpperCase());  
  100.  return CommonUtil.ArrayToXml(nativeObj);  
  101. }  
  102. }  

4.调用微信支付接口

[java]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. package com.pay.controller.weixin;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.security.KeyStore;  
  6. import java.text.SimpleDateFormat;  
  7. import java.util.Date;  
  8. import java.util.List;  
  9.   
  10. import javax.net.ssl.SSLContext;  
  11. import javax.servlet.http.HttpServletRequest;  
  12. import javax.servlet.http.HttpServletResponse;  
  13.   
  14. import net.sf.json.JSONArray;  
  15. import net.sf.json.JSONObject;  
  16.   
  17. import org.apache.http.HttpEntity;  
  18. import org.apache.http.client.methods.CloseableHttpResponse;  
  19. import org.apache.http.client.methods.HttpPost;  
  20. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;  
  21. import org.apache.http.conn.ssl.SSLContexts;  
  22. import org.apache.http.entity.StringEntity;  
  23. import org.apache.http.impl.client.CloseableHttpClient;  
  24. import org.apache.http.impl.client.HttpClients;  
  25. import org.apache.http.util.EntityUtils;  
  26. import org.dom4j.Document;  
  27. import org.dom4j.DocumentHelper;  
  28. import org.dom4j.Element;  
  29. import org.dom4j.io.SAXReader;  
  30. import org.springframework.beans.factory.annotation.Autowired;  
  31. import org.springframework.http.HttpStatus;  
  32. import org.springframework.web.bind.annotation.RequestBody;  
  33. import org.springframework.web.bind.annotation.RequestMapping;  
  34. import org.springframework.web.bind.annotation.RequestMethod;  
  35. import org.springframework.web.bind.annotation.ResponseStatus;  
  36. import org.springframework.web.bind.annotation.RestController;  
  37.   
  38. import com.pay.bo.PayHist;  
  39. import com.pay.constants.PayHistoryPayStatus;  
  40. import com.pay.constants.PayHistoryPayType;  
  41. import com.pay.service.WeiXinPayService;  
  42. import com.pay.utils.weixin.ClientCustomSSL;  
  43. import com.pay.utils.weixin.CloseWeiXinOrderUtils;  
  44. import com.pay.utils.weixin.CustomizedPropertyPlaceholderConfigurer;  
  45.   
  46.   
  47. @RestController  
  48. @RequestMapping("/Pay")  
  49. public class WeiXinPayController {  
  50.       
  51.       
  52.     @Autowired  
  53.     WeiXinPayService weiXinPayService;  
  54.     private static long standardTime = 1662652800000L;  
  55.       
  56.     /** 
  57.      * 返回生成二维码的url 
  58.      * @param request 
  59.      * @param response 
  60.      * @return 
  61.      */  
  62.     @RequestMapping(value="/getUrl",method=RequestMethod.POST)  
  63.     @ResponseStatus(HttpStatus.OK)  
  64.     public Object getUrl(HttpServletResponse response,@RequestBody String body){  
  65.         try{  
  66.             JSONObject jsonO = JSONObject.fromObject(body);  
  67.             PayHist ph = null;  
  68. //          List<Map<String,Object>> td = weiXinPayService.getTrade(orderNo);  
  69.             Date dt = new Date();  
  70.             SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");  
  71.             String nonceStr = sdf.format(dt).toString();  
  72.             Date now = new Date();  
  73.               
  74.             String tradePayNo = jsonO.get("orderNo").toString()+String.format("%10d",standardTime - now.getTime()).substring(010);  
  75.             System.out.println("订单标号orderNo======="+jsonO.get("orderNo").toString());  
  76.             System.out.println("10位随机数======="+String.format("%10d",standardTime - now.getTime()).substring(010));  
  77.             String price = Math.round(Float.valueOf(jsonO.get("price").toString())*100)+"";  
  78.             Long timeExpireStrOld = dt.getTime();  
  79.             Long timeNew = Long.parseLong(CustomizedPropertyPlaceholderConfigurer.getContextProperty("weixin.send2finish.overtime").toString());  
  80.             Long timeExpireNew = timeExpireStrOld+timeNew;  
  81.             Date dtTimeExpire = new Date(timeExpireNew);  
  82.             SimpleDateFormat dtSdf = new SimpleDateFormat("yyyyMMddHHmmss");  
  83.             String timeExpire = dtSdf.format(dtTimeExpire).toString();  
  84.             System.out.println("nonceStr=="+nonceStr);  
  85.             System.out.println("orderNo=="+jsonO.get("orderNo").toString());  
  86.             System.out.println("price=="+price);  
  87.             System.out.println("timeStart=="+nonceStr);  
  88.             System.out.println("timeExpire=="+timeExpire);  
  89.               
  90.               
  91.             JSONObject result = (JSONObject) setUrl(nonceStr,"订单",tradePayNo,price,nonceStr,timeExpire);  
  92.               
  93.             if(result.get("status").toString().equals("success")){  
  94.                 ph = new PayHist();  
  95.                 ph.setTradePayUrl(result.getString("weixinPayUrl"));//此字段为支付链接,可以此链接生成二维码扫码支付  
  96.                 ph.setPayTradeNo(jsonO.get("orderNo").toString());  
  97.                 ph.setTradePayNo(tradePayNo);  
  98.                 ph.setPayStatus(PayHistoryPayStatus.WECHAT_PAY_STATUS_WAIT);  
  99.                 ph.setPayType(PayHistoryPayType.WECHAT);  
  100.                 ph.setAppKey(jsonO.getString("appKey").toString());  
  101.                 ph.setPayAmount(price);  
  102.                   
  103.                 result.put("payTradeNo", ph.getPayTradeNo());  
  104.                 result.put("tradePayNo", ph.getTradePayNo());  
  105.                 result.put("payStatus", ph.getPayStatus());  
  106.                 result.put("payType", ph.getPayType());  
  107.                   
  108.             }             
  109.             return result;  
  110.               
  111.               
  112.         }catch(Exception e){  
  113.             e.printStackTrace();  
  114.             JSONObject result = new JSONObject();  
  115.             result.put("status","error");  
  116.             result.put("msg",e.getMessage());  
  117. //          return result.toString();  
  118.         }  
  119.         return null;  
  120.       
  121.           
  122.     }  
  123.   
  124.     public Object setUrl(String nonceStr,String orderDescribe,String orderNo,String price,String timeStart,String timeExpire) {  
  125.         try{  
  126.               
  127.             KeyStore keyStore = KeyStore.getInstance("PKCS12");  
  128.             FileInputStream instream = new FileInputStream(new File(微信证书绝对路径));  
  129.             try {  
  130.                 keyStore.load(instream, "商户ID".toCharArray());  
  131.             }finally {  
  132.                 instream.close();  
  133.             }  
  134.   
  135.             // Trust own CA and all self-signed certs  
  136.             SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore,<span style="font-family: Arial, Helvetica, sans-serif;">商户ID</span>.toCharArray()).build();  
  137.             // Allow TLSv1 protocol only  
  138.             SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(  
  139.                     sslcontext, new String[] { "TLSv1" }, null,  
  140.                     SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);  
  141.             CloseableHttpClient httpclient = HttpClients.custom()  
  142.                     .setSSLSocketFactory(sslsf).build();  
  143.             // HttpGet httpget = new  
  144.             // HttpGet("https://api.mch.weixin.qq.com/secapi/pay/refund");  
  145.             HttpPost httppost = new HttpPost(  
  146.                     "https://api.mch.weixin.qq.com/pay/unifiedorder");  
  147.               
  148.             String xml = ClientCustomSSL.CreateNativePackage(nonceStr,orderDescribe,orderNo,price,timeStart,timeExpire);  
  149.             try {  
  150.   
  151.                   
  152.                 StringEntity se = new StringEntity(xml);  
  153.                   
  154.                 httppost.setEntity(se);  
  155.   
  156.                 System.out.println("executing request" + httppost.getRequestLine());  
  157.   
  158.                 CloseableHttpResponse responseEntry = httpclient.execute(httppost);  
  159.                 try {  
  160.                     HttpEntity entity = responseEntry.getEntity();  
  161.   
  162.                     System.out.println("----------------------------------------");  
  163.                     System.out.println(responseEntry.getStatusLine());  
  164.                     if (entity != null) {  
  165.                         System.out.println("Response content length: "  
  166.                                 + entity.getContentLength());  
  167.                 /*  BufferedReader bufferedReader = new BufferedReader( 
  168.                                 new InputStreamReader(entity.getContent())); 
  169.                         String text; 
  170.                         while ((text = bufferedReader.readLine()) != null) { 
  171.                             System.out.println("======="+text); 
  172.                         }*/       
  173.                                                   
  174.                         SAXReader saxReader = new SAXReader();  
  175.                         Document document = saxReader.read(entity.getContent());  
  176.                         Element rootElt = document.getRootElement();  
  177.                         System.out.println("根节点:" + rootElt.getName());  
  178.                         System.out.println("==="+rootElt.elementText("result_code"));  
  179.                         System.out.println("==="+rootElt.elementText("return_msg"));  
  180.                         String resultCode = rootElt.elementText("result_code");  
  181.                         JSONObject result = new JSONObject();                 
  182.                           
  183.                         Document documentXml =DocumentHelper.parseText(xml);  
  184.                         Element rootEltXml = documentXml.getRootElement();  
  185.                           
  186.                         if(resultCode.equals("SUCCESS")){  
  187.                             System.out.println("=================prepay_id===================="+ rootElt.elementText("prepay_id"));  
  188.                             System.out.println("=================sign===================="+ rootEltXml.elementText("sign"));  
  189.                             result.put("weixinPayUrl",  rootElt.elementText("code_url"));  
  190.                             result.put("prepayId",  rootElt.elementText("prepay_id"));  
  191.                             result.put("status","success");  
  192.                             result.put("msg","success");  
  193.                         }else{  
  194.                             result.put("status","false");  
  195.                             result.put("msg",rootElt.elementText("err_code_des"));  
  196.                         }  
  197.                           
  198.                           
  199.                         return result;  
  200.   
  201.                     }  
  202.                     EntityUtils.consume(entity);  
  203.                 }  
  204.                 finally {  
  205.                     responseEntry.close();  
  206.                 }  
  207.             }  
  208.             finally {  
  209.                 httpclient.close();  
  210.             }  
  211.             return null;  
  212.               
  213.               
  214.         }catch(Exception e){  
  215.             e.printStackTrace();  
  216.             JSONObject result = new JSONObject();  
  217.             result.put("status","error");  
  218.             result.put("msg",e.getMessage());  
  219.             return result;  
  220.         }  
  221.     }  
  222.       
  223. }  

httpclient  jar包下载地址:http://download.csdn.net/detail/wangxuewei111/8460181

json jar包现在地址:http://download.csdn.net/detail/wangxuewei111/8460185


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值