Java根据不同商户动态生成微信付款码(模式二),包括扫码支付成功页面跳转后台思路

技术标签: Java微信支付  java微信扫码付款  微信扫码付款成功页面跳转  

Java根据不同商户动态生成微信付款码(模式二),包括扫码支付成功页面跳转后台思路

一、生成动态二维码

接受前台传来的必要参数,返回包括二维码短连接以及微信相关参数的实体

Controller

@RequestMapping("/getPayWxqrcode")
@ResponseBody
public URLCode wxqrcode(@RequestBody WxCusInfoBean wxCusInfoBean, 	 HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception{
    BigDecimal fen = wxCusInfoBean.getPayAmount().multiply(new BigDecimal(100));
    fen = fen.setScale(0, BigDecimal.ROUND_HALF_UP);
    String order_price = fen.toString();

    // 微信支交易订单号,不能重复
    String out_trade_no = wxCusInfoBean.getOrderId();

    // 组装参数
    Map<String, Object> param = new HashMap<>();
    param.put("order_price", order_price);
    param.put("body", wxCusInfoBean.getBody());
    param.put("out_trade_no", out_trade_no);
    param.put("attach", wxCusInfoBean.getOrderId());

    // 生成微信支付二维码链接
    Map<String, String> result = phoneOrderService.doUnifiedOrder(wxCusInfoBean,param, request);
    URLCode urlCode = new URLCode();
    if ("FAIL".equals(result.get("return_code"))){
        urlCode.setErorr("eroor");
        return urlCode;
        //session.setAttribute("create_wx_qrcode_error_msg",  result.get("return_msg"));
    } else {
        String urlcode = result.get("code_url");
        String prepay_id = result.get("prepay_id");
        urlCode.setPrepayId(prepay_id);
        urlCode.setUrlCode(urlcode);
        urlCode.setNonce_str(result.get("nonce_str"));
        urlCode.setSign(result.get("sign"));
        return urlCode;// 生成微信二维码

    }
}

Service

    @Override
public Map<String, String> doUnifiedOrder(WxCusInfoBean wxCusInfoBean, Map<String, Object> param, HttpServletRequest request) {
    String appid = wxCusInfoBean.getAppId();
    String mch_id = wxCusInfoBean.getMchId();
    String key = wxCusInfoBean.getApiKey();
    String trade_type = "NATIVE";
    String spbill_create_ip = PayCommonUtil.getIpAddress(request);      // 获取发起电脑 ip
    //String notify_url = PayConfigUtil.NOTIFY_URL+"?key="+wxCusInfoBean.getApiKey();                       // 回调接口
    String notify_url = PayConfigUtil.NOTIFY_URL;
    String currTime = PayCommonUtil.getCurrTime();
    String strTime = currTime.substring(8, currTime.length());
    String strRandom = PayCommonUtil.buildRandom(4) + "";
    String nonce_str = strTime + strRandom;                             // 随机字符串
    String order_price = (String) param.get("order_price");             // 价格   注意:价格的单位是分
    String body = (String) param.get("body");                           // 商品名称
    String out_trade_no = (String) param.get("out_trade_no");           // 订单号

    String attach = (String) param.get("attach");                       // 附加参数,这里传的是我们的订单号orderId

    SortedMap<Object, Object> packageParams = new TreeMap<>();
    packageParams.put("appid", appid);
    packageParams.put("mch_id", mch_id);
    packageParams.put("nonce_str", nonce_str);
    packageParams.put("body", body);
    packageParams.put("out_trade_no", out_trade_no);
    packageParams.put("total_fee", order_price);
    packageParams.put("spbill_create_ip", spbill_create_ip);
    packageParams.put("notify_url", notify_url);
    packageParams.put("trade_type", trade_type);
    packageParams.put("attach", attach);

    // 签名
    String sign = PayCommonUtil.createSign("UTF-8", packageParams, key);
    packageParams.put("sign", sign);
    // 微信支付接口传输数据使用xml方式进行的,此处将参数装换为xml
    // map --> xml
    String requestXML = PayCommonUtil.getRequestXml(packageParams);
    System.out.println("---------- Request XML: " + requestXML);
    String resXml = HttpUtil.postData(PayConfigUtil.UFDODER_URL, requestXML);
    System.out.println("---------- Response XML: " + resXml);

    // xml --> map
    try {
        return XMLUtil4jdom.doXMLParse(resXml);
    } catch (JDOMException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

二、微信自动回调接口

生成二维码之后,如果有人扫描二维码并支付成功,微信会回调下面的接口,当然回调地址需要自己配置,后面代码会展示(注意:回调地址必须在公网可访问),此回调接口可用来处理自己的业务逻辑,此接口我用来存储微信方生成的此笔交易订单号,为后面页面跳转做铺垫

Controller

@RequestMapping("/wxnotify")
@ResponseBody
public String wxnotify(HttpServletRequest request, HttpServletResponse response) throws Exception{
    String te = t1.get();
    //读取参数
    String str = "";
    InputStream inputStream ;
    StringBuffer sb = new StringBuffer();
    inputStream = request.getInputStream();
    String s ;
    BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
    while ((s = in.readLine()) != null){
        sb.append(s);
    }
    in.close();
    inputStream.close();
    //解析xml成map
    Map<String, String> m = new HashMap<String, String>();
    m = XMLUtil4jdom.doXMLParse(sb.toString());

    //过滤空 设置 TreeMap
    SortedMap<Object,Object> packageParams = new TreeMap<Object,Object>();
    Iterator it = m.keySet().iterator();
    while (it.hasNext()) {
        String parameter = (String) it.next();
        String parameterValue = m.get(parameter);

        String v = "";
        if(null != parameterValue) {
            v = parameterValue.trim();
        }
        packageParams.put(parameter, v);
    }
	//此处根据AppID换取商户的APIKey(已在数据库里存好),业务逻辑自己写即可
    String appid = (String)packageParams.get("appid");
    String key = phoneOrderService.getKeyByMchId(appid);
    System.out.println(key);
    //判断签名是否正确
    if(PayCommonUtil.isTenpaySign("UTF-8", packageParams,key)) {
        //------------------------------
        //处理业务开始
        //------------------------------
        String resXml = "";
        if("SUCCESS".equals((String)packageParams.get("result_code"))){
            // 这里是支付成功
            //执行自己的业务逻辑
            String mch_id = (String)packageParams.get("mch_id");
            String openid = (String)packageParams.get("openid");
            String is_subscribe = (String)packageParams.get("is_subscribe");
            String out_trade_no = (String)packageParams.get("out_trade_no");

            BigDecimal total_fee = new BigDecimal((String)packageParams.get("total_fee"));
            String transaction_id = (String)packageParams.get("transaction_id");
            String sydid = phoneOrderService.getSydIdByOid(out_trade_no);
            System.out.println("sydid+"+sydid);
            String hyjlId = phoneOrderService.getHyjlIdByOid(out_trade_no);
            System.out.println("hyjlid+"+hyjlId);
            if (sydid != null && !"".equals(sydid)) {
                System.out.println("执行修改收银单方法");
                phoneOrderService.updateSydTranId(transaction_id,out_trade_no);
            } else if(hyjlId != null && !"".equals(hyjlId)) {
                phoneOrderService.updateHyjlTranId(transaction_id,out_trade_no);
            }

            System.out.println("微信订单号="+transaction_id);

            //通知微信.异步确认成功.必写.不然会一直通知后台.八次之后就认为交易失败了.
            resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
                    + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
            str =  "支付成功"+total_fee+"元";
            System.out.println(str+"mch_id="+mch_id+"openid="+openid+"is_subscribe="+is_subscribe+"out_trade_no="+out_trade_no);

        } else {

            resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                    + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
            str =  "支付失败";
        }
        BufferedOutputStream out = new BufferedOutputStream(
                response.getOutputStream());
        out.write(resXml.getBytes());
        out.flush();
        out.close();
    } else{
        str = "验证签名失败";
    }
    System.out.println(str);
    return  str;
}

三、扫码支付成功之后商户系统实现页面跳转

此处我采用查询微信系统的订单状态来判断此单是否支付成功,具体操作为拿到前面存储的微信订单号去微信的统一订单查询地址:https://api.mch.weixin.qq.com/pay/orderquery 换取支付信息,当生成二维码时,前台便开始Ajax轮训下面的接口,直到返回成功支付停止轮训并跳页
Controller

@RequestMapping("/getOrderCode")
    @ResponseBody
    public returnOrderCode getOrderCode(@RequestBody getOrderCode getOrderCode){
    //查询存储的微信订单编号来查询订单状态
        String transaction_id = phoneOrderService.getTransactionIdBySydId(getOrderCode.getOrderId());
        String transaction_idCopy = phoneOrderService.getTransactionIdByHyjlId(getOrderCode.getOrderId());
        if(transaction_id != null && !"".equals(transaction_id)) {
            getOrderCode.setOrderId(transaction_id);
        } else if (transaction_idCopy != null && !"".equals(transaction_idCopy)) {
            getOrderCode.setOrderId(transaction_idCopy);
        }
        Map<String, String> result = phoneOrderService.getOrderCode(getOrderCode);
        String return_code = result.get("return_code");
        String return_msg = result.get("return_msg");
        String err_code = result.get("err_code");
        String err_code_des = result.get("err_code_des");
        String trade_state_desc = result.get("trade_state_desc");
        returnOrderCode returnOrderCode = new returnOrderCode();
        returnOrderCode.setErr_code(err_code);
        returnOrderCode.setErr_code_des(err_code_des);
        returnOrderCode.setReturn_code(return_code);
        returnOrderCode.setReturn_msg(return_msg);
        returnOrderCode.setTrade_state_desc(trade_state_desc);
        return returnOrderCode;
    }

Service

 @Override
    public Map<String, String> getOrderCode(getOrderCode getOrderCode) {
        String appid = getOrderCode.getAppId();
        String mch_id = getOrderCode.getMchId();
        String orderId = getOrderCode.getOrderId();
        String nonce_str = getOrderCode.getNonce_str();
        String sign = "";
        SortedMap<Object, Object> packageParams = new TreeMap<>();
        packageParams.put("appid", appid);
        packageParams.put("mch_id", mch_id);
        packageParams.put("nonce_str", nonce_str);
        packageParams.put("transaction_id", orderId);
        sign = PayCommonUtil.createSign("UTF-8", packageParams, getOrderCode.getApiKey());
        packageParams.put("sign", sign);
        String requestXML = PayCommonUtil.getRequestXml(packageParams);
        System.out.println("---------- Request XML: " + requestXML);
        String resXml = HttpUtil.postData(PayConfigUtil.WXORDER_URL, requestXML);
        System.out.println("---------- Response XML: " + resXml);

        // xml --> map
        try {
            return XMLUtil4jdom.doXMLParse(resXml);
        } catch (JDOMException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

涉及到的实体类与工具类

PayConfigUtil

package com.sj.Utils;

public class PayConfigUtil {

    // 支付成功回调接口,我们在WXPayController中编写的回调接口的公网地址


    public static final String NOTIFY_URL = "http://***/PhoneOrder/wxnotify";

    public static final String UFDODER_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";

    //微信查询地址
    public  static final String WXORDER_URL="https://api.mch.weixin.qq.com/pay/orderquery";
}

PayCommonUtil

package com.sj.Utils;

import javax.servlet.http.HttpServletRequest;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.*;

public class PayCommonUtil {

    /**
     * @Description:将请求参数转换为xml格式的string
     * @param parameters
     *            请求参数
     * @return
     */
    public static String getRequestXml(SortedMap<Object, Object> parameters) {
        StringBuffer sb = new StringBuffer();
        sb.append("<xml>");
        Set es = parameters.entrySet();
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            String v = (String) entry.getValue();
            if ("attach".equalsIgnoreCase(k) || "body".equalsIgnoreCase(k) || "sign".equalsIgnoreCase(k)) {
                sb.append("<" + k + ">" + "<![CDATA[" + v + "]]></" + k + ">");
            } else {
                sb.append("<" + k + ">" + v + "</" + k + ">");
            }
        }
        sb.append("</xml>");
        return sb.toString();
    }
    /**
     * 微信支付签名算法sign
     * @param characterEncoding
     * @param parameters
     * @return
     */
    @SuppressWarnings("unchecked")
    public static String createSign(String characterEncoding, SortedMap<Object,Object> parameters, String API_KEY){

        StringBuffer sb = new StringBuffer();
        Set es = parameters.entrySet();//所有参与传参的参数按照accsii排序(升序)
        Iterator it = es.iterator();
        while(it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            String k = (String)entry.getKey();
            Object v = entry.getValue();
            if(null != v && !"".equals(v)
                    && !"sign".equals(k) && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }
        sb.append("key=" + API_KEY);
        String sign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toUpperCase();

        return sign;
    }
    /**
     * 获取当前时间 yyyyMMddHHmmss
     *
     * @return String
     */
    public static String getCurrTime() {
        Date now = new Date();
        SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String s = outFormat.format(now);
        return s;
    }

    /**
     * 取出一个指定长度大小的随机正整数.
     *
     * @param length
     *            int 设定所取出随机数的长度。length小于11
     * @return int 返回生成的随机数。
     */
    public static int buildRandom(int length) {
        int num = 1;
        double random = Math.random();
        if (random < 0.1) {
            random = random + 0.1;
        }
        for (int i = 0; i < length; i++) {
            num = num * 10;
        }
        return (int) ((random * num));
    }

    /**
     * 获取IP地址
     *
     * @param request
     * @return
     */
    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }



    /**
     * 是否签名正确,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。
     * @return boolean
     */
    public static boolean isTenpaySign(String characterEncoding, SortedMap<Object, Object> packageParams, String API_KEY) {
        StringBuffer sb = new StringBuffer();
        Set es = packageParams.entrySet();
        Iterator it = es.iterator();
        while(it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            String k = (String)entry.getKey();
            String v = (String)entry.getValue();
            if(!"sign".equals(k) && null != v && !"".equals(v)) {
                sb.append(k + "=" + v + "&");
            }
        }

        sb.append("key=" + API_KEY);

        //算出摘要
        String mysign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toLowerCase();
        String tenpaySign = ((String)packageParams.get("sign")).toLowerCase();

        //System.out.println(tenpaySign + "    " + mysign);
        return tenpaySign.equals(mysign);
    }

    private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
}


MD5Util

package com.sj.Utils;

import java.security.MessageDigest;

public class MD5Util {
    private static String byteArrayToHexString(byte b[]) {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; i++)
            resultSb.append(byteToHexString(b[i]));

        return resultSb.toString();
    }

    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0)
            n += 256;
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }

    public static String MD5Encode(String origin, String charsetname) {
        String resultString = null;
        try {
            resultString = new String(origin);
            MessageDigest md = MessageDigest.getInstance("MD5");
            if (charsetname == null || "".equals(charsetname))
                resultString = byteArrayToHexString(md.digest(resultString
                        .getBytes()));
            else
                resultString = byteArrayToHexString(md.digest(resultString
                        .getBytes(charsetname)));
        } catch (Exception exception) {
        }
        return resultString;
    }

    private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

}

HttpUtil

package com.sj.Utils;

import sun.rmi.runtime.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;

public class HttpUtil {
    private final static int CONNECT_TIMEOUT = 5000; // in milliseconds
    private final static String DEFAULT_ENCODING = "UTF-8";

    public static String postData(String urlStr, String data){
        return postData(urlStr, data, null);
    }

    public static String postData(String urlStr, String data, String contentType){
        BufferedReader reader = null;
        try {
            URL url = new URL(urlStr);
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            conn.setConnectTimeout(CONNECT_TIMEOUT);
            conn.setReadTimeout(CONNECT_TIMEOUT);
            if(contentType != null)
                conn.setRequestProperty("content-type", contentType);
            OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), DEFAULT_ENCODING);
            if(data == null)
                data = "";
            writer.write(data);
            writer.flush();
            writer.close();

            reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), DEFAULT_ENCODING));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
                sb.append("\r\n");
            }
            return sb.toString();
        } catch (IOException e) {
            return  "eroor";
        } finally {
            try {
                if (reader != null)
                    reader.close();
            } catch (IOException e) {
            }
        }
    }
}

