nickchange
2023-10-11 95ec3536dfd071443a5704dc28eb30fd19b4ae98
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
package com.dsh.account.util;
 
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.*;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import com.dsh.account.dto.Receivers;
import com.dsh.account.entity.OperatorUser;
import com.dsh.account.feignclient.competition.DeductionCompetitionsClient;
import com.dsh.account.feignclient.competition.model.PaymentCompetition;
import com.dsh.account.feignclient.course.CoursePackageClient;
import com.dsh.account.feignclient.course.model.TCoursePackagePayment;
import com.dsh.account.feignclient.other.SiteClient;
import com.dsh.account.feignclient.other.model.SiteBooking;
import com.dsh.account.mapper.RechargeRecordsMapper;
import com.dsh.account.util.httpClinet.HttpClientUtil;
//import com.github.binarywang.wxpay.bean.profitsharingV3.ProfitSharingReceiver;
//import com.github.binarywang.wxpay.bean.profitsharingV3.ProfitSharingRequest;
//import com.github.binarywang.wxpay.service.ProfitSharingV3Service;
//import com.github.binarywang.wxpay.service.WxPayService;
 
import org.apache.commons.collections.map.HashedMap;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
 
import javax.annotation.Resource;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import java.util.*;
 
/**
 * 第三方支付工具类
 */
@Component
public class PayMoneyUtil {
    private String aliAppid = "2021004105665036";//支付宝appid
 
    private String appPrivateKey = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCi5i9nW/hGLJ3A06cZxTQdviFC7THpdSihoTYGLr9q006hu0V26ecBMY/o4w5bvIX0Ok/yofmZsVcCJpAPvbXL/uqVrIjnRRxXiaeBFThlxoBUTdunvbUSDYfzlEhJr5NvUKI6H6lz2niXlQGx4qy8Hau4ccWit9kM8jwUvsBVQoFgJA+xrjMvooA7YLopQtpOD+UJr5thApTSf1xrnr1W12yolTLEH15JmNV372cqXrYUuqnY0QsaPtxeqJUGAOcGdVLllQ7easEznP8DFBvDdHATcmp2SHNQDUEWN6MCVPbMgY06NQVqAXxqjTAYSVh+6TRu6bofPmpYC3TZB003AgMBAAECggEBAJAcR2+PA3NBYUYHeFrqBRMS8uX8ZR19kjZ7IgoSLTFaQsP9opRylPSPXhrPVBKAE5leRQAHn4MCSlESwHvMfxo7KFjFTFAc6dffZZpipYQUOc9bGampwJh58/3e/pyBgVMG6J23CPf/HJQtNFSkjd/V9+ayb/9l2dUEL3bC0fAZ/dbx8HsxdLw8wn3fLlWLj68hOMqa2deCZe3JdSVsPbeWqkh56FFsMLug0Nd+Ar4TgRl9/jnhXF0JWiD0LmPUYLhboY7EfUBzN4w1iYbDi1P+3zvoOYsiVKAXox9GMhQ2VzOO2UcSTuizSza2e98mGpabl/GpKmCz+RDFjtkX6eECgYEA2MyCij65eO3aGIm3FUe93DULRBYTfX8qJQSJq2WOWA3mmQlEW6L3O2B5/lG2h+8WmN6iLEs9eHpgycGYp7vAqgrANEn16ACVcuyx0scFtrZfZ+kmHMzFfiUWxJjVYk/6YngsGVBLdw6ueM42C8TTP67X9tU5TdVGoGWuqEj4W98CgYEAwFqwprXOch5Pqk/RPbb49r0Ou03K/UbciWnWWKzUhFFNS8MdlQPoDvQZbMwHLeWsa2VhaKITK3x5biLQb3U+0GLOn6lTvEyrEUH+ucREyLgVYTRAvwBPtnvlrzpyxPk2HnslQjju8WrvvLLBMKWUjlTrTOzhaHT21gz3pHMiOakCgYEAhLmfaXdBITGshb054sNLDtdCkGpbgEcrzAHdLps769iGxkYQHXHFngpQZUwtTUcoNGqIKknd1jZFrv7gsD+XkgKG7PwimehRlkwmCX5ilxtLiVgJRzRt6+5U5AMVD90a0tHzXYP0z2yjj73fBJF5KtGl0a10KZxaYrQdm1UhB00CgYBZZgzx/k9rtHC8LAqIj1CYhHejT92G53c6Gkl3vyOqN4sgKhfGmSEySfrDGPRBPZxr8ZtbIPCd5mUdberH0osWGMYFaJI1UsCy7aQwvGpniz7MhZeN7dweaOjwDs8mgtjHQ96mL4XGCDhR0BZ/wIURvZ/6iaGdhbbu9unlsWj3uQKBgQCmZYdsbbZkd3ev6f8rwyvMz+DrCQyYpY44cegBYuJgrZiQnL2fJioeN7ixX0UM48SfwsZEIrzshP/LGAwnc2MdjxKUl4jLN8SEe0NAjXOnz9Zaw740+aOmLpXcLWdP4uM2gIhWsvW1tEkQZCXmm7c9s/RsU8Pmzv+YL3+fSijOzA==";//支付宝开发者应用私钥
 
    private String alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAouYvZ1v4RiydwNOnGcU0Hb4hQu0x6XUooaE2Bi6/atNOobtFdunnATGP6OMOW7yF9DpP8qH5mbFXAiaQD721y/7qlayI50UcV4mngRU4ZcaAVE3bp721Eg2H85RISa+Tb1CiOh+pc9p4l5UBseKsvB2ruHHForfZDPI8FL7AVUKBYCQPsa4zL6KAO2C6KULaTg/lCa+bYQKU0n9ca569VtdsqJUyxB9eSZjVd+9nKl62FLqp2NELGj7cXqiVBgDnBnVS5ZUO3mrBM5z/AxQbw3RwE3JqdkhzUA1BFjejAlT2zIGNOjUFagF8ao0wGElYfuk0bum6Hz5qWAt02QdNNwIDAQAB";//支付宝应用公钥
 
    private String alipay_public_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmu8n/4yTHWbn7VOrNc9OsLtDL1bEQ8gC1dHkj8Wy5z0mkaOsjJRIG/28ze12M0V8jdCKuuDr5Z1OPKiqf+XO3ypguEh+mYUVMBM/cZodDFQfTY1TKLWjvQCuaqlA+QUTCK6f7T7stsgyQ1o9Jj0rXZDz6PM4QHSTzjrLIBaeqM5WIBvH+fy/X+QG5Utd+/UT0kc0JyvuKhZ65yVUd/C9VcwJJAPliRsAQNrqYterwAJ9zvw9tF11wj9W0XgJ8Ccu4x3gR1vrlLRJJo/OA97RmxPQ+5hSacWQZCUd1dwiBq+YCrKVHGTj14izRHXrLc0yBlRXo7tBOIqcy3IsvKVthQIDAQAB";//支付宝支付公钥
 
