xin
2025-07-08 83396a38be3c69c81f8acc4681c18f5dd0e698be
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
package com.oying.modules.hwc.service.impl;
 
import com.alibaba.fastjson2.JSONObject;
import com.google.gson.Gson;
import com.oying.exception.BadRequestException;
import com.oying.modules.hwc.domain.HwcResponse;
import com.oying.modules.hwc.service.SwiftPassService;
import com.oying.modules.hwc.utils.SignUtil;
import com.oying.modules.hwc.utils.SignUtils;
import com.oying.modules.hwc.utils.XmlUtils;
import com.oying.modules.security.config.SwiftPassProperties;
import com.oying.modules.security.config.WeiXinProperties;
import com.oying.utils.CloseUtil;
import com.oying.utils.enums.PayTypeEnum;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
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.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import java.util.*;
 
/**
 * @author xin
 * @description
 * @date 2025/1/23 下午4:01
 */
@SuppressWarnings({"unchecked", "all"})
@Slf4j
@Service
@RequiredArgsConstructor
public class SwiftPassServiceImpl implements SwiftPassService {
 
    private final static String version = "2.0";
    private final static String charset = "UTF-8";
    private final static String service_pay = "pay.weixin.jspay";
    private final static String service_query = "unified.trade.query";
    private final static String service_refund = "unified.trade.refund";
    private final static String service_close = "unified.trade.close";
 
    private final SwiftPassProperties properties;
    private final WeiXinProperties weiXinProperties;
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public HwcResponse pay(String ip, String total, String timeExpire, String description, String openId,
                           String orderNum, PayTypeEnum status) {
        SortedMap<String, String> map = new TreeMap<>();
        map.put("service", service_pay);
        map.put("version", version);
        map.put("charset", charset);
        map.put("sign_type", properties.getSignType());
        map.put("is_raw", properties.getIsRaw());
        map.put("is_minipg", properties.getIsMinipg());
        map.put("out_trade_no", orderNum);
        map.put("body", description);
        map.put("sub_openid", openId);
        map.put("sub_appid", weiXinProperties.getAppId());
        map.put("total_fee", total);
        map.put("mch_create_ip", ip);
        map.put("notify_url", properties.getNotifyUrl());
        map.put("time_expire", timeExpire);
        map.put("nonce_str", String.valueOf(new Date().getTime()));
        switch (status) {
            case HWC:
                map.put("mch_id", properties.getMchId());
                break;
            case HWC2:
                map.put("mch_id", properties.getMchId2());
                break;
            default:
                throw new BadRequestException("汇旺财类型错误");
        }
        Map<String, String> params = SignUtils.paraFilter(map);
        StringBuilder buf = new StringBuilder((params.size() + 1) * 10);
        SignUtils.buildPayParams(buf, params, false);
        String preStr = buf.toString();
        String sign_type = map.get("sign_type");
 
        map.put("sign", SignUtil.getSign(sign_type, preStr, properties, status));
 
        String reqUrl = properties.getReqUrl();
        CloseableHttpResponse response = null;
        CloseableHttpClient client = null;
        Map<String, String> resultMap = new HashMap<>();
        try {
            HttpPost httpPost = new HttpPost(reqUrl);
            StringEntity entityParams = new StringEntity(XmlUtils.parseXML(map), "utf-8");
            httpPost.setEntity(entityParams);
            httpPost.setHeader("Content-Type", "text/xml;utf-8");
            client = HttpClients.createDefault();
            response = client.execute(httpPost);
            if (response != null && response.getEntity() != null) {
                resultMap = XmlUtils.toMap(EntityUtils.toByteArray(response.getEntity()), "utf-8");
                String reSign = resultMap.get("sign");
                sign_type = resultMap.get("sign_type");
                if (resultMap.containsKey("sign") && SignUtil.verifySign(reSign, sign_type, resultMap, properties, status)) {
                    throw new BadRequestException("验证签名错误");
                } else {
                    if ("0".equals(resultMap.get("status")) && "0".equals(resultMap.get("result_code"))) {
                        Gson gson = new Gson();
                        return gson.fromJson(resultMap.get("pay_info"), HwcResponse.class);
                    } else {
                        throw new BadRequestException(resultMap.get("err_code") + " : " + resultMap.get("err_msg") + "\n" +
                                resultMap.get("status") + " : " + resultMap.get("message"));
                    }
                }
            } else {
                throw new BadRequestException("操作失败");
            }
        } catch (Exception e) {
            log.error("汇旺财下单错误请求参数:{}", params);
            log.error("汇旺财下单错误返回参数:{}", resultMap);
            throw new BadRequestException("汇旺财下单错误:" + e.getMessage());
        } finally {
            if (response != null) {
                CloseUtil.close(response);
            }
            if (client != null) {
                CloseUtil.close(client);
            }
        }
    }
 
