无关风月
4 天以前 74f666605450658b86e1b5ca076500aa341b6f49
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
package com.ruoyi.other.util.payment;
 
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.other.util.UUIDUtil;
import com.ruoyi.other.util.payment.model.*;
import lombok.extern.slf4j.Slf4j;
 
import java.math.BigDecimal;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.*;
 
/**
 * 支付工具类
 * @author zhibing.pu
 * @Date 2024/12/27 17:00
 */
@Slf4j
public class PaymentUtil {
 
    //微信公众号、微信小程序、微信 APP+/H5、云微小程序支付
    private static final String appId = "wx049faf9c5234f31c";
    /**
     * 商户密钥
     */
    private static final String key = "ss369875124965782f148539657826321";
    /**
     * 商户号
     */
    private static final String merchantNo = "1717539630";
    /**
     * 平台-报备商户号
     */
    private static final String sysTradeMerchantNo = "";
    /**
     * 支付回调地址
     */
    private static final String callbackUrl = "https://221.182.45.100:8084";
    
    
    /**
     * 支付
     * @param orderNo           商户订单号
     * @param amount            订单金额
     * @param productName       商品名称
     * @param productDesc       商品描述
     * @param mp                公用回传参数
     * @param notifyUrl         服务器异步通知地址
     * @param openId            微信 Openid
     * @param tradeMerchantNo   报备商户号
     * @return
     */
    public static UniPayResult uniPay(String orderNo, Double amount, String productName, String productDesc, String mp, String notifyUrl, String openId, String tradeMerchantNo){
        String url = "https://trade.joinpay.com/tradeRt/uniPay";
        HttpRequest post = HttpUtil.createPost(url);
        post.header(Header.CONTENT_TYPE, "application/x-www-form-urlencoded");
        JSONObject body = new JSONObject();
        //版本号
        body.put("p0_Version", "2.5");
        //商户编号
        body.put("p1_MerchantNo", merchantNo);
        //商户订单号
        body.put("p2_OrderNo", orderNo);
        //订单金额
        body.put("p3_Amount", amount);
        //交易币种
        body.put("p4_Cur", "1");
        //商品名称
        body.put("p5_ProductName", productName);
        //商品描述
        body.put("p6_ProductDesc", productDesc);
        //公用回传参数
        body.put("p7_Mp", mp);
        //服务器异步通知地址
        body.put("p9_NotifyUrl", callbackUrl + notifyUrl);
        //交易类型
        body.put("q1_FrpCode", FrpCodeEnum.WEIXIN_XCX.getCode());
        //微信 Openid
        body.put("q5_OpenId", openId);
        //APPID
        body.put("q7_AppId", appId);
        //报备商户号
        body.put("qa_TradeMerchantNo", StringUtils.isNotEmpty(tradeMerchantNo) ? tradeMerchantNo : sysTradeMerchantNo);
        String sign = null;
        try {
            sign = sign(body);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        body.put("hmac", sign);
        post.form(body);
        log.info("支付接口请求参数:" + body);
        HttpResponse execute = post.execute();
        log.info("支付接口请求响应:" + execute.body());
        if(200 != execute.getStatus()){
            log.error("支付接口异常:" + execute.body());
            return null;
        }
        UniPayResult uniPayResult = JSON.parseObject(execute.body(), UniPayResult.class);
        return uniPayResult;
    }
    /**
     * native支付
     * @param orderNo           商户订单号
     * @param amount            订单金额
     * @param notifyUrl         服务器异步通知地址
     * @return
     */
    public static String nativePay(String orderNo, BigDecimal amount, String notifyUrl) throws Exception {
        int totalFee = amount.multiply(new BigDecimal("100")).intValue();
 
        String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
 
        // 构建 XML 请求体
        Map<String, Object> params = new HashMap<>();
        params.put("appid", appId);
        params.put("mch_id", merchantNo);
        params.put("nonce_str", UUIDUtil.getRandomCode(16));
        params.put("body", "积分充值");
        params.put("out_trade_no", orderNo);
        params.put("total_fee", totalFee);
//        params.put("spbill_create_ip", InetAddress.getLocalHost().getHostAddress());
        params.put("spbill_create_ip", "221.182.45.100");
        params.put("notify_url", "https://221.182.45.100:8084/undif");
        params.put("trade_type", "NATIVE");
        params.put("product_id", "1");
 
        String sign = sign1(JSONObject.from(params)); // 使用原来的 sign 方法
        params.put("sign", sign);
 
        String xmlBody = mapToXml(params); // 转换为 XML 字符串
 
        // 发送请求
        HttpRequest post = HttpUtil.createPost(url);
        post.header(Header.CONTENT_TYPE, "application/xml");
        post.body(xmlBody); // 发送原始 XML 字符串
 
        log.info("Native支付接口请求参数:" + xmlBody);
        HttpResponse execute = post.execute();
        log.info("Native支付接口请求响应:" + execute.body());
 
        if (execute.getStatus() != 200) {
            log.error("Native支付接口异常:" + execute.body());
            return null;
        }
        return execute.body();
    }
    private static String mapToXml(Map<String, Object> map) {
        StringBuilder sb = new StringBuilder();
        sb.append("<xml>");
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            if (value != null && !value.toString().isEmpty()) {
                sb.append("<").append(key).append(">");
                sb.append(value);
                sb.append("</").append(key).append(">");
            }
        }
        sb.append("</xml>");
        return sb.toString();
    }
    public static String sign1(JSONObject body) {
        Set<Map.Entry<String, Object>> entries = body.entrySet();
        List<Map.Entry<String, Object>> infoIds = new ArrayList<>(entries);
 
        // 排除 sign 字段本身
        infoIds.removeIf(entry -> "sign".equals(entry.getKey()));
 
        // 按 ASCII 顺序排序
        infoIds.sort(Map.Entry.comparingByKey());
 
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, Object> entry : infoIds) {
            Object val = entry.getValue();
            if (val != null && !val.toString().trim().isEmpty()) {
                sb.append(entry.getKey()).append("=").append(val).append("&");
            }
        }
 