PayCommonUtil

package com.sj.Utils;

import javax.servlet.http.HttpServletRequest;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.*;

public class PayCommonUtil {

    /**
     * @Description:将请求参数转换为xml格式的string
     * @param parameters
     *            请求参数
     * @return
     */
    public static String getRequestXml(SortedMap<Object, Object> parameters) {
        StringBuffer sb = new StringBuffer();
        sb.append("<xml>");
        Set es = parameters.entrySet();
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            String v = (String) entry.getValue();
            if ("attach".equalsIgnoreCase(k) || "body".equalsIgnoreCase(k) || "sign".equalsIgnoreCase(k)) {
                sb.append("<" + k + ">" + "<![CDATA[" + v + "]]></" + k + ">");
            } else {
                sb.append("<" + k + ">" + v + "</" + k + ">");
            }
        }
        sb.append("</xml>");
        return sb.toString();
    }
    /**
     * 微信支付签名算法sign
     * @param characterEncoding
     * @param parameters
     * @return
     */
    @SuppressWarnings("unchecked")
    public static String createSign(String characterEncoding, SortedMap<Object,Object> parameters, String API_KEY){

        StringBuffer sb = new StringBuffer();
        Set es = parameters.entrySet();//所有参与传参的参数按照accsii排序(升序)
        Iterator it = es.iterator();
        while(it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            String k = (String)entry.getKey();
            Object v = entry.getValue();
            if(null != v && !"".equals(v)
                    && !"sign".equals(k) && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }
        sb.append("key=" + API_KEY);
        String sign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toUpperCase();

        return sign;
    }
    /**
     * 获取当前时间 yyyyMMddHHmmss
     *
     * @return String
     */
    public static String getCurrTime() {
        Date now = new Date();
        SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String s = outFormat.format(now);
        return s;
    }

    /**
     * 取出一个指定长度大小的随机正整数.
     *
     * @param length
     *            int 设定所取出随机数的长度。length小于11
     * @return int 返回生成的随机数。
     */
    public static int buildRandom(int length) {
        int num = 1;
        double random = Math.random();
        if (random < 0.1) {
            random = random + 0.1;
        }
        for (int i = 0; i < length; i++) {
            num = num * 10;
        }
        return (int) ((random * num));
    }

    /**
     * 获取IP地址
     *
     * @param request
     * @return
     */
    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }



    /**
     * 是否签名正确,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。
     * @return boolean
     */
    public static boolean isTenpaySign(String characterEncoding, SortedMap<Object, Object> packageParams, String API_KEY) {
        StringBuffer sb = new StringBuffer();
        Set es = packageParams.entrySet();
        Iterator it = es.iterator();
        while(it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            String k = (String)entry.getKey();
            String v = (String)entry.getValue();
            if(!"sign".equals(k) && null != v && !"".equals(v)) {
                sb.append(k + "=" + v + "&");
            }
        }

        sb.append("key=" + API_KEY);

        //算出摘要
        String mysign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toLowerCase();
        String tenpaySign = ((String)packageParams.get("sign")).toLowerCase();

        //System.out.println(tenpaySign + "    " + mysign);
        return tenpaySign.equals(mysign);
    }

    private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
}