    @Override
    public JSONObject query(String orderNum, PayTypeEnum status) {
        // 参数
        SortedMap<String, String> map = new TreeMap<>();
        map.put("service", service_query);
        map.put("version", version);
        map.put("charset", charset);
        map.put("out_trade_no", orderNum);
        map.put("sign_type", properties.getSignType());
        switch (status) {
            case HWC:
                map.put("mch_id", properties.getMchId());
                break;
            case HWC2:
                map.put("mch_id", properties.getMchId2());
                break;
            default:
                throw new BadRequestException("汇旺财类型错误");
        }
        map.put("nonce_str", String.valueOf(new Date().getTime()));
        // 签名
        Map<String, String> params = SignUtils.paraFilter(map);
        StringBuilder buf = new StringBuilder((params.size() + 1) * 10);
        SignUtils.buildPayParams(buf, params, false);
        String preStr = buf.toString();
        String sign_type = map.get("sign_type");
        map.put("sign", SignUtil.getSign(sign_type, preStr, properties, status));
        // 请求
        CloseableHttpResponse response = null;
        CloseableHttpClient client = null;
        Map<String, String> resultMap = new HashMap<>();
        try {
            HttpPost httpPost = new HttpPost(properties.getReqUrl());
            StringEntity entityParams = new StringEntity(XmlUtils.parseXML(map), "utf-8");
            httpPost.setEntity(entityParams);
            httpPost.setHeader("Content-Type", "text/xml;utf-8");
            client = HttpClients.createDefault();
            response = client.execute(httpPost);
            if (response != null && response.getEntity() != null) {
                resultMap = XmlUtils.toMap(EntityUtils.toByteArray(response.getEntity()), "utf-8");
                String reSign = resultMap.get("sign");
                sign_type = resultMap.get("sign_type");
                if (resultMap.containsKey("sign") && SignUtil.verifySign(reSign, sign_type, resultMap, properties, status)) {
                    throw new BadRequestException("验证签名错误");
                } else {
                    if ("0".equals(resultMap.get("status"))) {
                        return JSONObject.parseObject(JSONObject.toJSONString(resultMap));
                    } else {
 
                        throw new BadRequestException(resultMap.get("err_code") + " : " + resultMap.get("err_msg") + "\n" +
                                resultMap.get("status") + " : " + resultMap.get("message"));
                    }
                }
            } else {
                throw new BadRequestException("操作失败!");
            }
        } catch (Exception e) {
            log.error("请求参数:{}", params);
            log.error("返回参数:{}", resultMap);
            throw new BadRequestException("操作失败,原因:" + e.getMessage());
        } finally {
            if (response != null) {
                CloseUtil.close(response);
            }
            if (client != null) {
                CloseUtil.close(client);
            }
        }
    }
 
