86183
2022-09-09 0d999e33085c0a25c5525242748f6aa62a401159
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
package com.dsh.app.util.pay.wechat;
 
import com.dsh.app.util.DateTimeHelper;
import com.dsh.app.util.pay.config.Config;
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.*;
 
public class WXPayCommonUtil {
 
    public static String CreateNoncestr(int length) {
        String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        String res = "";
        for (int i = 0; i < length; i++) {
            Random rd = new Random();
            res += chars.indexOf(rd.nextInt(chars.length() - 1));
        }
        return res;
    }
 
    public static String CreateNoncestr() {
        String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        String res = "";
        for (int i = 0; i < 16; i++) {
            Random rd = new Random();
            res += chars.charAt(rd.nextInt(chars.length() - 1));
        }
        return res;
    }
 
 
    /**
     * 是否签名正确,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。
     *
     * @return boolean
     */
    public static boolean isTenpaySign(String characterEncoding, SortedMap<Object, Object> packageParams) {
        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=" + Config.WX_PAY_API_KEY);
 
        //算出摘要
        String mysign = WXMD5Util.MD5Encode(sb.toString(), characterEncoding).toLowerCase();
 
        String tenpaySign = ((String) packageParams.get("sign")).toLowerCase();
 
        return tenpaySign.equals(mysign);
    }
 
 
    /**
     * @param characterEncoding 编码格式
     * @param parameters        请求参数
     * @return
     * @Description:sign签名
     */
    public static String createSign(String characterEncoding, SortedMap<Object, Object> parameters) {
        StringBuffer sb = new StringBuffer();
        Set es = parameters.entrySet();
        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=" + Config.WX_PAY_API_KEY);
        String sign = WXMD5Util.MD5Encode(sb.toString(), "UTF-8").toUpperCase();
        return sign;
    }
 
    /**
     * @param parameters 请求参数
     * @return
     * @Description:将请求参数转换为xml格式的string
     */
    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)) {
                sb.append("<" + k + ">" + "<![CDATA[" + v + "]]></" + k + ">");
            } else {
                sb.append("<" + k + ">" + v + "</" + k + ">");
            }
        }
        sb.append("</xml>");
        return sb.toString();
    }
 
    /**
     * @param return_code 返回编码
     * @param return_msg  返回信息
     * @return
     * @Description:返回给微信的参数
     */
    public static String setXML(String return_code, String return_msg) {
 
 
        return "<xml><return_code><![CDATA[" + return_code
                + "]]></return_code><return_msg><![CDATA[" + return_msg
                + "]]></return_msg></xml>";
 
    }
 
 
    public static Map<String, String> decodeXml(String content) {
 
        Map<String, String> xml = new HashMap<String, String>();
        try {
            //创建一个SAXBuilder对象
            SAXBuilder saxBuilder = new SAXBuilder();
            byte[] bytes = content.getBytes("UTF-8");
            InputStream xmlInput = new ByteArrayInputStream(bytes);
            //读取prop.xml资源
            Document doc = saxBuilder.build(xmlInput);
            //获取根元素(prop)
            Element root = doc.getRootElement();
            //获取根元素下面的所有子元素(mess)
            List<Element> messList = root.getChildren();
            for (Element element : messList) {
                xml.put(element.getName(), element.getValue());
 
            }
        } catch (JDOMException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return xml;
    }
 
 
    public static SortedMap<Object, Object> appParam(String content) {
 
        String sign = "";
        Boolean status = false;
        SortedMap<Object, Object> params = new TreeMap<>();
        Map<String, String> maps = decodeXml(content);
        for (Map.Entry<String, String> item : maps.entrySet()) {
            if (item.getKey().equals("result_code") && item.getValue().equals("SUCCESS")) {
                status = true;
            }
            maps.put(item.getKey(), item.getValue());
            System.out.println(item.getKey() + "-------" + item.getValue());
        }
        if (status) {
            maps.remove("return_code");
            maps.remove("return_msg");
            maps.remove("result_code");
            maps.remove("sign");
            maps.remove("trade_type");
            maps.put("partnerid", maps.get("mch_id"));
            maps.remove("mch_id");
            maps.put("timestamp", DateTimeHelper.formatDateTimetoString(DateTimeHelper.getWXTime(), DateTimeHelper.FMT_yyyyMMddHH_noseparator));
            maps.put("package", "Sign=WXPay");//默认sign=WXPay
            maps.put("noncestr", maps.get("nonce_str"));
            maps.remove("nonce_str");
            maps.put("prepayid", maps.get("prepay_id"));
            maps.remove("prepay_id");
            params = new TreeMap<>(maps);
            String signAgain = WXPayCommonUtil.createSign("UTF-8", params);//再次生成签名
            System.out.println("+二次签名+" + signAgain);
            params.put("sign", signAgain);
        }
        return params;
    }
 
 
}