无关风月
2024-11-12 3ec572e2cb7adf7d33d2018b24c003d9ef18906a
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
package com.xinquan.order.utils;
 
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.xinquan.common.core.exception.ServiceException;
import com.xinquan.common.core.utils.DateUtils;
import com.xinquan.common.core.utils.StringUtils;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
 
/**
 * 桔禾付支付工具类
 *
 * @author mitao
 * @date 2024/9/7
 */
public class JuHeFuUtil {
 
    private static Logger logger = LoggerFactory.getLogger(JuHeFuUtil.class);
    // 商户RSA私钥 TODO
    private static final String MERCHANT_PRIVATE_KEY = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAMQPsMj4OYgjHFWS8wDIQOoMeAx9Ad1wKfIks7Oz5Kw8EVnmZ9o1ZY14goMMr1vJo/XxLLYXDvwj+EhV4MqT6ji2QDVqlhA4f6WFFmKOsvxgNnu0zAysfDpVpYihWC5uOf4ece9fWVci8DYFeXcawYGNB6GrJuo186sqMYwkE90/AgMBAAECgYAnMvfmhnKCPHraxSGeo2sPIGUUIh4wVs+cIShoomvy36OcdMuIvipKqbB2YR/iWyNT9d85nMybLtniJIFoH0CxshmLH/yg31vYhyLfVyih1RVFBRYuDMnIjvmNTBgXM/9vaAwkzonIQnoFoLVjxK2+JIFY+86Iak1Cv/vEi1vaSQJBAPRwebK51NBfrnO+2HY9nuDvbZbSx9I8uR+Yw/ebDUmbow/Dacibl0Hha+fw6cy5I3Rlm2kk5fKXIDIkwyLVq80CQQDNVXuQ8kXrDR0WjPcYPnwKNPEd0EHOKFiT7OqwoMFUUROyajO2nWs80eiZYZ+6M6+LEvYT6KcSiyiIwREnh1k7AkBV3BwjNzsVZkZ0yZhnEAX6pJ8t1yPxKPstqg9Lrd7g+BYyt0U0/dIHhhLNCcZV7sIRZI9OQ3Ox3nukoV0Zo0wRAkBT1eEbry+I5tPHj0qb5Xczm6YOrCcSCzsPOp4f+6Kz0F6ga+gtWVyden7jkQ5sMgosWFOMkWMVmSe1nk5ou0RdAkEAzfJJavQgu+BGQwqS1EojlXKe0GmpbQu+HwuDKcHmju0P2qGQ2yPfvURg1dMp7tmBM8AlVJhgzkNuyUAN1J841w==";
    // 平台RSA公钥 TODO
    private static final String PLAT_PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDOKBBFXirWIJth+SNJCY4mhbATbL60sKV66bRixHMVz8vpBqONio9X6A+Pm9LNutBe+hLpI1BMmFJk3Mb1/QEcklWptRGgHqIrBxR4b19qc/2/pSxyqlpaifYJFZhOg2+OcQ/fqpAmhNXN5uc1pcYvbvWTam0j+6+nBNQeAAku5QIDAQAB";
    // 应用的app_id TODO
    private static final String APP_ID = "app_10024101201";
    // 商户id TODO
    private static final String MER_ID = "1120241012072667";
    // AES密钥 TODO
    private static final String AES_KEY = "cb0a181ac97395c6942be19315fc0727";
    // 创建用户接口
    private static final String CREATE_USER_INTERFACE = "/api/member/create_user_a";
    private static final String BALANCE_PAY = "/api/account/balance_pay";
    // 创建支付订单
    private static final String CREATE_PAYMENT_INTERFACE = "/api/payment/create_payment";
    private static final String CREATE_PAYMENT_INTERFACE_CODE = "/api/payment/create_payment_qrcode";
    private static final String CREATE_PAYMENT_INTERFACE_THIRD = "/api/payment/create_payment_third";
    // 退款接口
    private static final String PAYMENT_REFUND_INTERFACE = "/api/payment/payment_refund";
    private static final String MERCHANT_PAY_INTERFACE = "/api/account/merchant_pay";
    // 接口地址 TODO
    private static final String BASE_URL = "http://paytest.juhefu.com/";
    // 支付宝支付渠道
    private static final String PAY_CHANNEL_ALIPAY = "alipay_qr";
    // 微信支付渠道
    private static final String PAY_CHANNEL_WECHAT = "wx_lite";
    private static final String PAY_CHANNEL_WECHAT_THiRD = "wx";
    // 微信小程序id TODO
    private static final String WX_APP_ID = "";
 
