微信支付java后台

最近要做支付接口,主要是为APP和H5提供接口,我直接写代码:

配置文件:WeixinPay 

package com.shopping.pay.weixin;

import com.shopping.app.config.URL;
import com.shopping.foundation.domain.OrderPackage;
import com.shopping.pay.weixin.util.MD5Util;
import com.shopping.view.web.tools.HttpUitl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;

/**
 * 微信支付的配置文件
 */
public class WeixinPay {

    private static Logger LOG = LoggerFactory.getLogger(WeixinPay.class);

    //公众账号ID
    public static final String APPID = "wxa1261e22bf0e9094";
    //商户号
    public static final String MCH_ID = "1490693182";
    public static String unifiedorder_url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
    public static String trade_type = "APP";
    public static String notify_url_order = URL.url + "/json/wxpay/inform.htm";
    public static String notify_url_tryorder = URL.url + "/json/payWeixin_Tryout_callback.htm";
    public static String notify_url_LessonTrailer = URL.url + "/json/payWeixin_LessonTrailer_callback.htm";
    public static String notify_url_order_h5 = URL.url + "/json/wxpay/informH5.htm";
    public static String notify_url_contribute = URL.url + "/json/contribute/weixinback.htm";
    public static String notify_url_lesson = URL.url + "/json/lesson/weixinback.htm";
    public static String notify_url_EnlistOrder = URL.url + "/json/pay_enlist_callBack.htm";
    public static String notify_url_RecuitOrder = URL.url + "/json/pay_recuitOrder_callBack.htm";
    public static String notify_url_CourseInfoOrder = URL.url + "/json/pay_courseInfo_callBack.htm";
    public static String notify_url_AuditOrder = URL.url + "/notify/pay_auditOrder_callBack.htm";
    public static String notify_url_Libsheet = URL.url + "/json/pay_libsheetOrder_callBack.htm";
    public static String notify_url_CreditOrder = URL.url + "/json/pay_creditOrder_callBack.htm";
    public static String aliyun_notify_url_CreditOrder = URL.url + "/json/pay_aliyun_creditOrder_callBack.htm";

    public static String notify_url_LiveMoney = URL.url + "/json/pay_LiveMoney_callBack.htm";
    public static String aliyun_notify_url_LiveMoney = URL.url + "/json/pay_aliyun_LiveMoney_callBack.htm";

    public static String notify_url_son_order = URL.url + "/json/wxpay/son_inform.htm";
    public static String notify_url_fenda_order = URL.url + "/json/wxpay/fenDaBack.htm";
    public static String notify_url_hs_order = URL.url + "/json/payHealthService_callBack.htm";
    public static String notify_url_vct_order = URL.url + "/json/payVideoCourseTopic_callBack.htm";
    public static String notify_url_lightService_video_order = URL.url + "/json/payLightService_video_callBack.htm";

    public static String notify_url_am_order = URL.url + "/json/payApplyMavin_callBack.htm";

    public static String notify_url_lightService_goods_order = URL.url + "/json/lightService_goods_callback.htm";
    public static String notify_url_mavinEnter_order = URL.url + "/json/wx_mavinEnter_callBack.htm";
    public static String notify_url_lightService0_goods_order = URL.url + "/callback/wx_notify_lightService0_goods_callBack.htm";



    public static String query_order = "https://api.mch.weixin.qq.com/pay/orderquery";

    public static String declare_order ="https://api.mch.weixin.qq.com/cgi-bin/mch/customs/customdeclareorder";



    public static String refund ="https://api.mch.weixin.qq.com/secapi/pay/refund";
    //API密钥
    public static String api_sec = "010z6uBeZIFPS2sDXuKZ55ZbGHd72t0W";

    //公众账号ID
    public static final String APPID_H5 = "wxdba8522d8b**71**";
    //商户号
    public static final String MCH_ID_H5 = "149139****";

    //API密钥
    public static String api_sec_H5 = "67076c903947312fddf06f8b00b5f065";

    public static String key ="****2015****2015********";

    //public static String api_sec_H5 = "wx96cc19ffa7799eb0";
            //d5b7eac0fc6f2827f5cf3ab37b47dd81

    public static String generateSign(LinkedHashMap<String, Object> params){
        StringBuffer str = new StringBuffer();
        String result = "";
        if(params != null && params.size() > 0){
            for(Map.Entry<String, Object> entry : params.entrySet()){
                if(entry != null){
                    str.append(entry.getKey()).
                            append("=").
                            append(entry.getValue());
                }
            }
            String s = str.toString();
            LOG.info(s);
            result = MD5Util.MD5Encode(s,"UTF-8");
        }
        return result;
    }

    public static String declareOrder(OrderPackage orderPackage){
        LinkedHashMap<String, Object> params = new LinkedHashMap<String, Object>();
        params.put("appid", WeixinPay.APPID);
        params.put("&customs", "HANGZHOU");
        params.put("&mch_customs_no", "352471121");
        params.put("&mch_id", WeixinPay.MCH_ID);
        params.put("&out_trade_no", orderPackage.getYun_order_no());
        params.put("&transaction_id",orderPackage.getOut_order_no());

        //生成签名
        String sign = WeixinPay.generateSign(params);
        //组装查询订单接口需要的xml文件
        StringBuilder sb = new StringBuilder();
        sb.append("<xml>");
        sb.append("<appid>"+WeixinPay.APPID+"</appid>");
        sb.append("<customs>HANGZHOU</customs>");
        sb.append("<mch_customs_no>352471121</mch_customs_no>");
        sb.append("<mch_id>"+ WeixinPay.MCH_ID +"</mch_id>");
        sb.append("<out_trade_no>"+ orderPackage.getYun_order_no() +"</out_trade_no>");
        sb.append("<transaction_id>" + orderPackage.getOut_order_no() + "</transaction_id>");
        sb.append("<sign>" + sign + "</sign>");
        sb.append("</xml>");

        //调用微信的查询订单接口
        String result = HttpUitl.postXML(WeixinPay.declare_order, sb.toString());

        System.out.println("微信报关接口=="+result);
        return "";
    }

