liulin
2025-07-09 49aaecfb0617b0e6043147c86f3d303e9f24867e
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
package com.fengdu.gas.service;
 
import com.fengdu.gas.entity.request.test.TestPayVO;
import com.fengdu.gas.repository.po.TestInfoPO;
import com.fengdu.gas.service.convert.TestInfoConvert;
import com.fengdu.gas.common.ExecutedResult;
import com.fengdu.gas.common.PagerResult;
import com.fengdu.gas.common.enums.EYesOrNo;
import com.fengdu.gas.common.model.Tuple;
import com.fengdu.gas.common.util.*;
import com.fengdu.gas.entity.enums.EState;
import com.fengdu.gas.entity.request.ReqListSetSort;
import com.fengdu.gas.entity.request.ReqSetSort;
import com.fengdu.gas.entity.request.test.ReqCreateTestInfo;
import com.fengdu.gas.entity.request.test.ReqModifyTestInfo;
import com.fengdu.gas.entity.search.SearchTestInfo;
import com.fengdu.gas.repository.impl.TestInfoMapperImpl;
import com.fengdu.gas.repository.vo.TestInfoVO;
import com.google.gson.Gson;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.http.HttpStatus;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.Signature;
import java.security.interfaces.RSAPrivateCrtKey;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * 测试信息 相关服务
 */
@Service
public class TestInfoService extends BaseService {
    @Autowired
    private TestInfoMapperImpl mapper;
    //私钥
   private final static String PRIVATE_KEY="";
    private final static String PASSWORD="";
 