    /**
     * 创建用户
     *
     * @param memberId 用户id
     * @param memberP  用户信息
     * @return boolean
     * @throws Exception
     */
    public static boolean createUser(String memberId)
            throws Exception {
        JSONObject memberP = new JSONObject();
        memberP.put("user_name","周帅");
        memberP.put("cert_type","00");
        memberP.put("cert_id","513902200006257079");
        memberP.put("tel_no","19983174515");
        memberP.put("card_id","6228480469852935177");
        JSONObject data = new JSONObject();
        data.put("app_id", APP_ID);
        data.put("member_id", memberId);
        data.put("member_type", "01");
        String jsonString = JSON.toJSONString(JSONObject.parseObject(data.toString(), TreeMap.class));
        data.put("member_p", jsonString);
 
        System.err.println(data);
        JSONObject body = new JSONObject();
        body.put("merId", MER_ID);
        body.put("sign", sign(JSONObject.toJSONString(data)));
        body.put("reqCipher",
                EncryptUtils.aes256ECBPkcs7PaddingEncrypt(JSONObject.toJSONString(data), AES_KEY));
        body.put("reqTime", DateUtils.dateTimeNow("yyyyMMddHHmmsssss"));
        System.err.println(body);
        String result = sendPost(BASE_URL + CREATE_USER_INTERFACE, body);
        JSONObject resJsonObject = JSONObject.parseObject(result);
        System.err.println(resJsonObject);
        return false;
    }
 
    public static void main(String[] args) throws Exception {
        createPaymentCode("CZ19281833123", 1, "0.01",
                "充值", "充值",
                "127.0.0.1", "openId",
//                "https://v7ro848ar5jx.ngrok.xiaomiqiu123.top/order/client/order/order/base/callback")
        "https://xq.xqzhihui.com/api/order/client/order/order/base/callback");
//        String orderNo = OrderUtil.getOrderNoForPrefix("User");
//        createUser("usera12937812893718297391");
////          balancePay("12345678912", "0.01", "http://www.baidu.com");
    }
 
    public static JSONObject balancePay(String orderNo,  String payAmt, String notifyUrl) throws Exception {
        JSONObject data = new JSONObject();
 
        data.put("order_no", orderNo);
        data.put("app_id", APP_ID);
        data.put("pay_amt", payAmt);
        data.put("member_id", "21233333");
        data.put("notify_url", notifyUrl);
        JSONObject body = new JSONObject();
        body.put("merId", MER_ID);
        body.put("sign", sign(JSONObject.toJSONString(data)));
        body.put("reqCipher",
                EncryptUtils.aes256ECBPkcs7PaddingEncrypt(JSONObject.toJSONString(data), AES_KEY));
        body.put("reqTime", DateUtils.dateTimeNow("yyyyMMddHHmmsssss"));
        String result = sendPost(BASE_URL + BALANCE_PAY, body);
        JSONObject resJsonObject = JSONObject.parseObject(result);
        System.err.println(resJsonObject);
        String string = resJsonObject.getString("resCipher");
        String decrypt = decrypt(string);
        System.err.println(decrypt);
        JSONObject jsonObject = JSONObject.parseObject(decrypt);
        System.err.println(jsonObject);
        return null;
    }
 