XMLUtil4jdom

package com.sj.Utils;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class XMLUtil4jdom {
    /**
     * 解析xml,返回第一级元素键值对。如果第一级元素有子节点,则此节点的值是子节点的xml数据。
     * @param strxml
     * @return
     * @throws JDOMException
     * @throws IOException
     */
    public static Map doXMLParse(String strxml) throws JDOMException, IOException {
        strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");

        if(null == strxml || "".equals(strxml)) {
            return null;
        }

        Map<String, String> m = new HashMap<String, String>();
        InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(in);
        Element root = doc.getRootElement();
        List list = root.getChildren();
        Iterator it = list.iterator();
        while(it.hasNext()) {
            Element e = (Element) it.next();
            String k = e.getName();
            String v = "";
            List children = e.getChildren();
            if(children.isEmpty()) {
                v = e.getTextNormalize();
            } else {
                v = XMLUtil4jdom.getChildrenText(children);
            }

            m.put(k, v);
        }

        //关闭流
        in.close();

        return m;
    }

    /**
     * 获取子结点的xml
     * @param children
     * @return String
     */
    public static String getChildrenText(List children) {
        StringBuffer sb = new StringBuffer();
        if(!children.isEmpty()) {
            Iterator it = children.iterator();
            while(it.hasNext()) {
                Element e = (Element) it.next();
                String name = e.getName();
                String value = e.getTextNormalize();
                List list = e.getChildren();
                sb.append("<" + name + ">");
                if(!list.isEmpty()) {
                    sb.append(XMLUtil4jdom.getChildrenText(list));
                }
                sb.append(value);
                sb.append("</" + name + ">");
            }
        }

        return sb.toString();
    }

}

