Java使用微信支付

  1. package com.tenpay.util;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.ByteArrayInputStream;  
  5. import java.io.File;  
  6. import java.io.FileInputStream;  
  7. import java.io.InputStream;  
  8. import java.io.InputStreamReader;  
  9. import java.io.OutputStream;  
  10. import java.net.ConnectException;  
  11. import java.net.HttpURLConnection;  
  12. import java.net.InetAddress;  
  13. import java.net.URL;  
  14. import java.security.KeyStore;  
  15. import java.util.Date;  
  16. import java.util.HashMap;  
  17. import java.util.Iterator;  
  18. import java.util.List;  
  19. import java.util.Map;  
  20.   
  21. import javax.net.ssl.SSLContext;  
  22.   
  23. import org.apache.http.Consts;  
  24. import org.apache.http.HttpEntity;  
  25. import org.apache.http.client.methods.CloseableHttpResponse;  
  26. import org.apache.http.client.methods.HttpPost;  
  27. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;  
  28. import org.apache.http.conn.ssl.SSLContexts;  
  29. import org.apache.http.entity.StringEntity;  
  30. import org.apache.http.impl.client.CloseableHttpClient;  
  31. import org.apache.http.impl.client.HttpClients;  
  32. import org.apache.http.util.EntityUtils;  
  33. import org.glassfish.jersey.internal.util.Base64;  
  34. import org.jdom.Document;  
  35. import org.jdom.Element;  
  36. import org.jdom.input.SAXBuilder;  
  37.   
  38. import com.zhiweism.util.MD5;  
  39. import com.zhiweism.util.Util;  
  40.   
  41. /* 
  42.  * 用户发起统一下单请求 
  43.  * 作者:董志平 
  44.  */  
  45. public class WXRequestUtil {  
  46.       
  47.     public static void main(String[] args) {  
  48.         SendPayment("苹果","20170106113324",1,"1");  
  49.     }  
  50.       
  51.     /* 
  52.      * 发起支付请求 
  53.      * body 商品描述 
  54.      * out_trade_no 订单号 
  55.      * total_fee    订单金额        单位  元 
  56.      * product_id   商品ID 
  57.      */  
  58.     public static Map<String,String> SendPayment(String body,String out_trade_no,double total_fee,String product_id){  
  59.         String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";  
  60.         String xml = WXParamGenerate(body,out_trade_no,total_fee,product_id);  
  61.         String res = httpsRequest(url,"POST",xml);  
  62.           
  63.         Map<String,String> data = null;  
  64.         try {  
  65.             data = doXMLParse(res);  
  66.         } catch (Exception e) {  
  67.         }  
  68.         return data;  
  69.     }  
  70.       
  71.     public static String NonceStr(){  
  72.         String res = Base64.encodeAsString(Math.random()+"::"+new Date().toString()).substring(030);  
  73.         return res;  
  74.     }  
  75.       
  76.      public static String GetIp() {  
  77.         InetAddress ia=null;  
  78.         try {  
  79.             ia=InetAddress.getLocalHost();  
  80.             String localip=ia.getHostAddress();  
  81.             return localip;  
  82.         } catch (Exception e) {  
  83.             return null;  
  84.         }  
  85.     }  
  86.        
  87.      public static String GetSign(Map<String,String> param){  
  88.         String StringA =  Util.formatUrlMap(param, falsefalse);  
  89.         String stringSignTemp = MD5.md5(StringA+"&key="+ConstantUtil.API_KEY).toUpperCase();  
  90.         return stringSignTemp;  
  91.      }  
  92.        
  93.      //Map转xml数据  
  94.      public static String GetMapToXML(Map<String,String> param){  
  95.          StringBuffer sb = new StringBuffer();  
  96.          sb.append("<xml>");  
  97.          for (Map.Entry<String,String> entry : param.entrySet()) {   
  98.                 sb.append("<"+ entry.getKey() +">");  
  99.                 sb.append(entry.getValue());  
  100.                 sb.append("</"+ entry.getKey() +">");  
  101.         }    
  102.          sb.append("</xml>");  
  103.          return sb.toString();  
  104.      }  
  105.       
  106.       
  107.     //微信统一下单参数设置  
  108.     public static String WXParamGenerate(String description,String out_trade_no,double total_fee,String product_id){  
  109.         int fee = (int)(total_fee * 100.00);  
  110.         Map<String,String> param = new HashMap<String,String>();  
  111.         param.put("appid", ConstantUtil.APP_ID);  
  112.         param.put("mch_id", ConstantUtil.MCH_ID);  
  113.         param.put("nonce_str",NonceStr());  
  114.         param.put("body", description);  
  115.         param.put("out_trade_no",out_trade_no);  
  116.         param.put("total_fee", fee+"");  
  117.         param.put("spbill_create_ip", GetIp());  
  118.         param.put("notify_url", ConstantUtil.WEIXIN_NOTIFY);  
  119.         param.put("trade_type""NATIVE");  
  120.         param.put("product_id", product_id+"");  
  121.           
  122.         String sign = GetSign(param);  
  123.           
  124.         param.put("sign", sign);  
  125.         return GetMapToXML(param);  
  126.     }  
  127.       
  128.     //发起微信支付请求  
  129.     public static String httpsRequest(String requestUrl, String requestMethod, String outputStr) {    
  130.       try {    
  131.           URL url = new URL(requestUrl);    
  132.           HttpURLConnection conn = (HttpURLConnection) url.openConnection();    
  133.             
  134.           conn.setDoOutput(true);    
  135.           conn.setDoInput(true);    
  136.           conn.setUseCaches(false);    
  137.           // 设置请求方式(GET/POST)    
  138.           conn.setRequestMethod(requestMethod);    
  139.           conn.setRequestProperty("content-type""application/x-www-form-urlencoded");    
  140.           // 当outputStr不为null时向输出流写数据    
  141.           if (null != outputStr) {    
  142.               OutputStream outputStream = conn.getOutputStream();    
  143.               // 注意编码格式    
  144.               outputStream.write(outputStr.getBytes("UTF-8"));    
  145.               outputStream.close();    
  146.           }    
  147.           // 从输入流读取返回内容    
  148.           InputStream inputStream = conn.getInputStream();    
  149.           InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");    
  150.           BufferedReader bufferedReader = new BufferedReader(inputStreamReader);    
  151.           String str = null;  
  152.           StringBuffer buffer = new StringBuffer();    
  153.           while ((str = bufferedReader.readLine()) != null) {    
  154.               buffer.append(str);    
  155.           }    
  156.           // 释放资源    
  157.           bufferedReader.close();    
  158.           inputStreamReader.close();    
  159.           inputStream.close();    
  160.           inputStream = null;    
  161.           conn.disconnect();    
  162.           return buffer.toString();    
  163.       } catch (ConnectException ce) {    
  164.           System.out.println("连接超时:{}"+ ce);    
  165.       } catch (Exception e) {    
  166.           System.out.println("https请求异常:{}"+ e);    
  167.       }    
  168.       return null;    
  169.     }    
  170.         
  171.     //退款的请求方法    
  172.     public static String httpsRequest2(String requestUrl, String requestMethod, String outputStr) throws Exception {    
  173.           KeyStore keyStore  = KeyStore.getInstance("PKCS12");    
  174.           StringBuilder res = new StringBuilder("");    
  175.           FileInputStream instream = new FileInputStream(new File("/home/apiclient_cert.p12"));    
  176.           try {    
  177.               keyStore.load(instream, "".toCharArray());    
  178.           } finally {    
  179.               instream.close();    
  180.           }    
  181.   
  182.           // Trust own CA and all self-signed certs    
  183.           SSLContext sslcontext = SSLContexts.custom()    
  184.                   .loadKeyMaterial(keyStore, "1313329201".toCharArray())    
  185.                   .build();    
  186.           // Allow TLSv1 protocol only    
  187.           SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(    
  188.                   sslcontext,    
  189.                   new String[] { "TLSv1" },    
  190.                   null,    
  191.                   SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);    
  192.           CloseableHttpClient httpclient = HttpClients.custom()    
  193.                   .setSSLSocketFactory(sslsf)    
  194.                   .build();    
  195.           try {    
  196.   
  197.               HttpPost httpost = new HttpPost("https://api.mch.weixin.qq.com/secapi/pay/refund");    
  198.               httpost.addHeader("Connection""keep-alive");    
  199.               httpost.addHeader("Accept""*/*");    
  200.               httpost.addHeader("Content-Type""application/x-www-form-urlencoded; charset=UTF-8");    
  201.               httpost.addHeader("Host""api.mch.weixin.qq.com");    
  202.               httpost.addHeader("X-Requested-With""XMLHttpRequest");    
  203.               httpost.addHeader("Cache-Control""max-age=0");    
  204.               httpost.addHeader("User-Agent""Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");    
  205.                StringEntity entity2 = new StringEntity(outputStr ,Consts.UTF_8);    
  206.                httpost.setEntity(entity2);    
  207.               System.out.println("executing request" + httpost.getRequestLine());    
  208.   
  209.               CloseableHttpResponse response = httpclient.execute(httpost);    
  210.                  
  211.               try {    
  212.                   HttpEntity entity = response.getEntity();    
  213.                       
  214.                   System.out.println("----------------------------------------");    
  215.                   System.out.println(response.getStatusLine());    
  216.                   if (entity != null) {    
  217.                       System.out.println("Response content length: " + entity.getContentLength());    
  218.                       BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));    
  219.                       String text = "";  
  220.                       res.append(text);    
  221.                       while ((text = bufferedReader.readLine()) != null) {    
  222.                           res.append(text);    
  223.                           System.out.println(text);    
  224.                       }    
  225.                          
  226.                   }    
  227.                   EntityUtils.consume(entity);    
  228.               } finally {    
  229.                   response.close();    
  230.               }    
  231.           } finally {    
  232.               httpclient.close();    
  233.           }    
  234.           return  res.toString();    
  235.               
  236.     }  
  237.         
  238.     //xml解析    
  239.     public static Map<String, String> doXMLParse(String strxml) throws Exception {    
  240.           strxml = strxml.replaceFirst("encoding=\".*\"""encoding=\"UTF-8\"");    
  241.           if(null == strxml || "".equals(strxml)) {    
  242.               return null;    
  243.           }    
  244.               
  245.           Map<String,String> m = new HashMap<String,String>();     
  246.           InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));    
  247.           SAXBuilder builder = new SAXBuilder();    
  248.           Document doc = builder.build(in);    
  249.           Element root = doc.getRootElement();    
  250.           List list = root.getChildren();    
  251.           Iterator it = list.iterator();    
  252.           while(it.hasNext()) {    
  253.               Element e = (Element) it.next();    
  254.               String k = e.getName();    
  255.               String v = "";    
  256.               List children = e.getChildren();    
  257.               if(children.isEmpty()) {    
  258.                   v = e.getTextNormalize();    
  259.               } else {    
  260.                   v = getChildrenText(children);    
  261.               }    
  262.                   
  263.               m.put(k, v);    
  264.           }    
  265.               
  266.           //关闭流    
  267.           in.close();     
  268.           return m;    
  269.     }    
  270.         
  271.     public static String getChildrenText(List children) {    
  272.           StringBuffer sb = new StringBuffer();    
  273.           if(!children.isEmpty()) {    
  274.               Iterator it = children.iterator();    
  275.               while(it.hasNext()) {    
  276.                   Element e = (Element) it.next();    
  277.                   String name = e.getName();    
  278.                   String value = e.getTextNormalize();    
  279.                   List list = e.getChildren();    
  280.                   sb.append("<" + name + ">");    
  281.                   if(!list.isEmpty()) {    
  282.                       sb.append(getChildrenText(list));    
  283.                   }    
  284.                   sb.append(value);    
  285.                   sb.append("</" + name + ">");    
  286.               }    
  287.           }     
  288.           return sb.toString();    
  289.     }  
  290. }

转载地址:http://blog.csdn.net/dong_18383219470/article/details/54340586

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值