    /**
     * 创建支付订单
     *
     * @param orderNo    订单号
     * @param payChannel 支付渠道 1:支付宝 2:微信
     * @param payAmt     支付金额
     * @param goodsTitle 商品标题
     * @param goodsDesc  商品描述信息,微信小程序和微信公众号该字段 最大长度 42 个字符
     * @param deviceIp   设备支付公网ip
     * @param openId     微信openId
     * @param notifyUrl  回调地址
     * @return JSONObject
     * @throws Exception
     */
    public static JSONObject createPayment(String orderNo, Integer payChannel, String payAmt,
            String goodsTitle, String goodsDesc, String deviceIp, String openId,
            String notifyUrl) throws Exception {
        JSONObject data = new JSONObject();
        JSONObject expand = new JSONObject();
        data.put("order_no", orderNo);
        data.put("app_id", APP_ID);
        if (payChannel == 1) {
            data.put("pay_channel", PAY_CHANNEL_WECHAT);
            expand.put("open_id", openId);
            expand.put("wx_app_id", WX_APP_ID);
            data.put("expand", expand);
        } else {
 
            data.put("pay_channel", PAY_CHANNEL_ALIPAY);
 
        }
        data.put("pay_amt", payAmt);
        data.put("goods_title", goodsTitle);
        data.put("goods_desc", goodsDesc);
        Map<String, Object> deviceInfo = new HashMap<>();
        deviceInfo.put("device_ip", deviceIp);
        data.put("device_info", deviceInfo);
        data.put("notify_url", notifyUrl);
        JSONObject body = new JSONObject();
        body.put("merId", MER_ID);
        body.put("sign", sign(JSONObject.toJSONString(data)));
        body.put("reqCipher",
                EncryptUtils.aes256ECBPkcs7PaddingEncrypt(JSONObject.toJSONString(data), AES_KEY));
        body.put("reqTime", DateUtils.dateTimeNow("yyyyMMddHHmmsssss"));
        String result = sendPost(BASE_URL + CREATE_PAYMENT_INTERFACE, body);
        JSONObject resJsonObject = JSONObject.parseObject(result);
        System.err.println(resJsonObject);
        String string = resJsonObject.getString("resCipher");
        String decrypt = decrypt(string);
        System.err.println(decrypt);
        JSONObject jsonObject = JSONObject.parseObject(decrypt);
 
//        if (resJsonObject.getString("status").equals("failed")) {
//            throw new ServiceException(resJsonObject.getString("error_msg"));
//        }
//        if (resJsonObject.getString("status").equals("succeeded")) {
//            return resJsonObject.getJSONObject("expand");
//        }
        return jsonObject;
    }
    public static JSONObject createPaymentCode(String orderNo, Integer payChannel, String payAmt,
            String goodsTitle, String goodsDesc, String deviceIp, String openId,
            String notifyUrl) throws Exception {
        JSONObject data = new JSONObject();
        JSONObject expand = new JSONObject();
        data.put("order_no", orderNo);
        data.put("app_id", APP_ID);
        if (payChannel == 1) {
            data.put("pay_channel", PAY_CHANNEL_ALIPAY);
        } else {
            data.put("pay_channel", PAY_CHANNEL_WECHAT);
            expand.put("open_id", openId);
            expand.put("wx_app_id", WX_APP_ID);
            data.put("expand", expand);
        }
        data.put("pay_amt", payAmt);
        data.put("goods_title", goodsTitle);
        data.put("goods_desc", goodsDesc);
        data.put("time_expire", "20241031000000");
        Map<String, Object> deviceInfo = new HashMap<>();
        deviceInfo.put("device_ip", deviceIp);
        data.put("device_info", deviceInfo);
        data.put("notify_url", notifyUrl);
        JSONObject body = new JSONObject();
        body.put("merId", MER_ID);
        body.put("sign", sign(JSONObject.toJSONString(data)));
        body.put("reqCipher",
                EncryptUtils.aes256ECBPkcs7PaddingEncrypt(JSONObject.toJSONString(data), AES_KEY));
        body.put("reqTime", DateUtils.dateTimeNow("yyyyMMddHHmmsssss"));
        String result = sendPost(BASE_URL + CREATE_PAYMENT_INTERFACE_CODE, body);
        JSONObject resJsonObject = JSONObject.parseObject(result);
        System.err.println(resJsonObject);
        String string = resJsonObject.getString("resCipher");
        String decrypt = decrypt(string);
        System.err.println(decrypt);
        JSONObject jsonObject = JSONObject.parseObject(decrypt);
 
//        if (resJsonObject.getString("status").equals("failed")) {
//            throw new ServiceException(resJsonObject.getString("error_msg"));
//        }
//        if (resJsonObject.getString("status").equals("succeeded")) {
//            return resJsonObject.getJSONObject("expand");
//        }
        return jsonObject.getJSONObject("expand");
    }
    /**
     * 创建支付订单 微信托管支付
     *
     * @param orderNo    订单号
     * @param payChannel 支付渠道 1:支付宝 2:微信
     * @param payAmt     支付金额
     * @param goodsTitle 商品标题
     * @param goodsDesc  商品描述信息,微信小程序和微信公众号该字段 最大长度 42 个字符
     * @param deviceIp   设备支付公网ip
     * @param openId     微信openId
     * @param notifyUrl  回调地址
     * @return JSONObject
     * @throws Exception
     */
    public static JSONObject createPayment1(String orderNo, Integer payChannel, String payAmt,
            String goodsTitle, String goodsDesc, String deviceIp, String openId,
            String notifyUrl) throws Exception {
        JSONObject data = new JSONObject();
        JSONObject expand = new JSONObject();
        data.put("order_no", orderNo);
        data.put("app_id", APP_ID);
        data.put("pay_channel", PAY_CHANNEL_WECHAT_THiRD);
        data.put("pay_amt", payAmt);
        data.put("goods_title", goodsTitle);
        data.put("goods_desc", goodsDesc);
        Map<String, Object> deviceInfo = new HashMap<>();
        deviceInfo.put("device_ip", deviceIp);
        data.put("device_info", deviceInfo);
        data.put("notify_url", notifyUrl);
        JSONObject body = new JSONObject();
        body.put("merId", MER_ID);
        body.put("sign", sign(JSONObject.toJSONString(data)));
        body.put("reqCipher",
                EncryptUtils.aes256ECBPkcs7PaddingEncrypt(JSONObject.toJSONString(data), AES_KEY));
        body.put("reqTime", DateUtils.dateTimeNow("yyyyMMddHHmmsssss"));
        String result = sendPost(BASE_URL + CREATE_PAYMENT_INTERFACE_THIRD, body);
        JSONObject resJsonObject = JSONObject.parseObject(result);
        System.err.println(resJsonObject);
        String string = resJsonObject.getString("resCipher");
        String decrypt = decrypt(string);
        System.err.println("解密后"+decrypt);
        JSONObject jsonObject = JSONObject.parseObject(decrypt);
 
//        if (resJsonObject.getString("status").equals("failed")) {
//            throw new ServiceException(resJsonObject.getString("error_msg"));
//        }
//        if (resJsonObject.getString("status").equals("succeeded")) {
//            return resJsonObject.getJSONObject("expand");
//        }
        return jsonObject;
    }
 