    /*public String wxPay(String body,) throws NoSuchAlgorithmException, UnsupportedEncodingException, DocumentException {
        String nonce_str = WebUtil.genNonceStr();
        String string1 = "appid=" +WeixinPay.APPID_H5 +
                "&body="+body+
                "&mch_id=" + WeixinPay.MCH_ID_H5 +
                "&nonce_str=" + nonce_str +
                "&notify_url=" +notify_url_order_h5+
                "&openid="+request.getParameter("openid")+
                "&out_trade_no="+orderNo+
                "&spbill_create_ip=123.57.151.22"+
                "&total_fee="+request.getParameter("total_price")+
                "&trade_type=JSAPI"+
                "&key="+wxAppid.getKey();
        System.out.println(string1);
        string1=new String(string1.getBytes(),"UTF-8");
        MessageDigest crypt = MessageDigest.getInstance("MD5");
        crypt.reset();
        crypt.update(string1.getBytes());
        String  signature = Sign.byteToHex(crypt.digest()).toUpperCase();
        System.out.println("统一支付接口签名:"+signature);
        StringBuilder sb = new StringBuilder();
        sb.append("<xml>");
        sb.append("<appid>"+wxAppid.getAppid()+"</appid>");
        sb.append("<body>"+request.getParameter("body") +"</body>");
        sb.append("<mch_id>"+wxAppid.getMchid()+"</mch_id>");
        sb.append("<nonce_str>"+ nonce_str+"</nonce_str>");
        sb.append("<notify_url>http://hk.zdmeng.com/zxzh/w/wxNotify.do</notify_url>");
        sb.append("<openid>"+ request.getParameter("openid")+"</openid>");
        sb.append("<out_trade_no>"+ orderNo +"</out_trade_no>");
        sb.append("<spbill_create_ip>123.57.228.82</spbill_create_ip>");
        sb.append("<total_fee>"+ request.getParameter("total_price")+"</total_fee>");
        sb.append("<trade_type>JSAPI</trade_type>");
        sb.append("<sign>" + signature + "</sign>");
        sb.append("</xml>");
        String str = sb.toString();
        str=new String(str.getBytes(),"utf-8");
        String msg = HttpClient.postXML(WX.pay_url, str);

        //System.out.println("222---"+StringUtil.testcode(msg));
        msg = new String(msg.getBytes("GBK"),"UTF-8");

        Document doc = DocumentHelper.parseText(msg);
        Element root =doc.getRootElement();
        Iterator iterator = root.elementIterator();


        String return_code="";
        String result_code="";
        String prepay_id="";
        String return_msg="";
        while(iterator.hasNext()){
            Element element= (Element) iterator.next();
            if(element.getName().equals("prepay_id")){
                prepay_id=element.getText();
            }

            if(element.getName().equals("return_code")){
                return_code=element.getText();
            }

            if(element.getName().equals("result_code")){
                result_code=element.getText();
            }

            if(element.getName().equals("return_msg")){
                return_msg=element.getText();
            }
        }
        map.put("return_code",return_code);
        map.put("return_msg",return_msg);
        if(return_code.equals("SUCCESS") && result_code.equals("SUCCESS")){
            map.put("prepay_id", prepay_id);
            String last = "appId="+wxAppid.getAppid()+
                    "&nonceStr="+nonce_str+
                    "&package=prepay_id="+prepay_id+
                    "&signType=MD5"+
                    "&timeStamp="+request.getParameter("timestamp")+
                    "&key="+wxAppid.getKey();

            MessageDigest crypt1 = MessageDigest.getInstance("MD5");
            crypt1.reset();
            crypt1.update(last.getBytes("UTF-8"));
            String  signature1 = Sign.byteToHex(crypt1.digest()).toUpperCase();
            System.out.println("jsapi签名:" + signature1);
            map.put("sign", signature1);
            map.put("nonce_str",nonce_str);
            map.put("orderNo", orderform.getOrderNo());
        }
        try {
            response.getWriter().print(JSONObject.fromObject(map));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
*/
}

 工具类:HttpUitl 

package com.shopping.view.web.tools;

import net.sf.json.JSONObject;
import org.apache.commons.httpclient.HttpURL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.*;

/**
 * 请求工具类
 */
public class HttpUitl {

    private static Logger LOG = LoggerFactory.getLogger(HttpURL.class);
    private static int CONNECTTIMEOUT =  5000;
    private static int READTIME = 10000;