    @Override
    public void closeOrder(String outTradeNo, PayTypeEnum status) {
        // 参数
        SortedMap<String, String> map = new TreeMap<>();
        map.put("service", service_close);
        map.put("version", version);
        map.put("charset", charset);
        map.put("out_trade_no", outTradeNo);
        map.put("sign_type", properties.getSignType());
        switch (status) {
            case HWC:
                map.put("mch_id", properties.getMchId());
                break;
            case HWC2:
                map.put("mch_id", properties.getMchId2());
                break;
            default:
                throw new BadRequestException("汇旺财类型错误");
        }
        map.put("nonce_str", String.valueOf(new Date().getTime()));
        // 签名
        Map<String, String> params = SignUtils.paraFilter(map);
        StringBuilder buf = new StringBuilder((params.size() + 1) * 10);
        SignUtils.buildPayParams(buf, params, false);
        String preStr = buf.toString();
        String sign_type = map.get("sign_type");
        map.put("sign", SignUtil.getSign(sign_type, preStr, properties, status));
        // 请求
        CloseableHttpResponse response = null;
        CloseableHttpClient client = null;
        Map<String, String> resultMap = new HashMap<>();
        try {
            HttpPost httpPost = new HttpPost(properties.getReqUrl());
            StringEntity entityParams = new StringEntity(XmlUtils.parseXML(map), "utf-8");
            httpPost.setEntity(entityParams);
            httpPost.setHeader("Content-Type", "text/xml;utf-8");
            client = HttpClients.createDefault();
            response = client.execute(httpPost);
            if (response != null && response.getEntity() != null) {
                resultMap = XmlUtils.toMap(EntityUtils.toByteArray(response.getEntity()), "utf-8");
                String reSign = resultMap.get("sign");
                sign_type = resultMap.get("sign_type");
                if (resultMap.containsKey("sign") && SignUtil.verifySign(reSign, sign_type, resultMap, properties, status)) {
                    throw new BadRequestException("验证签名错误");
                } else {
                    if (!("0".equals(resultMap.get("status")))) {
                        throw new BadRequestException(resultMap.get("err_code") + " : " + resultMap.get("err_msg") + "\n" +
                                resultMap.get("status") + " : " + resultMap.get("message"));
                    }
                }
            } else {
                throw new BadRequestException("操作失败!");
            }
        } catch (Exception e) {
            log.error("请求参数:{}", params);
            log.error("返回参数:{}", resultMap);
            throw new BadRequestException("操作失败,原因:" + e.getMessage());
        } finally {
            if (response != null) {
                CloseUtil.close(response);
            }
            if (client != null) {
                CloseUtil.close(client);
            }
        }
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, String> refund(String returnNum, String orderNum, String reason, long refund,
                                      long total, PayTypeEnum payType) {
        // 参数
        SortedMap<String, String> map = new TreeMap<>();
        map.put("service", service_refund);
        map.put("version", version);
        map.put("charset", charset);
        map.put("sign_type", properties.getSignType());
        map.put("out_trade_no", orderNum);
        map.put("out_refund_no", returnNum);
        map.put("total_fee", String.valueOf(total));
        map.put("refund_fee", String.valueOf(refund));
        map.put("nonce_str", String.valueOf(new Date().getTime()));
        switch (payType) {
            case HWC:
                map.put("mch_id", properties.getMchId());
                map.put("op_user_id", properties.getMchId());
                break;
            case HWC2:
                map.put("mch_id", properties.getMchId2());
                map.put("op_user_id", properties.getMchId2());
                break;
            default:
                throw new BadRequestException("汇旺财类型错误");
        }
        // 签名
        Map<String, String> params = SignUtils.paraFilter(map);
        StringBuilder buf = new StringBuilder((params.size() + 1) * 10);
        SignUtils.buildPayParams(buf, params, false);
        String preStr = buf.toString();
        String sign_type = map.get("sign_type");
        map.put("sign", SignUtil.getSign(sign_type, preStr, properties, payType));
        // 参数
        CloseableHttpResponse response = null;
        CloseableHttpClient client = null;
        Map<String, String> resultMap = new HashMap<>();
        try {
            HttpPost httpPost = new HttpPost(properties.getReqUrl());
            StringEntity entityParams = new StringEntity(XmlUtils.parseXML(map), "utf-8");
            httpPost.setEntity(entityParams);
            httpPost.setHeader("Content-Type", "text/xml;utf-8");
            client = HttpClients.createDefault();
            response = client.execute(httpPost);
            if (response != null && response.getEntity() != null) {
                resultMap = XmlUtils.toMap(EntityUtils.toByteArray(response.getEntity()), "utf-8");
                if (resultMap.containsKey("sign") && SignUtil.verifySign(resultMap.get("sign"), resultMap.get("sign_type"), resultMap, properties, payType)) {
                    throw new BadRequestException("验证签名错误");
                } else {
                    if ("0".equals(resultMap.get("status"))) {
                        return resultMap;
                    } else {
                        throw new BadRequestException(resultMap.get("err_code") + " : " + resultMap.get("err_msg") + "\n" +
                                resultMap.get("status") + " : " + resultMap.get("message"));
                    }
                }
            } else {
                throw new BadRequestException("操作失败!");
            }
        } catch (Exception e) {
            log.error("请求参数:{}", params);
            log.error("返回参数:{}", resultMap);
            throw new BadRequestException("操作失败,原因:" + e);
        } finally {
            if (response != null) {
                CloseUtil.close(response);
            }
            if (client != null) {
                CloseUtil.close(client);
            }
        }
    }
 
 
}