WxCusInfoBean

package com.sj.bean;

import java.math.BigDecimal;

public class WxCusInfoBean {
    private String appId;
    private String apiKey;//密匙
    private String orderId;
    private BigDecimal payAmount;//钱
    private  String body;//支付标语
    private String mchId;

    public String getMchId() {
        return mchId;
    }

    public void setMchId(String mchId) {
        this.mchId = mchId;
    }

    public String getAppId() {
        return appId;
    }

    public void setAppId(String appId) {
        this.appId = appId;
    }

    public String getApiKey() {
        return apiKey;
    }

    public void setApiKey(String apiKey) {
        this.apiKey = apiKey;
    }

    public BigDecimal getPayAmount() {
        return payAmount;
    }

    public void setPayAmount(BigDecimal payAmount) {
        this.payAmount = payAmount;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }



    public String getOrderId() {
        return orderId;
    }

    public void setOrderId(String orderId) {
        this.orderId = orderId;
    }
}

URLCode

package com.sj.bean;

public class URLCode {
    private String urlCode;
    private String Erorr;
    private  String prepayId;
    private String nonce_str;
    private String sign;

    public String getNonce_str() {
        return nonce_str;
    }

    public void setNonce_str(String nonce_str) {
        this.nonce_str = nonce_str;
    }