    private String appid = "";//微信appid
 
    private String appletsAppid = "";//微信小程序appid
 
    private String mchId = "";//微信商户号
 
    private String key = "";//微信商户号
 
    private String callbackPath = "";//支付回调网关地址
 
    private String app_cert_path = "C:/cert/alipay/user/app_cert_path.crt";//应用公钥证书路径
 
    private String alipay_cert_path = "C:/cert/alipay/user/alipay_cert_path.crt";//支付宝公钥证书文件路径
 
    private String alipay_root_cert_path = "C:/cert/alipay/user/alipay_root_cert_path.crt";//支付宝CA根证书文件路径
 
    private String certPath = "C:\\cert\\1523106371_20211206_cert\\apiclient_cert.p12";//微信证书
 
 
 
    /**
     * 支付宝支付
     */
    public ResultUtil alipay(String body, String subject, String passbackParams, String outTradeNo, String amount, String notifyUrl){
//        //构造client
//        CertAlipayRequest certAlipayRequest = new CertAlipayRequest ();
//        //设置网关地址
//        certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do");
//        //设置应用Id
//        certAlipayRequest.setAppId(aliAppid);
//        //设置应用私钥
//        certAlipayRequest.setPrivateKey(appPrivateKey);
//        //设置请求格式,固定值json
//        certAlipayRequest.setFormat("json");
//        //设置字符集
//        certAlipayRequest.setCharset("UTF-8");
//        //设置签名类型
//        certAlipayRequest.setSignType("RSA2");
//        //设置应用公钥证书路径
//        certAlipayRequest.setCertPath(app_cert_path);
//        //设置支付宝公钥证书路径
//        certAlipayRequest.setAlipayPublicCertPath(alipay_cert_path);
//        //设置支付宝根证书路径
//        certAlipayRequest.setRootCertPath(alipay_root_cert_path);
//        //构造client
//        AlipayClient alipayClient = null;
//        try {
//            alipayClient = new DefaultAlipayClient(certAlipayRequest);
//        } catch (AlipayApiException e) {
//            e.printStackTrace();
//        }
//        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称:alipay.trade.app.pay
//        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest ();
//        //SDK已经封装掉了公共参数,这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
//        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel ();
//        model.setBody(body);
//        model.setSubject (subject);
//        model.setOutTradeNo (outTradeNo);
//        model.setTimeoutExpress ("30m" );
//        model.setTotalAmount (amount);
//        model.setProductCode ( "QUICK_MSECURITY_PAY" );
//        model.setPassbackParams(passbackParams);//自定义参数
//        request.setBizModel ( model );
//        request.setNotifyUrl (callbackPath + notifyUrl);
//        try  {
//            //这里和普通的接口调用不同,使用的是sdkExecute
//            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
//            Map<String, String> map = new HashMap<>();
//            map.put("orderString", response.getBody());
//            System.out.println(map);//就是orderString 可以直接给客户端请求,无需再做处理。
//            return ResultUtil.success(map);
//        }  catch (AlipayApiException e ) {
//            e.printStackTrace();
//        }
 
 
        //实例化客户端
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", aliAppid, appPrivateKey, "json", "UTF-8", alipay_public_key, "RSA2");
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称:alipay.trade.app.pay
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数,这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setBody(body);//对一笔交易的具体描述信息。如果是多种商品,请将商品描述字符串累加传给body。
        model.setSubject(subject);//商品的标题/交易标题/订单标题/订单关键字等。
        model.setOutTradeNo(outTradeNo);//商户网站唯一订单号
        model.setTimeoutExpress("30m");
        model.setTotalAmount(amount);//付款金额
        model.setProductCode("QUICK_MSECURITY_PAY");
        model.setPassbackParams(passbackParams);//自定义参数
 
 
        //分账
        Integer    coursePackagePayments = coursePackageClient.queryByCode(outTradeNo);
        Integer paymentCompetitions = competitionsClient.queryByCode(outTradeNo);
        Integer siteBookings = siteClient.queryByCode(outTradeNo);
        List<Integer> stores = new ArrayList<>();
        stores.add(coursePackagePayments);
        stores.add(paymentCompetitions);
        stores.add(siteBookings);
 
        OperatorUser operatorUser = siteClient.queryOperator(stores);
 
        String alipayProportion = operatorUser.getAlipayProportion();
        String alipayNum = operatorUser.getAlipayNum();
 
        ExtendParams extendParams = new ExtendParams();
//        extendParams.setSysServiceProviderId("YOUR_SERVICE_PROVIDER_ID");
        model.setExtendParams(extendParams);
 
        RoyaltyInfo royaltyInfo = new RoyaltyInfo();
//        royaltyInfo.setRoyaltyType("transfer");
 
 
        RoyaltyDetailInfos royaltyDetailInfo1 = new RoyaltyDetailInfos();
        royaltyDetailInfo1.setTransOutType("userId");
        royaltyDetailInfo1.setTransOut(aliAppid);
        royaltyDetailInfo1.setTransInType("loginName");
        royaltyDetailInfo1.setTransIn("18398968484");
 
        royaltyDetailInfo1.setDesc("分账描述1");
        royaltyDetailInfo1.setAmountPercentage(alipayProportion);
        List<RoyaltyDetailInfos> royaltyDetailInfos = new ArrayList<>();
 
 
 
 
        royaltyInfo.setRoyaltyDetailInfos(royaltyDetailInfos);
        model.setRoyaltyInfo(royaltyInfo);
        System.err.println("=================="+royaltyInfo);
 
 
        //
        request.setBizModel(model);
        request.setNotifyUrl(callbackPath + notifyUrl);
        try {
            //这里和普通的接口调用不同,使用的是sdkExecute
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            Map<String, String> map = new HashMap<>();
            map.put("orderString", response.getBody());
            System.out.println(map);//就是orderString 可以直接给客户端请求,无需再做处理。
            return ResultUtil.success(map);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return null;
    }
 
 
    /**
     * 支付宝扫码支付下单
     * @param body
     * @param subject
     * @param outTradeNo
     * @param amount
     * @param notifyUrl
     * @return
     */
    public ResultUtil aliScanCodePay(String body, String subject, String outTradeNo, String amount, String notifyUrl){
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", aliAppid, appPrivateKey, "json", "UTF-8", alipay_public_key, "RSA2"); //获得初始化的AlipayClient
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();//创建API对应的request类
        request.setBizContent("{" +
                "    \"out_trade_no\":\"" + outTradeNo + "\"," +//商户订单号
                "    \"total_amount\":\"" + 1 + "\"," +
                "    \"subject\":\"" + subject + "\"," +
                "    \"notify_url\":\"" + callbackPath + notifyUrl + "\"," +
                "    \"body\":\"" + body + "\"," +
                "    \"store_id\":\"NJ_001\"," +
                "    \"timeout_express\":\"90m\"}");//订单允许的最晚付款时间
        AlipayTradePrecreateResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        JSONObject alipay_trade_precreate_response = JSON.parseObject(response.getBody()).getJSONObject("alipay_trade_precreate_response");
 
        System.err.print(alipay_trade_precreate_response.getString("qr_code"));
        return ResultUtil.success(alipay_trade_precreate_response.getString("qr_code"));
    }
 
 
    /**
     * 支付成功后的回调处理逻辑
     * @param request
     */
    public Map<String, String> alipayCallback(HttpServletRequest request){
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + "_";
            }
            //乱码解决,这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        //切记alipaypublickey是支付宝的公钥,请去open.alipay.com对应应用下查看。
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
//        try {
//            boolean flag = AlipaySignature.rsaCheckV1(params, alipay_public_key, "UTF-8","RSA2");
//            if(flag){
//                Map<String, String> map = new HashMap<>();
//                String out_trade_no = params.get("out_trade_no");
//                String subject = params.get("subject");
//                String total_amount = params.get("total_amount");
//                String trade_no = params.get("trade_no");
//                String passback_params = params.get("passback_params");
//                map.put("out_trade_no", out_trade_no);//商家订单号
//                map.put("subject", subject);
//                map.put("total_amount", total_amount);
//                map.put("trade_no", trade_no);//支付宝交易号
//                map.put("passback_params", passback_params);//回传参数
//                return map;
//            }else{
//                System.err.println("验签失败");
//            }
//
//        } catch (AlipayApiException e) {
//            e.printStackTrace();
//        }
//        return null;
 
 
        Map<String, String> map = new HashMap<>();
        String out_trade_no = params.get("out_trade_no");
        String subject = params.get("subject");
        String total_amount = params.get("total_amount");
        String trade_no = params.get("trade_no");
        String passback_params = params.get("passback_params");
        map.put("out_trade_no", out_trade_no);//商家订单号
        map.put("subject", subject);
        map.put("total_amount", total_amount);
        map.put("trade_no", trade_no);//支付宝交易号
        map.put("passback_params", passback_params);//回传参数
        return map;
    }
 
 
    /**
     * 支付宝查询订单支付状态
     * @param out_trade_no
     * @return
     * @throws Exception
     */
    public ResultUtil queryALIOrder(String out_trade_no) throws Exception{
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",aliAppid, appPrivateKey,"json","UTF-8",alipay_public_key,"RSA2");
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        request.setBizContent("{" +
                "  \"out_trade_no\":\"" + out_trade_no + "\"" +
                "}");
        AlipayTradeQueryResponse response = alipayClient.execute(request);
        if(response.isSuccess()){
            String tradeStatus = response.getTradeStatus();//交易状态:WAIT_BUYER_PAY(交易创建,等待买家付款)、TRADE_CLOSED(未付款交易超时关闭,或支付完成后全额退款)、TRADE_SUCCESS(交易支付成功)、TRADE_FINISHED(交易结束,不可退款)
            return ResultUtil.success(tradeStatus);
        } else {
            return ResultUtil.error(response.getMsg());
        }
    }
 
 
 
