Java根据不同商户动态生成微信付款码(模式二),包括扫码支付成功页面跳转后台思路_浮萍游子的博客-程序员宅基地_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

智能推荐

json特殊符号 java_java json字符串传递给 js 时 特殊字符转义错误 研究_焦点交易的博客-程序员宅基地

一些换行 回车等符号需要转义主要注意 单引号 与双引号。一 如果js以 双引号接收字符串 则转单引号 " 至 \" 否则js报错二 如果js以 单引号接收字符串 则转单引号 ' 至 \'否则js报错不管哪种情况 字符串中原有\ 需替换 成 \\{"Aaa":0,"bbb":1,"ddd":"a哦我\"我'我'哇"}====》{\"Aaa\":0,\"bbb\":1,\"ddd\":\"a哦...

OpenCV-Python学习之路-10:Image Gradients(图像梯度)_我是大黄同学呀的博客-程序员宅基地

文章目录参考依据目标图像梯度1. Sobel和Scharr求导2. Laplacian求导参考依据官方文档:https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_gradients/py_gradients.html#gradients目标寻找图像中的梯度、检测边缘等学习到以下函数:cv2.Sobel()、cv2.Scharr()、cv2.Laplacian()等图像梯度Ope

细节改善效率:c++中map结构erase函数不同用法的效率差异_暴走孙悟空的博客-程序员宅基地

这篇博客对c++中map结构erase函数的不同用法进行效率对比测试。内附可编译通过的例程。

HDU 1824 Let's go home (2-SAT判定)_蘑菇小哲的博客-程序员宅基地

Let's go homeTime Limit: 10000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 1616    Accepted Submission(s): 661Problem Description小时候,乡愁是一枚小

大数据之Hive集群操作_小神龙q的博客-程序员宅基地

1 Hive 数据仓库实战1.1 实验背景Hive是重要的数据仓库工具,在数据挖掘、数据汇总、统计分析等领域有重要作用。特别的在电信业务中,Hive扮演相当重要的角色,可以利用Hive统计用户的流量、话费、资费等信息,也可挖掘出用户的消费模型以帮助运营商更好的规划套餐内容。1.2 实验目的 掌握Hive的常用操作。 学会在Hue上使用和运行HQL。1.3 实验任务1.3.1 Hi...

关于Android Studio中动画文件夹anim无法创建animation-list失效问题_帅气大果果的博客-程序员宅基地

之前用eclipse一般动画文件都是在res下创建一个anim文件夹,然后创建xml文件,选择animation-list标签。事实上这样写确实没毛病,但是如果在Android Studio这样写的话就会报错。解决问题是,Android Studio里如果想要创建animation-list标签的xmll文件的话需要在drwable文件夹下创建。 1,在res下的drawable文件夹上右键 –>

随便推点

算法竞赛入门经典第九章_HUGG_dajingzi的博客-程序员宅基地

例题9-1 城市里的间谍 UVa1025仿佛有固定终点的DP问题都是从终点开始,往起点规划的???#include&lt;bits/stdc++.h&gt;using namespace std;#define INF 0X3F3F3F3Fint main(){ int kase=0; int n,T,t[55],M1,r_begin,M2,l_begin; int t...

最新服务器测试方法详细解析_lxting21的博客-程序员宅基地_服务器测试

在我们平时的工作生活中,服务器的种类日益繁多,服务器检测方法更是各种各样。本文旨在给读者朋友们做最新的服务器测试方法的详细的介绍。在这里,服务器测试方法分为两个大方面,性能测试与功能测试。  我们在性能测试方面采用了新的测试方法,主要分为文件测试、数据库性能测试与Web性能测试三个方面。其中,文件性能与数据库性能采用美国Quest软件公司的Benchmark Factory负载测试和容量规

XML解析错误:未组织好 _siruoxian的博客-程序员宅基地

XML解析错误:未组织好 位置:http://localhost:8080/showad/showad.groovy?method=getAdData 行:1,列:619: &amp;lt;imageurl&amp;gt;- &amp;lt;![CDATA[ http://192.168.1.10//adsfile/icon.jpg  ]]&amp;gt;&amp;lt;script&amp;gt;&amp;lt;/scr...

利用Udig修改铁路样式为黑白相间_啧啧啧biubiu的博客-程序员宅基地_udig 铁路

1. 下载铁路样式的SLD文件https://www.cnblogs.com/wuhenke/archive/2010/09/14/1826264.html2.导入铁路图层到Udig3.将下载好的SLD文件中以下三个部分对应复制到Tie Lu polyline图层的XML中复制/覆盖4.实现结果...

python 爬虫请求模块requests_码农一号已就位的博客-程序员宅基地

文章目录requestsrequests安装requests库的基本使用响应对象response的⽅法状态码请求⽅式GET请求POST请求请求头requests设置代理cookiesession处理不信任的SSL证书requests相比urllib,第三方库requests更加简单人性化,是爬虫工作中常用的库requests安装初级爬虫的开始主要是使用requests模块安装requests模块:Windows系统:cmd中:pip install requestsmac系统中:终端中

数据密集型应用--0625--单机应用-数据基础_浅笑黄花伊人泪的博客-程序员宅基地

本书将是一趙关于数据系统原理、实践与应用的旅程,并讲述了设计数据密集型应用的方法。我们将探索不同工具之间的共性与特性,以及各自的实现原理。1:可靠、可扩展、可维护的数据系统应用同步数据到全文搜索引擎和缓存:可靠性(Reliability)系统在困境(adversity)(硬件故障、软件故障、人为错误)中仍可正常工作(正确完成功能,并能达到期望的性能水准)。如果所有这些在一起意味着“正确工作“,那么可以把可靠性粗略理解为即使岀现冋题,也能继续正确工作硬件故障...

推荐文章

热门文章

相关标签