    public String getSign() {
        return sign;
    }

    public void setSign(String sign) {
        this.sign = sign;
    }

    public String getUrlCode() {
        return urlCode;
    }

    public void setUrlCode(String urlCode) {
        this.urlCode = urlCode;
    }

    public String getErorr() {
        return Erorr;
    }

    public void setErorr(String erorr) {
        Erorr = erorr;
    }

    public String getPrepayId() {
        return prepayId;
    }

    public void setPrepayId(String prepayId) {
        this.prepayId = prepayId;
    }
}

getOrderCode

package com.sj.model;

public class getOrderCode {
    private String nonce_str;
    private String sign;
    private String appId;
    private String orderId;
    private String mchId;
    private String apiKey;

    public String getApiKey() {
        return apiKey;
    }

    public void setApiKey(String apiKey) {
        this.apiKey = apiKey;
    }

    public String getNonce_str() {
        return nonce_str;
    }

    public void setNonce_str(String nonce_str) {
        this.nonce_str = nonce_str;
    }

    public String getSign() {
        return sign;
    }

    public void setSign(String sign) {
        this.sign = sign;
    }

    public String getAppId() {
        return appId;
    }

    public void setAppId(String appId) {
        this.appId = appId;
    }

    public String getOrderId() {
        return orderId;
    }