        // 最后拼接 &key=商户密钥
        sb.append("key=").append(key);
 
        String stringSignTemp = sb.toString();
        log.info("待签名串:{}", stringSignTemp);
 
        // 使用 MD5 加密
        return MD5AndKL.MD5(stringSignTemp);
    }
 
    /**
     * 微信下单的签名算法
     *
     * @param map
     * @return
     */
    private String weixinSignature(Map<String, Object> map) {
        try {
            Set<Map.Entry<String, Object>> entries = map.entrySet();
            List<Map.Entry<String, Object>> infoIds = new ArrayList<Map.Entry<String, Object>>(entries);
            // 对所有传入参数按照字段名的 ASCII 码从小到大排序(字典序)
            Collections.sort(infoIds, new Comparator<Map.Entry<String, Object>>() {
                public int compare(Map.Entry<String, Object> o1, Map.Entry<String, Object> o2) {
                    return (o1.getKey()).toString().compareTo(o2.getKey());
                }
            });
            // 构造签名键值对的格式
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, Object> item : infoIds) {
                if (item.getKey() != null || item.getKey() != "") {
                    String key = item.getKey();
                    Object val = item.getValue();
                    if (!(val == "" || val == null)) {
                        sb.append(key + "=" + val + "&");
                    }
                }
            }
            sb.append("key=" + key);
            String sign = MD5AndKL.MD5Encode(sb.toString(), "UTF-8").toUpperCase(); //注:MD5签名方式
            return sign;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public static void main(String[] args) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String code = sdf.format(new Date()) + UUIDUtil.getNumberRandom(5);
        String string = PaymentUtil.nativePay(code,new BigDecimal("0.1"),
                "/test"
        );
        System.err.println(string);
    }
    /**
     * 查询支付订单
     * @param orderNo   订单号
     * @return
     */
    public static QueryOrderResult queryOrder(String orderNo){
        String url = "https://trade.joinpay.com/tradeRt/queryOrder";
        HttpRequest post = HttpUtil.createPost(url);
        post.header(Header.CONTENT_TYPE, "application/x-www-form-urlencoded");
        JSONObject body = new JSONObject();
        //版本号
        body.put("p0_Version", "2.5");
        //商户编号
        body.put("p1_MerchantNo", merchantNo);
        //商户订单号
        body.put("p2_OrderNo", orderNo);
        String sign = null;
        try {
            sign = sign(body);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        body.put("hmac", sign);
        post.form(body);
        log.info("查询支付接口请求参数:" + body);
        HttpResponse execute = post.execute();
        log.info("查询支付接口请求响应:" + execute.body());
        if(200 != execute.getStatus()){
            log.error("查询支付接口异常:" + execute.body());
            return null;
        }
        QueryOrderResult uniPayResult = JSON.parseObject(execute.body(), QueryOrderResult.class);
        return uniPayResult;
    }
    
    
    /**
     * 退款
     * @param orderNo           支付订单号
     * @param refundOrderNo     退款订单号
     * @param refundAmount      退款金额
     * @param notifyUrl         异步通知地址
     * @return
     */
    public static RefundResult refund(String orderNo, String refundOrderNo, Double refundAmount, String notifyUrl){
        String url = "https://trade.joinpay.com/tradeRt/refund";
        HttpRequest post = HttpUtil.createPost(url);
        post.header(Header.CONTENT_TYPE, "application/x-www-form-urlencoded");
        JSONObject body = new JSONObject();
        //版本号
        body.put("p0_Version", "2.3");
        //商户编号
        body.put("p1_MerchantNo", merchantNo);
        //商户订单号
        body.put("p2_OrderNo", orderNo);
        //商户退款订单号
        body.put("p3_RefundOrderNo", refundOrderNo);
        //退款金额
        body.put("p4_RefundAmount", refundAmount);
        //服务器异步通知地址
        body.put("p6_NotifyUrl", notifyUrl);
        String sign = null;
        try {
            sign = sign(body);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        body.put("hmac", sign);
        post.form(body);
        log.info("退款接口请求参数:" + body);
        HttpResponse execute = post.execute();
        log.info("退款接口请求响应:" + execute.body());
        if(200 != execute.getStatus()){
            log.error("退款接口异常:" + execute.body());
            return null;
        }
        RefundResult uniPayResult = JSON.parseObject(execute.body(), RefundResult.class);
        return uniPayResult;
    }
    
    
    /**
     * 查询退款订单
     * @param refundOrderNo 退款订单号
     * @return
     */
    public static QueryRefundResult queryRefund(String refundOrderNo){
        String url = "https://trade.joinpay.com/tradeRt/refund";
        HttpRequest post = HttpUtil.createPost(url);
        post.header(Header.CONTENT_TYPE, "application/x-www-form-urlencoded");
        JSONObject body = new JSONObject();
        //版本号
        body.put("p0_Version", "2.3");
        //商户编号
        body.put("p1_MerchantNo", merchantNo);
        //商户退款订单号
        body.put("p2_RefundOrderNo", refundOrderNo);
        String sign = null;
        try {
            sign = sign(body);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        body.put("hmac", sign);
        post.form(body);
        log.info("退款接口请求参数:" + body);
        HttpResponse execute = post.execute();
        log.info("退款接口请求响应:" + execute.body());
        if(200 != execute.getStatus()){
            log.error("退款接口异常:" + execute.body());
            return null;
        }
        QueryRefundResult uniPayResult = JSON.parseObject(execute.body(), QueryRefundResult.class);
        return uniPayResult;
    }
    
    
    /**
     * 关闭订单(仅支持微信和支付宝)
     * @param orderNo   订单号
     * @return
     */
    public static CloseOrderResult closeOrder(String orderNo){
        String url = "https://www.joinpay.com/trade/closeOrder.action";
        HttpRequest post = HttpUtil.createPost(url);
        post.header(Header.CONTENT_TYPE, "application/x-www-form-urlencoded");
        JSONObject body = new JSONObject();
        //商户编号
        body.put("p1_MerchantNo", merchantNo);
        //商户订单号
        body.put("p2_OrderNo", orderNo);
        //交易类型
        body.put("p3_FrpCode", FrpCodeEnum.WEIXIN_XCX.getCode());
        String sign = null;
        try {
            sign = sign(body);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        body.put("hmac", sign);
        post.form(body);
        log.info("关闭订单接口请求参数:" + body);
        HttpResponse execute = post.execute();
        log.info("关闭订单接口请求响应:" + execute.body());
        if(200 != execute.getStatus()){
            log.error("关闭订单接口异常:" + execute.body());
            return null;
        }
        CloseOrderResult uniPayResult = JSON.parseObject(execute.body(), CloseOrderResult.class);
        return uniPayResult;
    }
    
    
    
    public static String sign(JSONObject body) {
        Set<Map.Entry<String, Object>> entries = body.entrySet();
        List<Map.Entry<String, Object>> infoIds = new ArrayList<Map.Entry<String, Object>>(entries);
        // 对所有传入参数按照字段名的 ASCII 码从小到大排序(字典序)
        Collections.sort(infoIds, new Comparator<Map.Entry<String, Object>>() {
            public int compare(Map.Entry<String, Object> o1, Map.Entry<String, Object> o2) {
                return (o1.getKey()).compareTo(o2.getKey());
            }
        });
        // 构造签名键值对的格式
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, Object> item : infoIds) {
            if (item.getKey() != null || item.getKey() != "") {
                Object val = item.getValue();
                if (!(val == "" || val == null)) {
                    sb.append(val);
                }
            }
        }
        sb.append(key);
        log.info("待签名串:{}", sb.toString());
        return MD5AndKL.MD5(sb.toString());
    }
    
    
 
}