    /**
     * Http请求发送
     * @param urlStr 请求的URL地址
     * @param reqMethod 请求方式,GET、POST
     * @return 返回信息,Json对象格式
     */
    public static JSONObject sendHttpRequest(String urlStr, String reqMethod){
        JSONObject root = null;
        try {
            URL url = new URL(urlStr);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod(reqMethod);
            connection.setConnectTimeout(CONNECTTIMEOUT);
            connection.setReadTimeout(READTIME);
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
            LOG.info("send httpRequest to url server...");
            String temp = "";
            StringBuffer stringBuffer = new StringBuffer();
            while((temp = reader.readLine()) != null){
                stringBuffer.append(temp);
            }
            String result = stringBuffer.toString();
            LOG.info("httpServer's response : " + result);
            root = JSONObject.fromObject(result);
            reader.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return root;
    }


    /**
     * Http请求发送
     * @param urlStr 请求的URL地址
     * @param reqMethod 请求方式,GET、POST
     * @return 返回信息,Json对象格式
     */
    public static JSONObject sendHttpRequest1(String urlStr, String reqMethod){
        JSONObject root = null;
        try {
            URL url = new URL(urlStr);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod(reqMethod);
            connection.setConnectTimeout(CONNECTTIMEOUT);
            connection.setReadTimeout(READTIME);
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
            LOG.info("send httpRequest to url server...");
            String temp = "";
            StringBuffer stringBuffer = new StringBuffer();
            while((temp = reader.readLine()) != null){
                stringBuffer.append(temp);
            }
            String result = stringBuffer.toString();
            System.out.println(result);
            reader.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return root;
    }

    /**
     * 向服务器发送xml
     * @param urlStr 服务器url地址
     * @param xmlInfo xml字符串文件
     * @return
     */
    public static String postXML(String urlStr,String xmlInfo) {
        String line = "";
        try {
            URL url = new URL(urlStr);
            URLConnection con = url.openConnection();
            con.setDoOutput(true);
            con.setRequestProperty("Pragma:", "no-cache");
            con.setRequestProperty("Cache-Control", "no-cache");
            con.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
            OutputStreamWriter out = new OutputStreamWriter(con
                    .getOutputStream(),"UTF-8");
            LOG.info("xmlInfo=" + xmlInfo);
            out.write(xmlInfo);
            out.flush();
            out.close();
            BufferedReader br = new BufferedReader(new InputStreamReader(con
                    .getInputStream()));

            for (String str = br.readLine(); str != null; str = br.readLine()) {
                line=line+str;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return line;

    }

//    public static void main(String[] args) {
////        HttpUitl.sendHttpRequest("http://upload.qiniu.com/");
//         HttpUitl.sendHttpRequest1("http://www.boohee.com/shiwu/jingmizhou","GET");
//    }
}

 web工具类:WebUtil 

package com.shopping.view.web.tools;

import com.shopping.pay.weixin.util.MD5Util;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.xml.sax.SAXException;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 工具类
 */
public class WebUtil {


    private final static char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
            '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
            'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y',
            'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
            'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y',
            'Z' };

    /**
     * 用户初始化密码默认长度
     */
    private static final int PWD_LENGTH = 6;

    private static int CONNECTTIMEOUT =  5000;
    private static int READTIME = 10000;


   /* public static DocumentBuilder newDocumentBuilder() throws ParserConfigurationException {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        documentBuilderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
        documentBuilderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
        documentBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        documentBuilderFactory.setXIncludeAware(false);
        documentBuilderFactory.setExpandEntityReferences(false);
        return documentBuilderFactory.newDocumentBuilder();
    }

    public static org.w3c.dom.Document newDocument() throws ParserConfigurationException {
        return newDocumentBuilder().newDocument();
    }
*/

    /**
     * 随机生成用户初始化密码
     * @return
     */
    public static String createUserPwd(){
        Random random = new Random();
        StringBuilder pwd = new StringBuilder();
        for(int i = 0; i < PWD_LENGTH; i ++){
            pwd.append(random.nextInt(10))  ;
        }
        return pwd.toString();
    }

    /**
     * 生成邀请码(6位)
     * 3位随机数 + 当前时间的毫秒数(不足三位的补齐3位) + 1位随机数
     * @return
     */
    public static String createInviteCode(){
        Random random = new Random();
        StringBuilder inviteCode = new StringBuilder();
        for(int i = 0; i < 2; i ++){
            inviteCode.append(random.nextInt(10));
        }
        Calendar nowtime = new GregorianCalendar();
        String millSecond = nowtime.get(Calendar.MILLISECOND) + "";
        while(millSecond.length() < 3){
            millSecond += random.nextInt(10);
            if(millSecond.length() >= 3){
                break;
            }
        }
        inviteCode.append(millSecond);
        inviteCode.append(random.nextInt(10));
        return inviteCode.toString();
    }

    /**
     * 检测字符是否为空
     * @param strs
     * @return true为空,false不为空
     */
    public static boolean checkEmpty(String...strs){
        if(null != strs && strs.length > 0){
            for(String s : strs){
                if(null == s || s.trim().equals("")){
                    return true;
                }
            }
        }
        return false;
    }


    /**
     * 发送Http请求到url对应的地址
     * @param urlStr 请求地址
     * @return 服务器的响应字符串(如果是json,需要做json处理)
     */
    public static String sendURL(String urlStr){
        if(!WebUtil.checkEmpty(urlStr)){
            try {
                URL url = new URL(urlStr);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                //设置连接的请求超时时间,单位为毫秒
                connection.setConnectTimeout(CONNECTTIMEOUT);
                //设置连接后读取response信息的超时时间,单位为毫秒
                connection.setReadTimeout(READTIME);
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
                StringBuffer stringBuffer = new StringBuffer();
                String temp = "";
                while((temp = reader.readLine()) != null){
                    stringBuffer.append(temp);
                }
                String result = stringBuffer.toString();
                return result;
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static String getDayBegin(Date date){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DATE);
        return "" + year + "-" + (month + 1) + "-" + day + " 00:00:00";
    }



    public static String getDayEnd(Date date){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DATE);
        return "" + year + "-" + (month + 1) + "-" + day + " 23:59:59";
    }

    /**
     * 生成UUID
     * @return
     */
    public static String getUUID(){
        UUID uuid = UUID.randomUUID();
        return uuid.toString();
    }

    public static String getRandomString(int length){
        StringBuffer s = new StringBuffer();
        //获取当前毫秒值
        Calendar nowTime = new GregorianCalendar();
        String millSecond = nowTime.get(Calendar.MILLISECOND) + "";
        s.append(millSecond);
        Random random = new Random();
        do{
            s.append(digits[random.nextInt(digits.length)]);
        }while(s.length() < length);
        return s.toString();
    }



    public static String genNonceStr() {
        Random random = new Random();
        return MD5Util.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
    }

    public static String formatTime(Date date){
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return f.format(date);
    }

    public static String changeTimeStyle(String timeStr, String style, String targetStyle){
        SimpleDateFormat f = new SimpleDateFormat(style);
        try {
            Date date = f.parse(timeStr);
            f = null;
            f = new SimpleDateFormat(targetStyle);
            return f.format(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "";
    }



    public static String formatTime(Date date, String style){
        SimpleDateFormat f = new SimpleDateFormat(style);
        return f.format(date);
    }


    public static Date formatTime(String dateStr, String style){
        SimpleDateFormat f = new SimpleDateFormat(style);
        try {
            return f.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String handlerPhone(String phone){
        if(!WebUtil.checkEmpty(phone) && phone.length() == 11){
            String str = "****";
            String str1 = phone.substring(0,3);
            String str2 = phone.substring(7);
            return str1 + str + str2;
        }
        return "";
    }


    public static String getBasePath(HttpServletRequest request){
        String path = request.getContextPath();
        String basePath = request.getScheme()+"://"+request.getServerName()
                +":"+request.getServerPort()+path+"/";
        return basePath;
    }

    public static String getRootRealPath(HttpServletRequest request){
        return request.getSession().getServletContext().getRealPath("/");
    }


    // 加密
    public static String getBase64(String str) {
        byte[] b = null;
        String s = null;
        try {
            b = str.getBytes("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (b != null) {
            s = new BASE64Encoder().encode(b);
        }
        return s;
    }

    // 解密
    public static String getFromBase64(String s) {
        byte[] b = null;
        String result = null;
        if (s != null) {
            BASE64Decoder decoder = new BASE64Decoder();
            try {
                b = decoder.decodeBuffer(s);
                result = new String(b, "utf-8");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }


    public static Map xmlHandler(String xmlStr, String...elementNames){
        SAXReader reader = new SAXReader();
        Map map = new HashMap();
        try {
            Document doc = DocumentHelper.parseText(xmlStr);
            //获取根目录元素
            Element root = doc.getRootElement();
            for(Iterator it = root.elementIterator(); it.hasNext();){
                Element element = (Element) it.next();
                String eName = element.getName();
                for(String s : elementNames){
                    if(eName.equals(s)){
                        map.put(s, element.getTextTrim());
                    }
                }
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return map;
    }

    public static void main(String[] args) {
        String msg = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg><appid>" +
                "<![CDATA[wxa1261e22bf0e9094]]></appid><mch_id><![CDATA[1490693182]]></mch_id><nonce_str><![CDATA[MG5ynq35ULuLT1RV]]>" +
                "</nonce_str><sign><![CDATA[4D14CEF41F6AFD83C21051B1162E765B]]></sign><result_code><![CDATA[SUCCESS]]></result_code><prepay_id>" +
                "<![CDATA[wx09151815977306e7142a604d2114954223]]></prepay_id><trade_type><![CDATA[APP]]></trade_type></xml>";

        Element root = WebUtil.getXmlRoot(msg);
        String return_code = root.element("return_code").getTextTrim();
        System.out.println(return_code);
    }

    public static Element getXmlRoot(String xmlStr){
        SAXReader reader = new SAXReader();
        try{
            reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl",true);

            reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
            reader.setFeature("http://xml.org/sax/features/external-general-entities", false);
            reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
            reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
            reader.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
           /* reader.setXIncludeAware(false);
            reader.setExpandEntityReferences(false);
*/
            Document document = reader.read(new ByteArrayInputStream(xmlStr.getBytes("utf-8")));
            //读取xml字符串,注意这里要转成输入流
            Element root = document.getRootElement();//获取根元素
            return root;

        }catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


   /* public static org.w3c.dom.Document getXmlRootV2(String xmlStr){
        //SAXReader reader = new SAXReader();

        try {
            //DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

            org.w3c.dom.Document document = WebUtil.newDocument();
            org.w3c.dom.Document root = (org.w3c.dom.Document) document.createElement(xmlStr);
            return root;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public   static   Document   parse(org.w3c.dom.Document   doc)   throws   Exception   {
        if   (doc   ==   null)   {
            return   (null);
        }
        org.dom4j.io.DOMReader   xmlReader   =   new   org.dom4j.io.DOMReader();
        return   (xmlReader.read(doc));
    }

    *//**
     *   org.dom4j.Document   ->   org.w3c.dom.Document
     *   @param   doc   Document(org.dom4j.Document)
     *   @throws   Exception
     *   @return   Document
     *//*
    public   static   org.w3c.dom.Document   parse(Document   doc)   throws   Exception   {
        if   (doc   ==   null)   {
            return   (null);
        }
        java.io.StringReader   reader   =   new   java.io.StringReader(doc.asXML());
        org.xml.sax.InputSource   source   =   new   org.xml.sax.InputSource(reader);
        javax.xml.parsers.DocumentBuilderFactory   documentBuilderFactory   =
                javax.xml.parsers.DocumentBuilderFactory.newInstance();
        javax.xml.parsers.DocumentBuilder   documentBuilder   =   documentBuilderFactory.
                newDocumentBuilder();
        return   (documentBuilder.parse(source));
    }*/

    public static String createlFileName(){
        Calendar currentTime = Calendar.getInstance();
        int year = currentTime.get(Calendar.YEAR);
        int month = currentTime.get(Calendar.MONTH) + 1;
        int date = currentTime.get(Calendar.DAY_OF_MONTH);
        int hour = currentTime.get(Calendar.HOUR_OF_DAY);
        int minuter = currentTime.get(Calendar.MINUTE);
        int second = currentTime.get(Calendar.SECOND);
        Random random = new Random();
        return hour + "-" + minuter + "-" + second + "_r-" + random.nextInt(10) + "" + random.nextInt(10) + "" + random.nextInt(10);
    }

    /**
     * 创建年月日形式的文件夹
     * @param rootPath
     * @return
     */
    public static File createDir(String rootPath){
        File dir = new File(rootPath);
        if(!dir.exists()){
            dir.mkdir();
        }
        Calendar currentTime = Calendar.getInstance();
        int year = currentTime.get(Calendar.YEAR);
        File yearDir = new File(dir, String.valueOf(year));
        if(!yearDir.exists()){
            yearDir.mkdirs();
        }
        int month = currentTime.get(Calendar.MONTH) + 1;
        File monthDir = new File(yearDir, String.valueOf(month));
        if(!monthDir.exists()){
            monthDir.mkdir();
        }
        int date = currentTime.get(Calendar.DAY_OF_MONTH);
        File dateDir = new File(monthDir, String.valueOf(date));
        if(!dateDir.exists()){
            dateDir.mkdir();
        }
        return dateDir;
    }


    /**
     * 将时间转换成显示的时间格式,参考微信
     * @param addTime
     * @return
     */
    public static String getShowTime(Date addTime) {
        //当前日历时间
        Calendar currentCalendar = Calendar.getInstance();
        //发布日历时间
        Calendar startCalendar = Calendar.getInstance();
        startCalendar.setTime(addTime);
        //当前时间单位
        int cYear = currentCalendar.get(Calendar.YEAR);
        int cMonth = currentCalendar.get(Calendar.MONTH);
        int cDate = currentCalendar.get(Calendar.DAY_OF_MONTH);
        int cHour = currentCalendar.get(Calendar.HOUR_OF_DAY);
        int cMinuter = currentCalendar.get(Calendar.MINUTE);
        //发布时间单位
        int sYear = startCalendar.get(Calendar.YEAR);
        int sMonth = startCalendar.get(Calendar.MONTH);
        int sDate = startCalendar.get(Calendar.DAY_OF_MONTH);
        int sHour = startCalendar.get(Calendar.HOUR_OF_DAY);
        int sMinuter = startCalendar.get(Calendar.MINUTE);
        if(cYear >sYear){
            return (cYear - sYear) + "年前";
        }
        else if(cMonth > sMonth){
            return (cMonth - sMonth) + "个月前";
        }
        else if(cDate > sDate){
            return (cDate - sDate) > 1 ?  (cDate - sDate) + "天前" : "昨天";
        }
        else if(cHour > sHour){
            return (cHour - sHour) + "小时前";
        }
        else if(cMinuter >= sMinuter){
            return (cMinuter - sMinuter) < 1 ? "刚刚" : (cMinuter - sMinuter) + "分钟前";
        }
        return "";
    }


    /**
     * 获取字符的编码
     * @param str
     * @return
     */
    public static String getEncoding(String str) {
        String encode = "GB2312";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String s = encode;
                return s;
            }
        } catch (Exception exception) {
        }
        encode = "ISO-8859-1";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String s1 = encode;
                return s1;
            }
        } catch (Exception exception1) {
        }
        encode = "UTF-8";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String s2 = encode;
                return s2;
            }
        } catch (Exception exception2) {
        }
        encode = "GBK";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String s3 = encode;
                return s3;
            }
        } catch (Exception exception3) {
        }
        return "";
    }


    public static String generateOrderNo(){
        Date date = new Date();
        String dateStr = formatTime(date,"yyyyMMddHHmmssSS");
        Random random = new Random();
        return dateStr + "521" + random.nextInt(10) + "" + random.nextInt(10) + "" + random.nextInt(10);
    }


    public static String generateOrderNo(String type,int step){
        Date date = new Date();
        String dateStr =type+ date.getTime();
        Random random = new Random();
        return dateStr + random.nextInt(step);
    }

    public static String DateformatTime(Date date) {
        //SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //转换为日期
        long time = date.getTime();
        if (isThisYear(date)) {//今年
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
            if (isToday(date)) { //今天
                int minute = minutesAgo(time);
                if (minute < 60) {//1小时之内
                    if (minute <= 1) {//一分钟之内,显示刚刚
                        return "刚刚";
                    } else {
                        return minute + "分钟前";
                    }
                } else {
                    return simpleDateFormat.format(date);
                }
            } else {
                if (isYestYesterday(date)) {//昨天,显示昨天
                    return "昨天 " + simpleDateFormat.format(date);
                } else if (isThisWeek(date)) {//本周,显示周几
                    String weekday = null;
                    if (date.getDay() == 1) {
                        weekday = "周一";
                    }
                    if (date.getDay() == 2) {
                        weekday = "周二";
                    }
                    if (date.getDay() == 3) {
                        weekday = "周三";
                    }
                    if (date.getDay() == 4) {
                        weekday = "周四";
                    }
                    if (date.getDay() == 5) {
                        weekday = "周五";
                    }
                    if (date.getDay() == 6) {
                        weekday = "周六";
                    }
                    if (date.getDay() == 0) {
                        weekday = "周日";
                    }
                    return weekday + " " + simpleDateFormat.format(date);
                } else {
                    SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm");
                    return sdf.format(date);
                }
            }
        } else {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            return sdf.format(date);
        }
    }

    /**
     * String型时间戳格式化
     *
     * @return
     */
    public static String LongFormatTime(String time) {
        //SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //转换为日期
        Date date = new Date();
        date.setTime(Long.parseLong(time));
        if (isThisYear(date)) {//今年
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
            if (isToday(date)) { //今天
                int minute = minutesAgo(Long.parseLong(time));
                if (minute < 60) {//1小时之内
                    if (minute <= 1) {//一分钟之内,显示刚刚
                        return "刚刚";
                    } else {
                        return minute + "分钟前";
                    }
                } else {
                    return simpleDateFormat.format(date);
                }
            } else {
                if (isYestYesterday(date)) {//昨天,显示昨天
                    return "昨天 " + simpleDateFormat.format(date);
                } else if (isThisWeek(date)) {//本周,显示周几
                    String weekday = null;
                    if (date.getDay() == 1) {
                        weekday = "周一";
                    }
                    if (date.getDay() == 2) {
                        weekday = "周二";
                    }
                    if (date.getDay() == 3) {
                        weekday = "周三";
                    }
                    if (date.getDay() == 4) {
                        weekday = "周四";
                    }
                    if (date.getDay() == 5) {
                        weekday = "周五";
                    }
                    if (date.getDay() == 6) {
                        weekday = "周六";
                    }
                    if (date.getDay() == 0) {
                        weekday = "周日";
                    }
                    return weekday + " " + simpleDateFormat.format(date);
                } else {
                    SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm");
                    return sdf.format(date);
                }
            }
        } else {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            return sdf.format(date);
        }
    }

    private static int minutesAgo(long time) {
        return (int) ((System.currentTimeMillis() - time) / (60000));
    }

    private static boolean isToday(Date date) {
        Date now = new Date();
        return (date.getYear() == now.getYear()) && (date.getMonth() == now.getMonth()) && (date.getDate() == now.getDate());
    }

    private static boolean isYestYesterday(Date date) {
        Date now = new Date();
        return (date.getYear() == now.getYear()) && (date.getMonth() == now.getMonth()) && (date.getDate() + 1 == now.getDate());
    }

    private static boolean isThisWeek(Date date) {
        Date now = new Date();
        if ((date.getYear() == now.getYear()) && (date.getMonth() == now.getMonth())) {
            if (now.getDay() - date.getDay() < now.getDay() && now.getDate() - date.getDate() > 0 && now.getDate() - date.getDate() < 7) {
                return true;
            }
        }
        return false;
    }

    private static boolean isThisYear(Date date) {
        Date now = new Date();
        return date.getYear() == now.getYear();
    }

}

 获取微信的token:WeiXinShare 方法从缓存中获取

package com.shopping.view.web.tools;

import com.shopping.app.controller.v1.WXTuiSong.WXTuiSongTools;
import com.shopping.app.controller.v1.pyp.HttpClientPostMethod;
import com.shopping.app.controller.v1.weixin.HttpClient;
import com.shopping.app.util.RedisManager;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 *
 * 微信分享接口的服务对象
 */
@Component
public class WeiXinShare {

    private static WeiXinShare weiXinShare;

    public static String APPID = "wxdba8522d8b167071";
    private static String APPSECRET = "67076c903947312fddf06f8b00b5f065";
    private static int CONNECTTIMEOUT =  5000;
    private static int READTIME = 10000;

    public final static String auth_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token";
    public final static String sns_userInfo = "https://api.weixin.qq.com/sns/userinfo";


    @Autowired
    public RedisManager redisManager;

    @PostConstruct
    public void init() {
        weiXinShare = this;
        weiXinShare.redisManager = this.redisManager;
    }


    public static String getAppSrcret(){
        return APPSECRET;
    }

    /**
     * 获取普通 Access_token
     * @return
     */
    public static String getAccess_token(){
        String access_token = "";
        access_token = weiXinShare.redisManager.STRINGS.get("dkservice_accessToken");
        /*access_token = accessTokenMap.get("accessToken");*/
        if(WebUtil.checkEmpty(access_token)){
            //如果是空的,进行请求,并且放入缓存
            access_token = getAccessTokenFromURL();

            weiXinShare.redisManager.STRINGS.set("dkservice_token_putTime", new Date().getTime() + "");
            weiXinShare.redisManager.STRINGS.set("dkservice_accessToken", access_token);

            /*accessTokenMap.put("putTime", new Date().getTime() + "");
            accessTokenMap.put("accessToken", access_token);*/
        }else{
            //如果不是空的,检测时间
            String time = weiXinShare.redisManager.STRINGS.get("dkservice_token_putTime");
            Long putTime = Long.parseLong(time);
            Long currentTime = new Date().getTime();
            if((currentTime - putTime) > 7000000){
                access_token = getAccessTokenFromURL();
                weiXinShare.redisManager.STRINGS.set("dkservice_token_putTime", new Date().getTime() + "");
                weiXinShare.redisManager.STRINGS.set("dkservice_accessToken", access_token);
                /*accessTokenMap.put("putTime", new Date().getTime() + "");
                accessTokenMap.put("accessToken", access_token);*/
            }
        }
        return weiXinShare.redisManager.STRINGS.get("dkservice_accessToken");
    }


    /**
     * 获取普通 jsapi_ticket
     * @param access_token
     * @return
     */
    public static String getJsapi_ticket(String access_token){
        String jsapi_ticket = "";
        jsapi_ticket = weiXinShare.redisManager.STRINGS.get("dkservice_jsapiTicket");
       /* jsapi_ticket = jsapiTicketMap.get("jsapiTicket");*/
        if(WebUtil.checkEmpty(jsapi_ticket)){
            jsapi_ticket = getJsapiTicketFromURL(access_token);

            weiXinShare.redisManager.STRINGS.set("dkservice_jsapi_ticket_putTime", new Date().getTime() + "");
            weiXinShare.redisManager.STRINGS.set("dkservice_jsapiTicket", jsapi_ticket);

            /*jsapiTicketMap.put("putTime", new Date().getTime() + "");
            jsapiTicketMap.put("jsapiTicket", jsapi_ticket);*/
        }else{
            String time = weiXinShare.redisManager.STRINGS.get("dkservice_jsapi_ticket_putTime");
            /*String time = jsapiTicketMap.get("putTime");*/
            Long putTime = Long.parseLong(time);
            Long currentTime = new Date().getTime();
            if((currentTime - putTime) > 7000000){
                jsapi_ticket = getJsapiTicketFromURL(access_token);

                weiXinShare.redisManager.STRINGS.set("dkservice_jsapi_ticket_putTime", new Date().getTime() + "");
                weiXinShare.redisManager.STRINGS.set("dkservice_jsapiTicket", jsapi_ticket);

                /*jsapiTicketMap.put("putTime", new Date().getTime() + "");
                jsapiTicketMap.put("jsapiTicket", jsapi_ticket);*/
            }
        }
        return weiXinShare.redisManager.STRINGS.get("dkservice_jsapiTicket");
    }


    /**
     * 获取签名
     * @param jsapi_ticket
     * @param noncestr
     * @param timestamp
     * @param url
     * @return
     */
    public static String getSignature(String jsapi_ticket, String noncestr, String timestamp, String url){
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("jsapi_ticket=").append(jsapi_ticket)
                .append("&noncestr=").append(noncestr)
                .append("&timestamp=").append(timestamp)
                .append("&url=").append(url);
        String string1 = stringBuffer.toString();
        System.out.println(string1);
        String signature = "";
        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return signature;
    }


    public static String signature(String[] strs){
        Arrays.sort(strs);
        StringBuffer stringBuffer = new StringBuffer();

        for (int i = 0; i < strs.length; i++) {
                stringBuffer.append(strs[i]);
         }
        System.out.println(stringBuffer.toString());
        String signature = "";
        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(stringBuffer.toString().getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return signature;
    }


    public static void sort(String a[]) {
            for (int i = 0; i < a.length - 1; i++) {
                       for (int j = i + 1; j < a.length; j++) {
                            if (a[j].compareTo(a[i]) < 0) {
                                    String temp = a[i];
                                     a[i] = a[j];
                                     a[j] = temp;
                                 }
                        }
                   }
         }

    public static String create_nonce_str() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    public static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash)
        {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    private static String getAccessTokenFromURL(){
        String access_token = "";
        try {
            String str = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APPID + "&secret=" + APPSECRET;
            URL url = new URL(str);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            //设置连接的请求超时时间,单位为毫秒
            connection.setConnectTimeout(CONNECTTIMEOUT);
            //设置连接后读取response信息的超时时间,单位为毫秒
            connection.setReadTimeout(READTIME);
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
            StringBuffer stringBuffer = new StringBuffer();
            String temp = "";
            while((temp = reader.readLine()) != null){
                stringBuffer.append(temp);
            }
            String result = stringBuffer.toString();
            System.out.println("token result = "+ result);
            JSONObject root = JSONObject.fromObject(result);
            access_token = root.getString("access_token");
            reader.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return access_token;
    }

    private static String getJsapiTicketFromURL(String access_token){
        String str = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + access_token + "&type=jsapi";
        String jsapi_ticket = "";
        try {
            URL url = new URL(str);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(CONNECTTIMEOUT);
            connection.setReadTimeout(READTIME);
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
            String temp = "";
            StringBuffer stringBuffer = new StringBuffer();
            while((temp = reader.readLine()) != null){
                stringBuffer.append(temp);
            }
            String result = stringBuffer.toString();
            JSONObject root = JSONObject.fromObject(result);
            jsapi_ticket = root.getString("ticket");
            reader.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsapi_ticket;
    }

    public static String sendWeChartMsg(String sendUrl,String json){

        try {
            String msg = HttpClientPostMethod.postJSON(sendUrl, json);
            JSONObject jsonObject = JSONObject.fromObject(msg);

            if (jsonObject.getInt("errcode") != 0){
                System.out.println(jsonObject.get("errcode"));
                System.out.println(jsonObject.get("errmsg"));
                System.out.println(jsonObject.get("msgid"));
            }

            return jsonObject.get("errcode").toString();


        } catch (IOException e) {
            e.printStackTrace();
        }
        return "-1";
    }

    /**
     * 用户已经关注公众号,获取用户信息
     * @param openId
     * @return
     */

    public static String getWXUserInfo(String openId){
        String url= WXTuiSongTools.usermessage+"?access_token="+WeiXinShare.getAccess_token()+"&openid="+openId;

        /*String url= WXTuiSongTools.sns_userInfo+"?access_token="+WeiXinShare.getAccess_token()+"&openid="+openId+"&lang=zh_CN";*/
        String msg = HttpClient.executeGet(url);
        /*String json = null;
        try {
            json = new String(msg.getBytes("GBK"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }*/
        return msg;
    }

    /**
     * 网页授权 不需要关注公众号获取用户信息
     * @param openId
     * @param access_token
     * @return
     */

    public static String getWXUserInfoNotNotice(String openId,String access_token){
        /*String url= WXTuiSongTools.usermessage+"?access_token="+WeiXinShare.getAccess_token()+"&openid="+openId;*/

        String url= WXTuiSongTools.sns_userInfo+"?access_token="+access_token+"&openid="+openId+"&lang=zh_CN";
        String msg = HttpClient.executeGet(url);
        /*String json = null;
        try {
            json = new String(msg.getBytes("GBK"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }*/
        return msg;
    }
}

 

最终要试用生成订单的方法:

package com.shopping.view.web.tools;

import com.shopping.pay.weixin.WX_XCXUtil;
import com.shopping.pay.weixin.WeixinPay;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import java.io.*;
import java.security.KeyStore;
import java.util.LinkedHashMap;

/**
 * Created by Leon on 2015/11/24 0024.
 */
public class WeixinTools {



    private static Logger LOG = LoggerFactory.getLogger(WeixinTools.class);

    public static void main(String[] args){
        try {
            refund("4008072001201605206075139628", 1,"");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 统一下单接口
     * @param body 商品描述
     * @param outTradeNo 订单号
     * @param detail 商品详情
     * @param total_fee 总金额,单位为分
     * @return
     */
    public static String  unifyOrder(String body, String outTradeNo, String detail, int total_fee, String...notify_url){
        LinkedHashMap<String, Object> params = new LinkedHashMap<String, Object>();

        String noncStr = WebUtil.genNonceStr();
        //组装生成签名需要的字段
        params.put("appid", WeixinPay.APPID);
        try {
            params.put("&body", new String(body.getBytes("UTF-8"),"UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            params.put("&detail",new String(detail.getBytes("UTF-8"),"UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        params.put("&mch_id",WeixinPay.MCH_ID);
        params.put("&nonce_str",noncStr);
        if(notify_url != null && notify_url.length > 0){
            params.put("&notify_url", notify_url[0]);
        }else {
            params.put("&notify_url", WeixinPay.notify_url_order);
        }

        params.put("&out_trade_no", outTradeNo);
        params.put("&total_fee", total_fee);
        params.put("&trade_type", WeixinPay.trade_type);
        //添加密钥key
        params.put("&key",WeixinPay.api_sec);
        //生成签名
        String sign = WeixinPay.generateSign(params);

        System.out.println("sign==" + sign);

        //组装请求统一下单接口的xml
        StringBuilder sb = new StringBuilder();
        sb.append("<xml>");
        sb.append("<appid>"+WeixinPay.APPID+"</appid>");
        try {
            sb.append("<body><![CDATA["+ new String(body.getBytes("UTF-8"),"UTF-8") +"]]></body>");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            sb.append("<detail><![CDATA["+new String(detail.getBytes("UTF-8"),"UTF-8")+"]]></detail>");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        sb.append("<mch_id>"+WeixinPay.MCH_ID+"</mch_id>");
        sb.append("<nonce_str>"+ noncStr +"</nonce_str>");
        if(notify_url != null && notify_url.length > 0){
            sb.append("<notify_url>" +notify_url[0] + "</notify_url>");
        }else{
            sb.append("<notify_url>" + WeixinPay.notify_url_order + "</notify_url>");
        }

        sb.append("<out_trade_no>"+ outTradeNo +"</out_trade_no>");
        sb.append("<total_fee>" + total_fee + "</total_fee>");
        sb.append("<trade_type>" + WeixinPay.trade_type + "</trade_type>");
        sb.append("<sign>" + sign.toUpperCase() + "</sign>");
        sb.append("</xml>");

        System.out.println(sb.toString());

        //调用微信的统一下单接口获取下单结果
        String result = HttpUitl.postXML(WeixinPay.unifiedorder_url, sb.toString());
        try {
            result = new String(result.getBytes("GBK"), "UTF-8");
            LOG.info("订单查询返回结果:" + result);
            Element root =  WebUtil.getXmlRoot(result);
            String return_code = root.element("return_code").getTextTrim();
            if(!WebUtil.checkEmpty(return_code) && return_code.equals("SUCCESS")){
                LOG.info("微信统一下单通信成功!");
                String appid = root.element("appid").getTextTrim();
                String mch_id = root.element("mch_id").getTextTrim();
                String nonce_str = root.element("nonce_str").getTextTrim();
                String sg = root.element("sign").getTextTrim(); //这里的签名是微信服务器给的,用来验证微信服务器的身份
                String result_code = root.element("result_code").getTextTrim();
                if(!WebUtil.checkEmpty(result_code) && result_code.equals("SUCCESS")){
                    LOG.info("微信统一下单业务成功!");
                    String trade_type = root.element("trade_type").getTextTrim();
                    String prepay_id = root.element("prepay_id").getTextTrim();
                    //生成终端需要的参数
                    String nStr = WebUtil.genNonceStr();
                    String timeStamp = Long.toString(System.currentTimeMillis() / 1000);
                    LinkedHashMap sgParams = new LinkedHashMap();
                    sgParams.put("appid", WeixinPay.APPID);
                    sgParams.put("&noncestr", nStr);
                    sgParams.put("&package", "Sign=WXPay");
                    sgParams.put("&partnerid", WeixinPay.MCH_ID);
                    sgParams.put("&prepayid", prepay_id);
                    sgParams.put("&timestamp", timeStamp);
                    sgParams.put("&key", WeixinPay.api_sec);
                    String sgStr = WeixinPay.generateSign(sgParams);
                    return "SUCCESS_" + prepay_id + "_" + nStr + "_" + timeStamp + "_" + sgStr;
                }
                else if(!WebUtil.checkEmpty(result_code) && result_code.equals("FAIL")){
                    String err_code = root.element("err_code").getTextTrim();
                    String err_code_des = root.element("err_code_des").getTextTrim();
                    LOG.info("微信统一下单业务失败!"+ "错误代码:" + err_code + " 错误描述:" + err_code_des);
                    return "ERROR_" + "[error_code : " + err_code + "],[err_code_des : " + err_code_des + "]";
                }
            }
            else if(!WebUtil.checkEmpty(return_code) && return_code.equals("FAIL")){
                LOG.info("微信统一下单通信失败:" + root.element("return_msg").getTextTrim());
                return "ERROR_" + "微信统一下单通信失败:" + root.element("return_msg").getTextTrim();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }


    public static String unifyOrder_H5(String body, String outTradeNo, String detail, int total_fee,String openId,String code,String url, String...notify_url){
        LinkedHashMap<String, Object> params = new LinkedHashMap<String, Object>();

        String access_token = WeiXinShare.getAccess_token();
        String jspai_ticket = WeiXinShare.getJsapi_ticket(access_token);
        String nonceStr = WeiXinShare.create_nonce_str();
        String timestamp = WeiXinShare.create_timestamp();
        // String url = URL.url + "/h5_shopping/m_shoppingMyOrder.html?code="+code+"&state=6";
        try {
            url =java.net.URLDecoder.decode(url,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        System.out.println(url);
        String signature = WeiXinShare.getSignature(jspai_ticket, nonceStr, timestamp, url);


        String noncStr = nonceStr;
        //组装生成签名需要的字段
        params.put("appid", WeixinPay.APPID_H5);
        try {
            params.put("&body", new String(body.getBytes("UTF-8"),"UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            params.put("&detail",new String(detail.getBytes("UTF-8"),"UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        params.put("&mch_id",WeixinPay.MCH_ID_H5);
        params.put("&nonce_str",noncStr);
        if(notify_url != null && notify_url.length > 0){
            params.put("&notify_url", notify_url[0]);
        }else {
            params.put("&notify_url", WeixinPay.notify_url_order);
        }
        params.put("&openid",openId);
        params.put("&out_trade_no", outTradeNo);
        params.put("&spbill_create_ip", "123.57.151.22");
        params.put("&total_fee", total_fee);
        params.put("&trade_type", "JSAPI");
        //添加密钥key
        params.put("&key",WeixinPay.key);
        //生成签名
        String sign = WeixinPay.generateSign(params);
        //组装请求统一下单接口的xml
        StringBuilder sb = new StringBuilder();
        sb.append("<xml>");
        sb.append("<appid>"+WeixinPay.APPID_H5+"</appid>");
        try {
            sb.append("<body><![CDATA["+ new String(body.getBytes("UTF-8"),"UTF-8") +"]]></body>");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            sb.append("<detail><![CDATA["+new String(detail.getBytes("UTF-8"),"UTF-8")+"]]></detail>");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        sb.append("<mch_id>"+WeixinPay.MCH_ID_H5+"</mch_id>");
        sb.append("<nonce_str>" + noncStr + "</nonce_str>");
        if(notify_url != null && notify_url.length > 0){
            sb.append("<notify_url>" +notify_url[0] + "</notify_url>");
        }else{
            sb.append("<notify_url>" + WeixinPay.notify_url_order + "</notify_url>");
        }
        sb.append("<openid>"+ openId +"</openid>");
        sb.append("<out_trade_no>"+ outTradeNo +"</out_trade_no>");
        sb.append("<spbill_create_ip>123.57.151.22</spbill_create_ip>");
        sb.append("<total_fee>" + total_fee + "</total_fee>");

        sb.append("<trade_type>JSAPI</trade_type>");
        sb.append("<sign>" + sign.toUpperCase() + "</sign>");
        sb.append("</xml>");
        //调用微信的统一下单接口获取下单结果
        String result = HttpUitl.postXML(WeixinPay.unifiedorder_url, sb.toString());
        try {
            result = new String(result.getBytes("GBK"), "UTF-8");
            LOG.info("订单查询返回结果:" + result);
            Element root =  WebUtil.getXmlRoot(result);
            String return_code = root.element("return_code").getTextTrim();
            if(!WebUtil.checkEmpty(return_code) && return_code.equals("SUCCESS")){
                LOG.info("微信统一下单通信成功!");
                String appid = root.element("appid").getTextTrim();
                String mch_id = root.element("mch_id").getTextTrim();
                String nonce_str = root.element("nonce_str").getTextTrim();
                String sg = root.element("sign").getTextTrim(); //这里的签名是微信服务器给的,用来验证微信服务器的身份
                String result_code = root.element("result_code").getTextTrim();
                if(!WebUtil.checkEmpty(result_code) && result_code.equals("SUCCESS")){
                    LOG.info("微信统一下单业务成功!");
                    String trade_type = root.element("trade_type").getTextTrim();
                    String prepay_id = root.element("prepay_id").getTextTrim();
                    //生成终端需要的参数
                    String nStr = WebUtil.genNonceStr();
                    //String timeStamp = Long.toString(System.currentTimeMillis() / 1000);
                    LinkedHashMap sgParams = new LinkedHashMap();
                    sgParams.put("appId", WeixinPay.APPID_H5);
                    sgParams.put("&nonceStr", noncStr);
                    sgParams.put("&package", "prepay_id="+prepay_id);
                    sgParams.put("&signType", "MD5");
                    sgParams.put("&timeStamp", timestamp);
                    sgParams.put("&key", WeixinPay.key);
                    String sgStr = WeixinPay.generateSign(sgParams);
                    return "SUCCESS_" + prepay_id + "_" + noncStr + "_" + timestamp + "_" + sgStr+"_"+signature;
                }
                else if(!WebUtil.checkEmpty(result_code) && result_code.equals("FAIL")){
                    String err_code = root.element("err_code").getTextTrim();
                    String err_code_des = root.element("err_code_des").getTextTrim();
                    LOG.info("微信统一下单业务失败!"+ "错误代码:" + err_code + " 错误描述:" + err_code_des);
                    return "ERROR_" + "[error_code : " + err_code + "],[err_code_des : " + err_code_des + "]";
                }
            }
            else if(!WebUtil.checkEmpty(return_code) && return_code.equals("FAIL")){
                LOG.info("微信统一下单通信失败:" + root.element("return_msg").getTextTrim());
                return "ERROR_" + "微信统一下单通信失败:" + root.element("return_msg").getTextTrim();
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String unifyOrder_XCX(String body, String outTradeNo, String detail, int total_fee,String openId,String code,String url, String...notify_url){
        LinkedHashMap<String, Object> params = new LinkedHashMap<String, Object>();

        String access_token = WeiXinShare.getAccess_token();
        String jspai_ticket = WeiXinShare.getJsapi_ticket(access_token);
        String nonceStr = WeiXinShare.create_nonce_str();
        String timestamp = WeiXinShare.create_timestamp();
        // String url = URL.url + "/h5_shopping/m_shoppingMyOrder.html?code="+code+"&state=6";
        try {
            url =java.net.URLDecoder.decode(url,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        System.out.println(url);
        String signature = WeiXinShare.getSignature(jspai_ticket, nonceStr, timestamp, url);


        String noncStr = nonceStr;
        //组装生成签名需要的字段
        params.put("appid",WX_XCXUtil.APPID);
        try {
            params.put("&body", new String(body.getBytes("UTF-8"),"UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            params.put("&detail",new String(detail.getBytes("UTF-8"),"UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        params.put("&mch_id",WeixinPay.MCH_ID_H5);
        params.put("&nonce_str",noncStr);
        if(notify_url != null && notify_url.length > 0){
            params.put("&notify_url", notify_url[0]);
        }else {
            params.put("&notify_url", WeixinPay.notify_url_order);
        }
        params.put("&openid",openId);
        params.put("&out_trade_no", outTradeNo);
        params.put("&spbill_create_ip", "123.57.151.22");
        params.put("&total_fee", total_fee);
        params.put("&trade_type", "JSAPI");
        //添加密钥key
        params.put("&key",WeixinPay.key);
        //生成签名
        String sign = WeixinPay.generateSign(params);
        //组装请求统一下单接口的xml
        StringBuilder sb = new StringBuilder();
        sb.append("<xml>");
        sb.append("<appid>"+WX_XCXUtil.APPID+"</appid>");
        try {
            sb.append("<body><![CDATA["+ new String(body.getBytes("UTF-8"),"UTF-8") +"]]></body>");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            sb.append("<detail><![CDATA["+new String(detail.getBytes("UTF-8"),"UTF-8")+"]]></detail>");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        sb.append("<mch_id>"+WeixinPay.MCH_ID_H5+"</mch_id>");
        sb.append("<nonce_str>" + noncStr + "</nonce_str>");
        if(notify_url != null && notify_url.length > 0){
            sb.append("<notify_url>" +notify_url[0] + "</notify_url>");
        }else{
            sb.append("<notify_url>" + WeixinPay.notify_url_order + "</notify_url>");
        }
        sb.append("<openid>"+ openId +"</openid>");
        sb.append("<out_trade_no>"+ outTradeNo +"</out_trade_no>");
        sb.append("<spbill_create_ip>123.57.151.22</spbill_create_ip>");
        sb.append("<total_fee>" + total_fee + "</total_fee>");

        sb.append("<trade_type>JSAPI</trade_type>");
        sb.append("<sign>" + sign.toUpperCase() + "</sign>");
        sb.append("</xml>");
        //调用微信的统一下单接口获取下单结果
        String result = HttpUitl.postXML(WeixinPay.unifiedorder_url, sb.toString());
        try {
            result = new String(result.getBytes("GBK"), "UTF-8");
            LOG.info("订单查询返回结果:" + result);
            Element root =  WebUtil.getXmlRoot(result);
            String return_code = root.element("return_code").getTextTrim();
            if(!WebUtil.checkEmpty(return_code) && return_code.equals("SUCCESS")){
                LOG.info("微信统一下单通信成功!");
                String appid = root.element("appid").getTextTrim();
                String mch_id = root.element("mch_id").getTextTrim();
                String nonce_str = root.element("nonce_str").getTextTrim();
                String sg = root.element("sign").getTextTrim(); //这里的签名是微信服务器给的,用来验证微信服务器的身份
                String result_code = root.element("result_code").getTextTrim();
                if(!WebUtil.checkEmpty(result_code) && result_code.equals("SUCCESS")){
                    LOG.info("微信统一下单业务成功!");
                    String trade_type = root.element("trade_type").getTextTrim();
                    String prepay_id = root.element("prepay_id").getTextTrim();
                    //生成终端需要的参数
                    String nStr = WebUtil.genNonceStr();
                    //String timeStamp = Long.toString(System.currentTimeMillis() / 1000);
                    LinkedHashMap sgParams = new LinkedHashMap();
                    sgParams.put("appId", WX_XCXUtil.APPID);
                    sgParams.put("&nonceStr", noncStr);
                    sgParams.put("&package", "prepay_id="+prepay_id);
                    sgParams.put("&signType", "MD5");
                    sgParams.put("&timeStamp", timestamp);
                    sgParams.put("&key", WeixinPay.key);
                    String sgStr = WeixinPay.generateSign(sgParams);
                    return "SUCCESS_" + prepay_id + "_" + noncStr + "_" + timestamp + "_" + sgStr+"_"+signature;
                }
                else if(!WebUtil.checkEmpty(result_code) && result_code.equals("FAIL")){
                    String err_code = root.element("err_code").getTextTrim();
                    String err_code_des = root.element("err_code_des").getTextTrim();
                    LOG.info("微信统一下单业务失败!"+ "错误代码:" + err_code + " 错误描述:" + err_code_des);
                    return "ERROR_" + "[error_code : " + err_code + "],[err_code_des : " + err_code_des + "]";
                }
            }
            else if(!WebUtil.checkEmpty(return_code) && return_code.equals("FAIL")){
                LOG.info("微信统一下单通信失败:" + root.element("return_msg").getTextTrim());
                return "ERROR_" + "微信统一下单通信失败:" + root.element("return_msg").getTextTrim();
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }



    public static String refund(String transaction_id,int total_fee,String basePath) throws Exception {
        LinkedHashMap<String, Object> params = new LinkedHashMap<String, Object>();

        String noncStr = WebUtil.genNonceStr();
        //组装生成签名需要的字段
        params.put("appid", WeixinPay.APPID);
        params.put("&mch_id",WeixinPay.MCH_ID);
        params.put("&nonce_str",noncStr);
        params.put("&op_user_id", WeixinPay.MCH_ID);
        params.put("&out_refund_no", transaction_id);
        params.put("&refund_fee", total_fee);
        params.put("&total_fee",total_fee);
        params.put("&transaction_id", transaction_id);
        //添加密钥key
        params.put("&key",WeixinPay.api_sec);
        //生成签名
        String sign = WeixinPay.generateSign(params);

        StringBuilder sb = new StringBuilder();
        sb.append("<xml>");
        sb.append("<appid>" + WeixinPay.APPID + "</appid>");
        sb.append("<mch_id>" + WeixinPay.MCH_ID + "</mch_id>");
        sb.append("<nonce_str>" + noncStr + "</nonce_str>");
        sb.append("<op_user_id>" + WeixinPay.MCH_ID + "</op_user_id>");
        sb.append("<out_refund_no>" + transaction_id + "</out_refund_no>");
        sb.append("<refund_fee>"+total_fee+"</refund_fee>");
        sb.append("<total_fee>"+ total_fee +"</total_fee>");
        sb.append("<transaction_id>"+ transaction_id +"</transaction_id>");
        sb.append("<sign>" + sign.toUpperCase() + "</sign>");
        sb.append("</xml>");


        KeyStore keyStore = KeyStore.getInstance("PKCS12");

        basePath = basePath.substring(1,basePath.indexOf(":")+1) + "/project/cenrt/apiclient_cert.p12";
        System.out.println("==="+basePath);
        FileInputStream instream = new FileInputStream(new File(basePath));
        //FileInputStream instream = new FileInputStream(new File("D:/project/cenrt/apiclient_cert.p12"));
        try {
            keyStore.load(instream, WeixinPay.MCH_ID.toCharArray());
        } finally {
            instream.close();
        }

        StringBuffer rezult = new StringBuffer();
        // Trust own CA and all self-signed certs
        SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, WeixinPay.MCH_ID.toCharArray()).build();
        // Allow TLSv1 protocol only
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslcontext,
                new String[] { "TLSv1" },
                null,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        try {

            HttpPost httpget = new HttpPost(WeixinPay.refund);
            StringEntity stringEntity = new StringEntity(sb.toString());
            httpget.setEntity(stringEntity);
            System.out.println("executing request" + httpget.getRequestLine());

            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                HttpEntity entity = response.getEntity();

                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                if (entity != null) {
                    System.out.println("Response content length: " + entity.getContentLength());
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
                    String text;
                    while ((text = bufferedReader.readLine()) != null) {
                        rezult.append(text);
                    }

                }
                EntityUtils.consume(entity);
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
        System.out.println(rezult.toString());
        String z = new String(rezult.toString().getBytes("GBK"), "UTF-8");
        Element root =  WebUtil.getXmlRoot(z);
        String return_code = root.element("return_code").getTextTrim();
        if(!WebUtil.checkEmpty(return_code) && return_code.equals("SUCCESS")) {
            LOG.info("微信退款接口通信成功!");
            String appid = root.element("appid").getTextTrim();
            String refund_id = root.element("refund_id").getTextTrim();
            System.out.println(refund_id);
            return "SUCCESS_"+refund_id;
        }else{
            return "FAIL_0";
        }

    }

    public static String refund_H5(String transaction_id,int total_fee,String basePath) throws Exception {
        LinkedHashMap<String, Object> params = new LinkedHashMap<String, Object>();

        String noncStr = WebUtil.genNonceStr();
        //组装生成签名需要的字段
        params.put("appid", WeixinPay.APPID_H5);
        params.put("&mch_id",WeixinPay.MCH_ID_H5);
        params.put("&nonce_str",noncStr);
        params.put("&op_user_id", WeixinPay.MCH_ID_H5);
        params.put("&out_refund_no",transaction_id );
        params.put("&refund_fee", total_fee);
        params.put("&total_fee",total_fee);
        params.put("&transaction_id", transaction_id);
        //添加密钥key
        params.put("&key",WeixinPay.key);
        //生成签名
        String sign = WeixinPay.generateSign(params);

        StringBuilder sb = new StringBuilder();
        sb.append("<xml>");
        sb.append("<appid>"+WeixinPay.APPID_H5+"</appid>");
        sb.append("<mch_id>"+WeixinPay.MCH_ID_H5+"</mch_id>");
        sb.append("<nonce_str>" + noncStr + "</nonce_str>");
        sb.append("<op_user_id>"+WeixinPay.MCH_ID_H5+"</op_user_id>");
        sb.append("<out_refund_no>"+transaction_id+"</out_refund_no>");
        sb.append("<refund_fee>"+total_fee+"</refund_fee>");
        sb.append("<total_fee>"+ total_fee +"</total_fee>");
        sb.append("<transaction_id>"+ transaction_id +"</transaction_id>");
        sb.append("<sign>" + sign.toUpperCase() + "</sign>");
        sb.append("</xml>");


        KeyStore keyStore  = KeyStore.getInstance("PKCS12");

        basePath = basePath.substring(1,basePath.indexOf(":")+1) + "/project/cenrt-H5/apiclient_cert.p12";
        System.out.println("==="+basePath);
        FileInputStream instream = new FileInputStream(new File(basePath));
        //FileInputStream instream = new FileInputStream(new File("D:/project/cenrt-H5/apiclient_cert.p12"));

        try {
            keyStore.load(instream, WeixinPay.MCH_ID_H5.toCharArray());
        } finally {
            instream.close();
        }

        StringBuffer rezult = new StringBuffer();
        // Trust own CA and all self-signed certs
        SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, WeixinPay.MCH_ID_H5.toCharArray()).build();
        // Allow TLSv1 protocol only
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslcontext,
                new String[] { "TLSv1" },
                null,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        try {

            HttpPost httpget = new HttpPost(WeixinPay.refund);
            StringEntity stringEntity = new StringEntity(sb.toString());
            httpget.setEntity(stringEntity);
            System.out.println("executing request" + httpget.getRequestLine());

            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                HttpEntity entity = response.getEntity();

                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                if (entity != null) {
                    System.out.println("Response content length: " + entity.getContentLength());
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
                    String text;
                    while ((text = bufferedReader.readLine()) != null) {
                        rezult.append(text);
                    }
                }
                EntityUtils.consume(entity);
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
        String b  = new String(rezult.toString().getBytes("GBK"),"UTF-8");
        System.out.println(b);

        Element root =  WebUtil.getXmlRoot(rezult.toString());
        String return_code = root.element("return_code").getTextTrim();
        if(!WebUtil.checkEmpty(return_code) && return_code.equals("SUCCESS")) {
            LOG.info("微信退款接口通信成功!");
            String appid = root.element("appid").getTextTrim();
            String refund_id = root.element("refund_id").getTextTrim();
            System.out.println(refund_id);
            return "SUCCESS_"+refund_id;
        }else{
            return "FAIL_0";
        }

    }



}

 

posted @ 2019-08-08 14:57  坠落凡尘的魔鬼  阅读(2467)  评论(0编辑  收藏  举报