    public void setOrderId(String orderId) {
        this.orderId = orderId;
    }

    public String getMchId() {
        return mchId;
    }

    public void setMchId(String mchId) {
        this.mchId = mchId;
    }
}

returnOrderCode

package com.sj.bean;

public class returnOrderCode {
    private String return_code;
    private String return_msg;
    private String err_code;
    private  String err_code_des;
    private String trade_state_desc;

    public String getTrade_state_desc() {
        return trade_state_desc;
    }

    public void setTrade_state_desc(String trade_state_desc) {
        this.trade_state_desc = trade_state_desc;
    }

    public String getReturn_code() {
        return return_code;
    }

    public void setReturn_code(String return_code) {
        this.return_code = return_code;
    }

    public String getReturn_msg() {
        return return_msg;
    }

    public void setReturn_msg(String return_msg) {
        this.return_msg = return_msg;
    }

    public String getErr_code() {
        return err_code;
    }

    public void setErr_code(String err_code) {
        this.err_code = err_code;
    }

    public String getErr_code_des() {
        return err_code_des;
    }

    public void setErr_code_des(String err_code_des) {
        this.err_code_des = err_code_des;
    }
}

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_39891166/article/details/86217720

智能推荐

gre sub 计算机,GRE Sub和留学的关系,你知道多少?_郑佩珊的博客-程序员宅基地