    /**
     * 微信统一下单
     * @param body          商品描述
     * @param attach        附加数据
     * @param out_trade_no  商户订单号
     * @param total_fee     标价金额
     * @param notify_url    通知地址
     * @param tradeType     交易类型
     * @return
     */
    public ResultUtil weixinpay(String body, String attach, String out_trade_no, String total_fee, String notify_url, String tradeType, String openId) throws Exception{
        int i = new BigDecimal(total_fee).multiply(new BigDecimal("100")).intValue();
        String hostAddress = null;
        try {
            hostAddress = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        String nonce_str = UUIDUtil.getRandomCode(16);
        Map<String, Object> map = new HashMap<>();
        map.put("appid", "APP".equals(tradeType) ? appid : appletsAppid);
        map.put("mch_id", mchId);
        map.put("nonce_str", nonce_str);
        map.put("body", body);
        map.put("attach", attach);//存储订单id
        map.put("out_trade_no", out_trade_no);//存储的订单code
        map.put("total_fee", i);
        map.put("spbill_create_ip", hostAddress);
        map.put("notify_url", callbackPath + notify_url);
        map.put("trade_type", tradeType);
        if("JSAPI".equals(tradeType)){
            map.put("openid", openId);
        }
        String s = this.weixinSignature(map);
        map.put("sign", s);
 
        String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_XML);
        StringBuffer xmlString = new StringBuffer();
        Set<String> strings = map.keySet();
        String[] keys = {};
        keys = strings.toArray(keys);
        Arrays.sort(keys);
        xmlString.append("<xml>");
        for(int l = 0; l < keys.length; l++){
            xmlString.append("<" + keys[l] + ">" + map.get(keys[l]) + "</" + keys[l] + ">");
        }
        xmlString.append("</xml>");
 
        Map<String, String> map1 = null;
        String body1 = HttpClientUtil.pushHttpRequsetXml(url, xmlString.toString(), new HashMap<>()).getData();
        //将结果xml解析成map
        body1 = body1.replaceAll("<!\\[CDATA\\[","");
        body1 = body1.replaceAll("]]>", "");
        try {
            map1 = this.xmlToMap(body1, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        String return_code = map1.get("return_code");
        if("SUCCESS".equals(return_code)){
            String result_code = map1.get("result_code");
            if("SUCCESS".equals(result_code)){
                String type = map1.get("trade_type");
                String prepay_id = map1.get("prepay_id");
 
 
 
 
                switch (type){
                    case "JSAPI":
                        //重新进行签名后返回给前端
                        Map<String, Object> map2 = new HashMap<>();
                        map2.put("appId", map1.get("appid"));
                        map2.put("nonceStr", map1.get("nonce_str"));
                        map2.put("package", "prepay_id=" + prepay_id);
                        map2.put("signType", "MD5");
                        map2.put("timeStamp", new Date().getTime() + "");
                        String s2 = this.weixinSignature(map2);
 
                        map2.put("prepay_id", prepay_id);
                        map2.put("mch_id", map1.get("mch_id"));
                        map2.put("trade_type", map1.get("trade_type"));
 
                        map2.put("sign", s2);
                        return ResultUtil.success(map2);
                    case "NATIVE":
                        String code_url = map1.get("code_url");
                        return ResultUtil.success(code_url);
                    case "APP":
                        //重新进行签名后返回给前端
                        Map<String, Object> map3 = new HashMap<>();
                        map3.put("appid", appid);
                        map3.put("noncestr", nonce_str);
                        map3.put("package", "Sign=WXPay");
                        map3.put("partnerid", mchId);
                        map3.put("prepayid", prepay_id);
                        map3.put("timestamp", new Date().getTime() / 1000);
                        String s1 = this.weixinSignature(map3);
                        map3.put("sign", s1);
                        System.err.println(map3);
                        return ResultUtil.success(map3);
                }
                return null;
            }else{
                System.err.println(map1.get("err_code_des"));
                return ResultUtil.error(map1.get("err_code_des"));
            }
        }else{
            System.err.println(map1.get("return_msg") + appid + "----" + mchId);
            return ResultUtil.error(map1.get("return_msg"), new JSONObject());
        }
    }
 
 
    @Resource
    private RechargeRecordsMapper rereMapper;
 
 
    /**
     * 微信支付成功后的回调处理
     * @param request
     */
    public Map<String, String> weixinpayCallback(HttpServletRequest request){
        try {
            String param = this.getParam(request);
            param = param.replaceAll("<!\\[CDATA\\[","");
            param = param.replaceAll("]]>", "");
            Map<String, String> map = this.xmlToMap(param, "UTF-8");
            String return_code = map.get("return_code");
            if("SUCCESS".equals(return_code)){
                String result_code = map.get("result_code");
                if("SUCCESS".equals(result_code)){
                    Map<String, String> map1 = new HashedMap();
                    map1.put("nonce_str", map.get("nonce_str"));
                    map1.put("out_trade_no", map.get("out_trade_no"));//存储的订单code
                    map1.put("attach", map.get("attach"));//存储订单id
                    map1.put("total_fee", map.get("total_fee"));
                    map1.put("transaction_id", map.get("transaction_id"));//微信支付订单号
                    String result = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
                    map1.put("result", result);
 
 
 
                    return map1;
                }else{
                    System.err.println(map.get("err_code_des"));
                }
            }else{
                System.err.println(map.get("return_msg"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return null;
    }
 
@Resource
private CoursePackageClient coursePackageClient;
    @Resource
    private DeductionCompetitionsClient competitionsClient;
 
    @Resource
    private SiteClient siteClient;
//    @Autowired
//    private WxPayService wxPayService;
    //分账
//    public ResultUtil order(String code) throws Exception {
//
//
//
//                  Integer    coursePackagePayments = coursePackageClient.queryByCode(code);
//                  Integer paymentCompetitions = competitionsClient.queryByCode(code);
//                  Integer siteBookings = siteClient.queryByCode(code);
//        List<Integer> stores = new ArrayList<>();
//                stores.add(coursePackagePayments);
//                stores.add(paymentCompetitions);
//                stores.add(siteBookings);
//
//                OperatorUser operatorUser = siteClient.queryOperator(stores);
//
//
////        WxPayService myWxPayService = wxPayService.switchoverTo("mch_id");
////
////        ProfitSharingV3Service profitSharingV3Service = myWxPayService.getProfitSharingV3Service();
//
//        String nonceStr = RandomUtil.randomString(32);
//        String appId = "您的appid";
//
//
//        //添加分账方
//
////        ProfitSharingReceiver profitSharingReceiver = new ProfitSharingReceiver();
////        profitSharingReceiver.setAccount("appid对应的openId");
////        profitSharingReceiver.setAmount(1l);
////        profitSharingReceiver.setAppid(appId);
////        profitSharingReceiver.setType("PERSONAL_OPENID");
////        profitSharingReceiver.setRelationType("PARTNER");
////        profitSharingV3Service.addProfitSharingReceiver(profitSharingReceiver);
//
//        //分账
//        ProfitSharingRequest profitSharingRequest = new ProfitSharingRequest();
//        profitSharingRequest.setAppid(appId);
//        profitSharingRequest.setTransactionId("微信支付订单号");
//        profitSharingRequest.setOutOrderNo("业务系统唯一编号");
//        //分账完成后,剩余金额自动解冻并返回给商户账号,默认false
//        profitSharingRequest.setUnfreezeUnsplit(true);
//        //待分账金额1元
//        Long money = 1L;
//        List<ProfitSharingReceiver> profitSharingReceivers = new ArrayList<>();
//        ProfitSharingReceiver profitSharingReceiver = new ProfitSharingReceiver();
//        profitSharingReceiver.setAccount("appid对应的openId,分账用户1");
//
//
//        //分账百分之5
//        profitSharingReceiver.setAmount(money * 100 / 5);
//        profitSharingReceiver.setAppid(appId);
//        profitSharingReceiver.setType("PERSONAL_OPENID");
//        profitSharingReceiver.setRelationType("PARTNER");
//        profitSharingReceiver.setDescription("test01");
//        profitSharingReceivers.add(profitSharingReceiver);
//
//        ProfitSharingReceiver receiver = new ProfitSharingReceiver();
//        receiver.setAccount("appid对应的openId,分账用户2");
//        //百分之10
//        receiver.setAmount(money * 100 / 10);
//        receiver.setAppid(appId);
//        receiver.setType("PERSONAL_OPENID");
//        receiver.setRelationType("PARTNER");
//        receiver.setDescription("test02");
//        profitSharingReceivers.add(receiver);
//
//
//        profitSharingRequest.setReceivers(profitSharingReceivers);
//
//        profitSharingV3Service.profitSharing(profitSharingRequest);
//
//
//
//
////                    Map<String,String> headers = new HashMap<>();
////                    headers.put("Authorization",map.get("sign"));
////                    headers.put("Accept","application/json");
////                    headers.put("Wechatpay-Serial",certPath);
////
////                    List<Receivers> receivers = new ArrayList<>();
////
////                    Map<String,Object> body = new HashMap<>();
////                    body.put("appid",appid);
////                    body.put("transaction_id",map.get("transaction_id"));
////                    body.put("out_order_no",map.get("out_trade_no"));
////                    body.put("receivers",receivers);
////                    body.put("unfreeze_unsplit",true);
//
//                    //支付分账
////                    String url ="https://api.mch.weixin.qq.com/v3/profitsharing/orders";
////                    CloseableHttpResponse closeableHttpResponse = HttpClientUtil.setPostHttpRequset(url, body, headers, "application/json");
////
//
//            return  null;
//
//
//
//
//    }
 
    /**
     * 微信扫码收款
     * @param body              商品描述
     * @param attach            附加数据
     * @param nonce_str         随机字符串
     * @param out_trade_no      商户订单号
     * @param total_fee         订单金额
     * @param auth_code         授权码    扫码支付授权码,设备读取用户微信中的条码或者二维码信息(注:用户付款码条形码规则:18位纯数字,以10、11、12、13、14、15开头)
     * @return
     */
    public ResultUtil wxScanQRCodePay(String body, String attach, String nonce_str, String out_trade_no, String total_fee, String auth_code){
        int i = new BigDecimal(total_fee).multiply(new BigDecimal("100")).intValue();
        String hostAddress = null;
        try {
            InetAddress address = InetAddress.getLocalHost();
            hostAddress = address.getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        String randomCode = null;
        try {
            randomCode = UUIDUtil.getRandomCode(10);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String, Object> map = new HashMap<>();
        map.put("appid", appid);
        map.put("mch_id", mchId);
        map.put("nonce_str", nonce_str);//存储的支付人员id,员工扫描二维码支付的时候存储的是收款员工id
        map.put("body", body);
        map.put("attach", attach);//存储的费用月份数据,员工扫描二维码支付的时候存储的是收费项id
        map.put("out_trade_no", randomCode + "_" + out_trade_no);//存储的房间id
        map.put("total_fee", i);
        map.put("spbill_create_ip", hostAddress);
        map.put("auth_code", auth_code);
        String s = this.weixinSignature(map);
        map.put("sign", s);
 
        String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_XML);
        StringBuffer xmlString = new StringBuffer();
        Set<String> strings = map.keySet();
        String[] keys = {};
        keys = strings.toArray(keys);
        Arrays.sort(keys);
        xmlString.append("<xml>");
        for(int l = 0; l < keys.length; l++){
            xmlString.append("<" + keys[l] + ">" + map.get(keys[l]) + "</" + keys[l] + ">");
        }
        xmlString.append("</xml>");
 
        Map<String, String> map1 = null;
        String body1 = null;
        try {
            body1 = HttpClientUtil.pushHttpRequsetXml(url, xmlString.toString(), new HashMap<>()).getData();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //将结果xml解析成map
        body1 = body1.replaceAll("<!\\[CDATA\\[","");
        body1 = body1.replaceAll("]]>", "");
        try {
            map1 = this.xmlToMap(body1, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        String return_code = map1.get("return_code");
        if("SUCCESS".equals(return_code)){
            String result_code = map1.get("result_code");
            if("SUCCESS".equals(result_code)){
                String type = map1.get("trade_type");
                switch (type){
                    case "JSAPI":
                        break;
                    case "NATIVE":
                        String code_url = map1.get("code_url");
                        return ResultUtil.success(code_url);
                    case "APP":
                        String prepay_id = map1.get("prepay_id");
                        //重新进行签名后返回给前端
                        Map<String, Object> map2 = new HashMap<>();
                        map2.put("appid", appid);
                        map2.put("noncestr", nonce_str);
                        map2.put("package", "Sign=WXPay");
                        map2.put("partnerid", mchId);
                        map2.put("prepayid", prepay_id);
                        map2.put("timestamp", new Date().getTime() + "");
                        String s1 = this.weixinSignature(map2);
 
                        map2.put("pac", "Sign=WXPay");
                        map2.put("sign", s1);
//                      System.err.println(map2);
                        return ResultUtil.success(map2);
                }
                return null;
            }else{
//                System.err.println(map1.get("err_code_des"));
                return ResultUtil.error(map1.get("err_code_des"));
            }
        }else{
//            System.err.println(map1.get("return_msg") + appid + "----" + mchId);
            return ResultUtil.error(map1.get("return_msg"), new JSONObject());
        }
    }
 
 
    /**
     * 支付宝扫码收款
     * @param data
     * @return
     */
    public Object aliScanQRCodePay(String data){
        return null;
    }
 
 
    /**
     * 微信退款申请
     * @param transaction_id    微信订单号。微信生成的订单号,在支付通知中有返回
     * @param out_refund_no     商户退款单号。商户系统内部的退款单号,商户系统内部唯一,只能是数字、大小写字母_-|*@ ,同一退款单号多次请求只退一笔。
     * @param total_fee         订单金额。订单总金额,单位为分,只能为整数
     * @param refund_fee        退款金额。退款总金额,订单总金额,单位为分,只能为整数
     * @param notify_url        退款结果通知url。异步接收微信支付退款结果通知的回调地址,通知URL必须为外网可访问的url,不允许带参数 如果参数中传了notify_url,则商户平台上配置的回调地址将不会生效。
     * @return
     */
    public Map<String, String> wxRefund(String transaction_id, String out_refund_no, String total_fee, String refund_fee, String notify_url){
        int tf = new BigDecimal(total_fee).multiply(new BigDecimal("100")).intValue();
        int rf = new BigDecimal(refund_fee).multiply(new BigDecimal("100")).intValue();
        String nonce_str = UUIDUtil.getRandomCode();
        Map<String, Object> map = new HashMap<>();
        map.put("appid", appid);
        map.put("mch_id", mchId);
        map.put("nonce_str", nonce_str);
        map.put("transaction_id", transaction_id);
        map.put("out_refund_no", out_refund_no);
        map.put("total_fee", tf);
        map.put("refund_fee", rf);
        map.put("notify_url", callbackPath + notify_url);
        String s = this.weixinSignature(map, key);
        map.put("sign", s);
 
        String url = "https://api.mch.weixin.qq.com/secapi/pay/refund";
        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_XML);
        StringBuffer xmlString = new StringBuffer();
        Set<String> strings = map.keySet();
        String[] keys = {};
        keys = strings.toArray(keys);
        Arrays.sort(keys);
        xmlString.append("<xml>");
        for(int l = 0; l < keys.length; l++){
            xmlString.append("<" + keys[l] + ">" + map.get(keys[l]) + "</" + keys[l] + ">");
        }
        xmlString.append("</xml>");
 
        Map<String, String> map1 = null;
        String body1 = null;
        try {
            body1 = HttpClientUtil.pushHttpsRequsetXml(url, xmlString.toString(), new HashMap<>(), mchId, certPath, "PKCS12");
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.err.println(body1);
        //将结果xml解析成map
        body1 = body1.replaceAll("<!\\[CDATA\\[","");
        body1 = body1.replaceAll("]]>", "");
        try {
            map1 = this.xmlToMap(body1, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        String return_code = map1.get("return_code");
        Map<String, String> map2 = new HashMap<>();
        if("SUCCESS".equals(return_code)){
            String result_code = map1.get("result_code");
            if("SUCCESS".equals(result_code)){
                map2.put("return_code", result_code);
                map2.put("refund_id", String.valueOf(map1.get("refund_id")));//微信退款订单号
                map2.put("refund_fee", String.valueOf(map1.get("refund_fee")));//退款金额
                return map2;
            }else{
                map2.put("return_code", result_code);
                map2.put("return_msg", map1.get("err_code_des"));
                return map2;
            }
        }else{
            map2.put("return_code", return_code);
            map2.put("return_msg", map1.get("return_msg"));
            return map2;
        }
    }
 
 
    /**
     * 微信退款成功后的回调处理
     * @param request
     * @return
     */
    public Map<String, String> wxRefundCallback(HttpServletRequest request){
        try {
            String param = this.getParam(request);
            param = param.replaceAll("<!\\[CDATA\\[","");
            param = param.replaceAll("]]>", "");
            Map<String, String> map = this.xmlToMap(param, "UTF-8");
            String return_code = map.get("return_code");
            if("SUCCESS".equals(return_code)){
                String req_info = map.get("req_info");//加密信息请用商户秘钥进行解密
                String s = this.wxDecrypt(req_info);
                s = s.replaceAll("<!\\[CDATA\\[","");
                s = s.replaceAll("]]>", "");
                map = this.xmlToMap(s, "UTF-8");
                Map<String, String> map1 = new HashMap<>();
                map1.put("refund_id", map.get("refund_id"));
                map1.put("out_refund_no", map.get("out_refund_no"));
                String result = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
                map1.put("result", result);
                return map1;
            }else{
//                System.err.println(map.get("return_msg"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        }
        return null;
    }
 
 
    /**
     * 支付宝退款
     * @param trade_no          支付宝交易号
     * @param refund_amount     退款金额
     * @return
     * @throws AlipayApiException
     */
    public Map<String, String> aliRefund(String trade_no, String refund_amount) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", aliAppid, appPrivateKey,"json","UTF-8", alipay_public_key,"RSA2");
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("trade_no", trade_no);
        jsonObject.put("refund_amount", refund_amount);
        request.setBizContent(jsonObject.toJSONString());
        AlipayTradeRefundResponse response = alipayClient.execute(request);
        Map<String, String> map = new HashMap<>();
        if(response.isSuccess()){
            System.out.println("调用成功");
            String outTradeNo = response.getOutTradeNo();
            map.put("code", response.getCode());//10000
            map.put("trade_no", response.getTradeNo());//支付宝交易号
            map.put("out_trade_no", outTradeNo);//商户订单号
        } else {
            System.out.println("调用失败");
            map.put("code", response.getCode());
            map.put("msg", response.getSubMsg());
        }
        return map;
    }
 
 
    /**
     * 查询微信支付订单
     * @return
     * @throws Exception
     */
    public ResultUtil<Map<String, String>> queryWXOrder(String out_trade_no, String transaction_id) throws Exception{
        String url = "https://api.mch.weixin.qq.com/pay/orderquery";
        String nonce_str = UUIDUtil.getRandomCode(16);
        Map<String, Object> map = new HashMap<>();
        map.put("appid", appid);
        map.put("mch_id", mchId);
        map.put("out_trade_no", out_trade_no);//商户订单号
        map.put("transaction_id", transaction_id);//微信订单号
        map.put("nonce_str", nonce_str);//随机字符串
        String s = this.weixinSignature(map);
        map.put("sign", s);
 
        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_XML);
        StringBuffer xmlString = new StringBuffer();
        Set<String> strings = map.keySet();
        String[] keys = {};
        keys = strings.toArray(keys);
        Arrays.sort(keys);
        xmlString.append("<xml>");
        for(int l = 0; l < keys.length; l++){
            xmlString.append("<" + keys[l] + ">" + map.get(keys[l]) + "</" + keys[l] + ">");
        }
        xmlString.append("</xml>");
 
        Map<String, String> map1 = null;
        String body1 = HttpClientUtil.pushHttpRequsetXml(url, xmlString.toString(), new HashMap<>()).getData();
        //将结果xml解析成map
        body1 = body1.replaceAll("<!\\[CDATA\\[","");
        body1 = body1.replaceAll("]]>", "");
        try {
            map1 = this.xmlToMap(body1, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        String return_code = map1.get("return_code");
        if("SUCCESS".equals(return_code)){
            String result_code = map1.get("result_code");
            if("SUCCESS".equals(result_code)){
                Map<String, String> map2 = new HashMap<>();
                map2.put("trade_type", map1.get("trade_type"));
                map2.put("trade_state", map1.get("trade_state"));//订单状态SUCCESS—支付成功,REFUND—转入退款,NOTPAY—未支付,CLOSED—已关闭,REVOKED—已撤销(刷卡支付),USERPAYING--用户支付中,PAYERROR--支付失败(其他原因,如银行返回失败)
                map2.put("transaction_id", map1.get("transaction_id"));
                return ResultUtil.success(map2);
            }else{
                System.err.println(map1.get("err_code_des"));
                return ResultUtil.error(map1.get("err_code_des"));
            }
        }else{
            System.err.println(map1.get("return_msg") + appid + "----" + mchId);
            return ResultUtil.error(map1.get("return_msg"));
        }
    }
 
 
 
    /**
     * 微信转账功能(企业付款到零钱)
     * @param openid                商户appid下,某用户的openid
     * @param desc                  企业付款备注,必填。
     * @param total_fee             企业付款金额
     * @param partner_trade_no      商户订单号,需保持唯一性
     * @return
     */
    public Map<String, String> wxTransfers(String openid, String desc, String total_fee, String partner_trade_no) throws Exception{
        int amount = new BigDecimal(total_fee).multiply(new BigDecimal("100")).intValue();
        String nonce_str = UUIDUtil.getRandomCode();
        Map<String, Object> map = new HashMap<>();
        map.put("mch_appid", appid);//申请商户号的appid或商户号绑定的appid
        map.put("mchid", mchId);//微信支付分配的商户号
        map.put("nonce_str", nonce_str);//随机字符串,不长于32位
        map.put("partner_trade_no", partner_trade_no);//商户订单号,需保持唯一性
        map.put("openid", openid);//商户appid下,某用户的openid
        map.put("check_name", "NO_CHECK");//NO_CHECK:不校验真实姓名 FORCE_CHECK:强校验真实姓名
        map.put("amount", amount);//企业付款金额,单位为分
        map.put("desc", desc);//企业付款备注,必填。
        String s = this.weixinSignature(map, key);
        map.put("sign", s);
 
        String url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";
        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_XML);
        StringBuffer xmlString = new StringBuffer();
        Set<String> strings = map.keySet();
        String[] keys = {};
        keys = strings.toArray(keys);
        Arrays.sort(keys);
        xmlString.append("<xml>");
        for(int l = 0; l < keys.length; l++){
            xmlString.append("<" + keys[l] + ">" + map.get(keys[l]) + "</" + keys[l] + ">");
        }
        xmlString.append("</xml>");
 
        Map<String, String> map1 = null;
        String body1 = HttpClientUtil.pushHttpsRequsetXml(url, xmlString.toString(), new HashMap<>(), mchId, certPath, "PKCS12");
        //将结果xml解析成map
        body1 = body1.replaceAll("<!\\[CDATA\\[","");
        body1 = body1.replaceAll("]]>", "");
        try {
            map1 = this.xmlToMap(body1, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        String return_code = map1.get("return_code");
        Map<String, String> map2 = new HashMap<>();
        if("SUCCESS".equals(return_code)){
            String result_code = map1.get("result_code");
            if("SUCCESS".equals(result_code)){
                map2.put("return_code", result_code);
                map2.put("payment_no", String.valueOf(map1.get("payment_no")));//付款订单号
                map2.put("payment_time", String.valueOf(map1.get("payment_time")));//付款时间
                return map2;
            }else{
                map2.put("return_code", result_code);
                map2.put("err_code", map1.get("err_code"));
                map2.put("err_code_des", map1.get("err_code_des"));
                return map2;
            }
        }else{
            map2.put("return_code", return_code);
            map2.put("return_msg", map1.get("return_msg"));
            return map2;
        }
    }
 
 
    /**
     * 微信转账功能(企业付款到银行卡)
     * @param desc              备注信息
     * @param total_fee         转账金额
     * @param partner_trade_no  订单号
     * @param enc_bank_no       银行卡号
     * @param enc_true_name     收款方用户名
     * @param bankName          银行名称
     * @return
     * @throws Exception
     */
    public Map<String, String> wxPayBank(String desc, String total_fee, String partner_trade_no, String enc_bank_no, String enc_true_name, String bankName) throws Exception{
        int amount = new BigDecimal(total_fee).multiply(new BigDecimal("100")).intValue();
        String nonce_str = UUIDUtil.getRandomCode();
        Map<String, Object> map = new HashMap<>();
        map.put("mch_id", mchId);//微信支付分配的商户号
        map.put("nonce_str", nonce_str);//随机字符串,不长于32位
        map.put("partner_trade_no", partner_trade_no);//商户订单号,需保持唯一性
        map.put("enc_bank_no", enc_bank_no);//收款方银行卡号(采用标准RSA算法,公钥由微信侧提供)
        map.put("enc_true_name", enc_true_name);//收款方用户名(采用标准RSA算法,公钥由微信侧提供)
        map.put("bank_code", findBankCode(bankName));//
        map.put("amount", amount);//企业付款金额,单位为分
        map.put("desc", desc);//企业付款备注,必填。
        String s = this.weixinSignature(map, key);
        map.put("sign", s);
 
        String url = "https://api.mch.weixin.qq.com/mmpaysptrans/pay_bank";
        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_XML);
        StringBuffer xmlString = new StringBuffer();
        Set<String> strings = map.keySet();
        String[] keys = {};
        keys = strings.toArray(keys);
        Arrays.sort(keys);
        xmlString.append("<xml>");
        for(int l = 0; l < keys.length; l++){
            xmlString.append("<" + keys[l] + ">" + map.get(keys[l]) + "</" + keys[l] + ">");
        }
        xmlString.append("</xml>");
 
        Map<String, String> map1 = null;
        String body1 = HttpClientUtil.pushHttpsRequsetXml(url, xmlString.toString(), new HashMap<>(), mchId, certPath, "PKCS12");
        //将结果xml解析成map
        body1 = body1.replaceAll("<!\\[CDATA\\[","");
        body1 = body1.replaceAll("]]>", "");
        try {
            map1 = this.xmlToMap(body1, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        String return_code = map1.get("return_code");
        Map<String, String> map2 = new HashMap<>();
        if("SUCCESS".equals(return_code)){
            String result_code = map1.get("result_code");
            if("SUCCESS".equals(result_code)){
                map2.put("return_code", result_code);
                map2.put("payment_no", String.valueOf(map1.get("payment_no")));//付款订单号
                map2.put("cmms_amt", String.valueOf(map1.get("cmms_amt")));//手续费金额 RMB:分
                return map2;
            }else{
                map2.put("return_code", result_code);
                map2.put("err_code", map1.get("err_code"));
                map2.put("err_code_des", map1.get("err_code_des"));
                return map2;
            }
        }else{
            map2.put("return_code", return_code);
            map2.put("return_msg", map1.get("return_msg"));
            return map2;
        }
    }
 
    /**
     * 微信转账到银行卡不编号
     * @param bankName
     * @return
     */
    public String findBankCode(String bankName){
        String json = "{\"工商银行 \":1002,\"农业银行\":1005,\"建设银行\":1003,\"中国银行\":1026,\"交通银行 \":1020,\"招商银行 \":1001,\"邮储银行\":1066,\"民生银行 \":1006,\"平安银行 \":1010,\"中信银行\":1021,\"浦发银行 \":1004,\"兴业银行 \":1009,\"光大银行 \":1022,\"广发银行\":1027,\"华夏银行\":1025,\"宁波银行\":1056,\"北京银行\":4836,\"上海银行\":1024,\"南京银行\":1054,\"长子县融汇村镇银行\":4755,\"长沙银行\":4216,\"浙江泰隆商业银行\":4051,\"中原银行 \":4753,\"企业银行(中国)\":4761,\"顺德农商银行 \":4036,\"衡水银行\":4752,\"长治银行\":4756,\"大同银行\":4767,\"河南省农村信用社\":4115,\"宁夏黄河农村商业银行\":4150,\"山西省农村信用社\":4156,\"安徽省农村信用社\":4166,\"甘肃省农村信用社\":4157,\"天津农村商业银行\":4153,\"广西壮族自治区农村信用社\":4113,\"陕西省农村信用社\":4108,\"深圳农村商业银行\":4076,\"宁波鄞州农村商业银行\":4052,\"浙江省农村信用社联合社\":4764,\"江苏省农村信用社联合社\":4217,\"江苏紫金农村商业银行股份有限公司 \":4072,\"北京中关村银行股份有限公司 \":4769,\"星展银行( 中国) 有限公司 \":4778,\"枣庄银行股份有限公司 \":4766,\"海口联合农村商业银行股份有限公司 \":4758,\"南洋商业银行( 中国) 有限公司 \":4763}";
        JSONObject jsonObject = JSON.parseObject(json);
        Set<String> strings = jsonObject.keySet();
        for(String key : strings){
            if(key.indexOf(bankName) >= 0){
                return jsonObject.getString(key);
            }
        }
        return "";
    }
 
 
 
    /**
     * 支付宝转账
     * @param out_biz_no        商家侧唯一订单号,由商家自定义。对于不同转账请求,商家需保证该订单号在自身系统唯一。
     * @param trans_amount      订单总金额,单位为元,精确到小数点后两位
     * @param order_title       转账业务的标题,用于在支付宝用户的账单里显示
     * @param identity          参与方的唯一标识(收款方支付宝账号)
     * @param name              参与方真实姓名,如果非空,将校验收款支付宝账号姓名一致性。
     * @param remark            业务备注
     * @return
     * @throws Exception
     */
    public Map<String, Object> aliTransfer(String out_biz_no, Double trans_amount, String order_title, String identity, String name, String remark) throws Exception{
        CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
        certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do");  //gateway:支付宝网关(固定)https://openapi.alipay.com/gateway.do
        certAlipayRequest.setAppId(aliAppid);  //APPID 即创建应用后生成,详情见创建应用并获取 APPID
        certAlipayRequest.setPrivateKey(appPrivateKey);  //开发者应用私钥,由开发者自己生成
        certAlipayRequest.setFormat("json");  //参数返回格式,只支持 json 格式
        certAlipayRequest.setCharset("UTF-8");  //请求和签名使用的字符编码格式,支持 GBK和 UTF-8
        certAlipayRequest.setSignType("RSA2");  //商户生成签名字符串所使用的签名算法类型,目前支持 RSA2 和 RSA,推荐商家使用 RSA2。
        certAlipayRequest.setCertPath(app_cert_path); //应用公钥证书路径(app_cert_path 文件绝对路径)
        certAlipayRequest.setAlipayPublicCertPath(alipay_cert_path); //支付宝公钥证书文件路径(alipay_cert_path 文件绝对路径)
        certAlipayRequest.setRootCertPath(alipay_root_cert_path);  //支付宝CA根证书文件路径(alipay_root_cert_path 文件绝对路径)
        AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
        AlipayFundTransUniTransferRequest request = new AlipayFundTransUniTransferRequest();
        request.setBizContent("{" +
                "\"out_biz_no\":\"" + out_biz_no + "\"," +
                "\"trans_amount\":" + trans_amount + "," +
                "\"product_code\":\"TRANS_ACCOUNT_NO_PWD\"," +
                "\"biz_scene\":\"DIRECT_TRANSFER\"," +
                "\"order_title\":\"" + order_title + "\"," +
                "\"payee_info\":{" +
                "\"identity\":\"" + identity + "\"," +
                "\"identity_type\":\"ALIPAY_USER_ID\"," +
                "\"name\":\"" + name + "\"," +
                "}," +
                "\"remark\":\"" + remark + "\"" +
                "}");
        AlipayFundTransUniTransferResponse response = alipayClient.certificateExecute(request);
        Map<String, Object> map = new HashMap<>();
        if(response.isSuccess()){
            String status = response.getStatus();
            if(status.equals("SUCCESS")){//成功
                map.put("code", response.getCode());
                map.put("order_id", response.getOrderId());//支付宝订单号
                map.put("pay_fund_order_id", response.getPayFundOrderId());//支付宝流水号
            }else{
                map.put("code", response.getCode());
                map.put("sub_msg", response.getSubMsg());
            }
        } else {
            map.put("code", response.getSubCode());
            map.put("sub_msg", response.getSubMsg());
        }
        return map;
    }
 
 
    /**
     * 获取请求内容
     * @param request
     * @return
     * @throws IOException
     */
    private String getParam(HttpServletRequest request) throws IOException {
        // 读取参数
        InputStream inputStream;
        StringBuilder sb = new StringBuilder();
        inputStream = request.getInputStream();
        String s;
        BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        while ((s = in.readLine()) != null) {
            sb.append(s);
        }
        in.close();
        inputStream.close();
        return sb.toString();
    }
 
 
    /**
     * 微信下单的签名算法
     * @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;
    }
 
 
    /**
     * 微信下单的签名算法
     * @param map
     * @return
     */
    private String weixinSignature(Map<String, Object> map, String key_){
        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;
    }
 
 
    /**
     * 微信退款成功后的解密
     * @param req_info
     * @return
     */
    private String wxDecrypt(String req_info) throws NoSuchPaddingException, NoSuchAlgorithmException, NoSuchProviderException,
            InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        byte[] decode = Base64.getDecoder().decode(req_info);
        String sign = MD5AndKL.MD5Encode(key, "UTF-8").toLowerCase();
        if (Security.getProvider("BC") == null){
            Security.addProvider(new BouncyCastleProvider());
        }
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC");
        SecretKeySpec secretKeySpec = new SecretKeySpec(sign.getBytes(), "AES");
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        return new String(cipher.doFinal(decode));
    }
 
 
//    public static void main(String[] ages){
//        PayMoneyUtil payMoneyUtil = new PayMoneyUtil();
//        ResultUtil ce = payMoneyUtil.alipay("测试", "测试", "", "121456457", "10", "http://123.com");
//        System.err.println(ce);
//        ResultUtil resultUtil = null;
//        try {
//            resultUtil = payMoneyUtil.queryALIOrder("121456457");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        System.err.println(resultUtil);
//    }
 
 
    /**
     * xml转map
     * @param xml
     * @param charset
     * @return
     * @throws UnsupportedEncodingException
     * @throws DocumentException
     */
    public static Map<String, String> xmlToMap(String xml, String charset) throws UnsupportedEncodingException, DocumentException {
 
        Map<String, String> respMap = new HashMap<String, String>();
 
        SAXReader reader = new SAXReader();
        Document doc = reader.read(new ByteArrayInputStream(xml.getBytes(charset)));
        Element root = doc.getRootElement();
        xmlToMap(root, respMap);
        return respMap;
    }
 
    public static Map<String, String> xmlToMap(Element tmpElement, Map<String, String> respMap){
        if (tmpElement.isTextOnly()) {
            respMap.put(tmpElement.getName(), tmpElement.getText());
            return respMap;
        }
 
        @SuppressWarnings("unchecked")
        Iterator<Element> eItor = tmpElement.elementIterator();
        while (eItor.hasNext()) {
            Element element = eItor.next();
            xmlToMap(element, respMap);
        }
        return respMap;
    }
}