    /**
     * 申请退款
     *
     * @param paymentId 支付单号
     * @param orderNo   订单号
     * @return
     */
    public static String refund(String paymentId, String orderNo) throws Exception {
        JSONObject data = new JSONObject();
        data.put("payment_id", paymentId);
        data.put("order_no", orderNo);
        JSONObject body = new JSONObject();
        body.put("merId", MER_ID);
        body.put("sign", sign(JSONObject.toJSONString(data)));
        body.put("reqCipher",
                EncryptUtils.aes256ECBPkcs7PaddingEncrypt(JSONObject.toJSONString(data), AES_KEY));
        body.put("reqTime", DateUtils.dateTimeNow("yyyyMMddHHmmsssss"));
        String result = sendPost(BASE_URL + PAYMENT_REFUND_INTERFACE, body);
        JSONObject resJsonObject = JSONObject.parseObject(result);
//        if (resJsonObject.getString("status").equals("succeeded")) {
//            return "ok";
//        } else if (resJsonObject.getString("status").equals("failed")) {
//            throw new ServiceException(resJsonObject.getString("error_msg"));
//        }
        return "ok";
    }
 
    /**
     * 商户付款
     *
     * @param orderNo  订单号
     * @param payAmt   交易金额
     * @param cardName 收款银行开户名
     * @param cardId   收款银行卡号
     * @param cardType 收款银行账户类型 DEBIT_CARD:借记卡 CREDIT_CARD:贷记卡 76 QUASI_CREDIT_CARD:准贷卡 PASSBOOK:存折
     *                 UNIT_SETTLE_CARD:单位结算卡 PUBLIC_CARD:对公卡
     * @return
     * @throws Exception
     */
    public static JSONObject merchantPay(String orderNo, String payAmt, String cardName, String cardId,
            String cardType)
            throws Exception {
        JSONObject data = new JSONObject();
        data.put("order_no", orderNo);
        data.put("app_id", APP_ID);
        data.put("pay_amt", payAmt);
        data.put("card_name", cardName);
        data.put("card_id", cardId);
        data.put("card_type", cardType);
        JSONObject body = new JSONObject();
        body.put("merId", MER_ID);
        body.put("sign", sign(JSONObject.toJSONString(data)));
        body.put("reqCipher",
                EncryptUtils.aes256ECBPkcs7PaddingEncrypt(JSONObject.toJSONString(data), AES_KEY));
        body.put("reqTime", DateUtils.dateTimeNow("yyyyMMddHHmmss"));
        String result = sendPost(BASE_URL + MERCHANT_PAY_INTERFACE, body);
        JSONObject resJsonObject = JSONObject.parseObject(result);
        System.err.println(resJsonObject);
        String string = resJsonObject.getString("resCipher");
        String decrypt = decrypt(string);
        System.err.println("解密后"+decrypt);
        JSONObject jsonObject = JSONObject.parseObject(decrypt);
        return jsonObject;
    }
 