原标题:GRE Sub和留学的关系,你知道多少?很多出国留学的小伙伴们都知道,TOEFL是必须要准备的英语能力方面的语言测试,GRE是大多数专业研究生入学考试,是每个人都无法逃脱的(除非你在英语国家学习过两年,部分学校可以免托)。那么你对GRE Sub了解多少呢?它和留学申请有什么关系呢?说实话,如果不是专门去了解,估计很多刚开始准备留学的学生们,还是很模糊的。现在就小侃让来给你科普一下吧。 其实...

[Android阅读代码]圆形旋转菜单CircleMenu_weixin_34092455的博客-程序员宅基地

项目名称:圆形旋转菜单CircleMenu原版项目代码下载感谢原作者开源转载于:https://www.cnblogs.com/hellenism/p/3623791.html

linux命令数据库别名查看,linux newaliases命令参数及用法详解--linux初始化别名数据库..._甜品专家的博客-程序员宅基地

名称:aliases.html' target='_blank'&gt;newaliases使用权限:系统管理者使用方式:newaliases说明:关于aliassendmail在/etc下有两个文件 aliases和aliases.db, 后者是前者用newaliases 生成的别名数据库. 你可以手工编辑/etc/aliases, 然后运行newaliases更新数据 库(其实newalia...

服务器系统开启休眠,Ubuntu系统启动休眠及无法唤醒问题的解决_健康和谐男哥的博客-程序员宅基地

大家都知道 Windows 有休眠模式,其实 Ubuntu 也有。休眠模式简单来说,就是可以在用户暂时离开时将内存中的所有内容都写入到硬盘当中,当用户下次开机时,就可以直接启动到上次保存的时间状态。打个比方,你正用 LibreOffice 在处理一个文档,同时打开了很多参考网页和其它文件,下班时间到了,你怕第二天回来再去找那些参考网页和文件等会影响你的写作思路,现在就可以在离开时将 Ubuntu ...