    /**
     * AES256加密
     * @param data
     * @return
     * @throws Exception
     */
    public String AES256(String data) throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(256); // 初始化密钥生成器,指定AES-256
        SecretKey key = keyGenerator.generateKey();
        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] encrypted = cipher.doFinal(data.getBytes("UTF-8"));
        return Base64.getEncoder().encodeToString(encrypted);
    }
 
    /**
     * Base64加密
     * @param data
     * @return
     */
    public String Base64(String data) {
        String encodedString = Base64.getEncoder().encodeToString(data.getBytes());
        return encodedString;
    }
    public static String getKeyAndValueStr(Map<String, String> map) {
        String result = "";
        try {
            List<Map.Entry<String, String>> infoIds = new ArrayList<>(map.entrySet());
            // 对所有传入参数按照字段名的 ASCII 码从小到大排序(字典序)
            Collections.sort(infoIds, Comparator.comparing(Map.Entry::getKey));
            // 构造签名键值对的格式
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, String> item : infoIds) {
                if (item.getKey() != null && item.getKey() != "") {
                    String key = item.getKey();
                    String val = item.getValue();
                    if (!(val == "" || val == null)) {
                        sb.append(key + "=" + val + "&");
                    }
                }
            }
            result = sb.toString().substring(0, sb.length() - 1);
        } catch (Exception e) {
            return null;
        }
        return result;
    }
 
 
    /**
     * 测试支付
     * @return
     * @throws Exception
     */
    public ExecutedResult<String> testPay() throws Exception {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost("https://test.sumpay.cn/entrance/gateway.htm");
        List<BasicNameValuePair> pairList = new ArrayList<>();
        Map<String, String> map = new HashMap<>();
        map.put("service", "fosun.sumpay.api.orderpay.order.apply");
        map.put("version","1.0");
        map.put("format","JSON");
        map.put("app_id",);
        map.put("timestamp","20250313142521");
        map.put("terminal_type","api");
        map.put("mer_no", "200102833852");//商户号
        map.put("account_type", "01");//付款方账户类型
        map.put("card_no", AES256("6217007200125513450"));//付款方账户号
        map.put("real_name", AES256("尹勇"));//付款方账户名
        //map.put("bank_code","");//银行代码
        //map.put("id_type","1");//证件类型
        //map.put("id_no",AES256(""));//证件号码
        //map.put("notify_url");//商户后台通知URL
        map.put("goods_name", Base64("测试001"));//商品名称
        map.put("goods_num", "1");//商品数量
        map.put("goods_price", "0.11");//商品价格
        map.put("goods_type", "1");//商品类型
        map.put("order_no", "111111111111111");//订单号
        map.put("order_amount", "0.11");//订单金额
        map.put("order_time", "20250313142521");//订单时间
        map.put("currency", "CNY");//币种
        // map.put("pay_comments");//附言
        //map.put("remark");//备注字段
        Map<String, String> map1 = new HashMap<>();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            map1.put(entry.getKey(), entry.getValue());
        }
        //map转换字符串&拼接并排序
        String keyAndValueStr = getKeyAndValueStr(map);
        //签名处理
        String msg = signMsg(keyAndValueStr, PRIVATE_KEY, PASSWORD, "UTF-8");
        map1.put("sign_type","CERT");
        map1.put("sign",msg);
 
        for(String key:map1.keySet()){
            pairList.add(new BasicNameValuePair(key,map1.get(key)));
        }
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairList, "UTF-8");
        httpPost.setEntity(entity);
        try {
            // 执行请求并获取响应
            CloseableHttpResponse response = client.execute(httpPost);
            try {
               if(response.getStatusLine().getStatusCode()== HttpStatus.SC_OK){
                   String data=EntityUtils.toString(response.getEntity(),"UTF-8");
                   System.out.println(data);
               }else {
                   throw new RuntimeException("接口连接失败");
               }
                // 处理响应...
            } finally {
                response.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ExecutedResult.success();
    }
    /**
     * 订单支付确认接口
     * @return
     * @throws Exception
     */
    public ExecutedResult<String> confirmPay() throws Exception {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost("https://test.sumpay.cn/entrance/gateway.htm");
        List<BasicNameValuePair> pairList = new ArrayList<>();
        Map<String, String> map = new HashMap<>();
        map.put("service", "fosun.sumpay.api.orderpay.order.apply");
        map.put("version","1.0");
        map.put("format","JSON");
        map.put("app_id",);
        map.put("timestamp","20250313142521");
        map.put("terminal_type","api");
        map.put("mer_no", "200102833852");//商户号
        map.put("order_no", "111111111111111");//订单号
        map.put("serial_no", "");//入账流水号
        Map<String, String> map1 = new HashMap<>();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            map1.put(entry.getKey(), entry.getValue());
        }
        //map转换字符串&拼接并排序
        String keyAndValueStr = getKeyAndValueStr(map);
        //签名处理
        String msg = signMsg(keyAndValueStr, PRIVATE_KEY, PASSWORD, "UTF-8");
        map1.put("sign_type","CERT");
        map1.put("sign",msg);
 
        for(String key:map1.keySet()){
            pairList.add(new BasicNameValuePair(key,map1.get(key)));
        }
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairList, "UTF-8");
        httpPost.setEntity(entity);
        try {
            // 执行请求并获取响应
            CloseableHttpResponse response = client.execute(httpPost);
            try {
                if(response.getStatusLine().getStatusCode()== HttpStatus.SC_OK){
                    String data=EntityUtils.toString(response.getEntity(),"UTF-8");
                    System.out.println(data);
                }else {
                    throw new RuntimeException("接口连接失败");
                }
                // 处理响应...
            } finally {
                response.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ExecutedResult.success();
    }
    /**
     * 签名处理
     * @param privateKeyPath:私钥
     * @param plaintext:原始字符串
     * @param passWord:证书密码
     * @param charset :UTF-8
     * @return
     */
    public String signMsg(String plaintext, String privateKeyPath, String passWord, String charset) {
        try {
            InputStream keyFile = new FileInputStream(new File(privateKeyPath));
            KeyStore ks = KeyStore.getInstance("PKCS12");
            try {
                ks.load(keyFile, passWord.toCharArray());
            } catch (Throwable ex) {
                if (keyFile != null)
                    keyFile.close();
                throw new RuntimeException("加载私钥失败",ex);
            }
            Enumeration<String> myEnum = ks.aliases();
            String keyAlias = null;
            RSAPrivateCrtKey prikey = null;
            /* IBM JDK必须使用While循环取最后一个别名,才能得到个人私钥别名 */
            while (myEnum.hasMoreElements()) {
                keyAlias = myEnum.nextElement();
                if (ks.isKeyEntry(keyAlias)) {
                    prikey = (RSAPrivateCrtKey) ks.getKey(keyAlias, passWord.toCharArray());
                    break;
                }
            }
            if (prikey == null) {
                throw new RuntimeException("没有找到匹配私钥");
            } else {
                Signature sign = Signature.getInstance("SHA256withRSA");
                sign.initSign(prikey);
                sign.update(plaintext.getBytes(charset));
                return org.apache.commons.codec.binary.Base64.encodeBase64String(sign.sign());
            }
        } catch (RuntimeException e) {
            throw e;
        } catch (Throwable e) {
            throw new RuntimeException("签名失败",e);
        }
    }
}