    /**
     * 发送post请求
     *
     * @param url  请求地址
     * @param body 请求体
     * @return
     */
    private static String sendPost(String url, JSONObject body) {
        HttpRequest post = HttpUtil.createPost(url);
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-type", "application/json; charset=utf-8");
        headers.put("Accept", "application/json");
        post.addHeaders(headers);
        post.body(body.toJSONString());
        HttpResponse execute = post.execute();
        String result = execute.body();
        execute.close();
        if (StringUtils.isBlank(result)) {
            throw new ServiceException("请求第三方支付平台异常");
        }
        return result;
    }
 
 
 
    /**
     * RSA私钥签名:签名方式SHA256WithRSA
     *
     * @param data 待签名字符串
     * @return 签名byte[]
     * @throws Exception
     */
    public static String sign(String data) {
        // 先对该json对象数据按照参数字典顺序(参数名ASCII码从小到大排序,参数名区分大小写)排序生成字符串,再进行加签和验签。
        data = JSON.toJSONString(JSONObject.parseObject(data, TreeMap.class));
        // Base64 --> Key
        try {
            byte[] bytes = Base64.getDecoder().decode(MERCHANT_PRIVATE_KEY);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes);
            KeyFactory keyFactory;
            keyFactory = KeyFactory.getInstance("RSA");
            PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
            // Sign
            Signature signature = Signature.getInstance("SHA256WithRSA");
            signature.initSign(privateKey);
            signature.update(data.getBytes("UTF-8"));
            return Base64.getEncoder().encodeToString(signature.sign());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    public static String decrypt(String strToDecrypt) {
        try {
        SecretKeySpec secretKey = new SecretKeySpec(AES_KEY.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
    } catch (Exception e) {
            System.out.println("Error while decrypting: " + e.toString());
    }
        return null;}
//    public static boolean verify(String data, String publicKeyStr) {
//        try {
//            // 解码公钥
//            byte[] publicKeyBytes = Base64.getDecoder().decode(publicKeyStr);
//            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes);
//            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
//            PublicKey publicKey = keyFactory.generatePublic(keySpec);
//            // 验证签名
//            Signature signature = Signature.getInstance("SHA256WithRSA");
//            signature.initVerify(publicKey);
//            signature.update(data.getBytes("UTF-8"));
//
//            return true;
//        } catch (Exception e) {
//            e.printStackTrace();
//            return false;
//        }
//    }
 
}