python一般用什么框架_python爬虫一般用什么框架?六大Python框架_心在指引方向的博客-程序员宅基地

python爬虫一般用什么框架?python爬虫可以使用的框架有很多,一般在大型需求的时候才会使用python爬虫框架。Scrapy:一个为了爬取网站数据,提取结构性数据而编写的应用框架。应用在数据挖掘、信息处理或者存储历史数据等一系列程序中。是很强大的爬虫框架,可以满足简单的页面爬取。Crawley:高速爬取对应网站内容,支持关系和非关系数据库,数据可以导出为JSON、XML等。Portia:开...

HALC: High throughput algorithm for long read error correction_wangchuang2017的博客-程序员宅基地

Journal|[J]BMC BioinformaticsVolume 18, Issue 1. 2017.HALC: High throughput algorithm for long read error correction作者:Ergude Bao;Lingxiao Lan作者背景:School of Software Engineering, Beijing Jiaotong University;University of California, RiversideDO...

随便推点

php获取文本框里面的数字,php – 仅在我的文本框中验证数字和字母_泰国旅行的博客-程序员宅基地

愉快的一天每个人..我在我的php文件中有这个java脚本代码,其中我使用它作为我的验证器…在我的文本框中的不同字段中的输入…我唯一的问题是我不知道如何创建验证只接受信件…在我的名字和姓氏字段…期待任何帮助感谢有一个美好的一天…我也想知道如何只在我的领域接受数字超级谢谢^^,这是代码:$(document).ready(function(){$('#employee_form').validate...

Cannot find class 'org.junit.Test' on project build path_暗冥惑的博客-程序员宅基地

Cannot find class 'org.junit.Test' on project build pathRight Click on project > Properties > Java Build Path > LibrariesIs JUnit4 included there? Is anything JUnit related there? If JUn

window下安装oracle_不懂技术的雷的博客-程序员宅基地

1 先打开官网https://www.oracle.com/index.html2 选择oracle database3 download4选择合适的版本下载 我这里下载的是window645如果没登陆账号要先注册登陆6解压结构如下:7点击setup.exe进行安装8 一步一步安装即可9 安装 要等一会10可以看到安装成功了...

SpringMVC国际化_mytt_10566的博客-程序员宅基地

Spring MVC国际化是建立在Java国际化的基础之上的,也是通过提供不同国家语言环境的消息资源,然后通过java.util.ResourceBundle加载指定Locale对应的资源文件,再取得该资源文件中指定key对应的内容。SpringMVC国际化执行步骤:给系统加载国际化资源文件输出国际化(两种方式)方式一:在视图页面输出国际化信息,使用Spring MVC标签库:

acm学习总结_夜雨声訉的博客-程序员宅基地

今天也是做了老师发的题全程划水对着题目发呆题意也不理解看来英语还是太弱了算法的题目也训练的太少了,发现自己太弱了和本人的差距不是一星半点,对于那种别人在那里一直出题自己就愣在那那种感觉很难受,明天继续洛谷做题做好总结。继续努力!...

android 传感器坐标系_关于Android 传感器坐标与读数的进一步讨论_Asama浅间的博客-程序员宅基地

关于Android 传感器坐标与读数的进一步讨论之前一些相关的讨论见:传感器分类总体来说,传感器分为运动传感器和位置传感器两种。(此处忽略了一些温度、光照等环境传感器)。运动传感器用来监测设备的运动,比如倾斜、震动和摇摆。运动传感器包括:加速度计、陀螺仪、重力感应器、线性加速度计、旋转向量传感器。位置传感器用来监测设备的位置,即相对于世界坐标系的位置。包括地磁场传感器、接近传感器和方向传感器。(方...

推荐文章

热门文章

相关标签