admin
2021-06-29 0a03971cf8b1ca89f171946ecce8e8e6435b9ec5
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
package org.yeshi.utils.alipay;
 
import com.alipay.api.*;
import com.alipay.api.Signer;
import com.alipay.api.internal.parser.json.ObjectJsonParser;
import com.alipay.api.internal.parser.xml.ObjectXmlParser;
import com.alipay.api.internal.util.*;
import com.alipay.api.internal.util.codec.Base64;
import com.alipay.api.internal.util.file.Charsets;
import com.alipay.api.internal.util.file.FileUtils;
import com.alipay.api.internal.util.file.IOUtils;
import com.alipay.api.internal.util.json.JSONWriter;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
 
import javax.net.ssl.SSLException;
import java.io.*;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.security.*;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
 
 
/**
 * @author liuqun.lq
 * @version $Id: AbstractAlipayClient.java, v 0.1 2018-07-03 10:45:21 liuqun.lq Exp $
 */
public abstract class MyAbstractAlipayClient implements AlipayClient {
    private String serverUrl;
    private String appId;
    private String prodCode;
    private String format = AlipayConstants.FORMAT_JSON;
    private String signType = AlipayConstants.SIGN_TYPE_RSA;
    private String encryptType = AlipayConstants.ENCRYPT_TYPE_AES;
 
    private String charset;
 
    private int connectTimeout = 3000;
    private int readTimeout = 15000;
 
    private String proxyHost;
    private int proxyPort;
    private SignChecker signChecker;
 
    private String appCertSN;
    private String alipayCertSN;
    private String alipayRootCertSN;
    private String alipayRootSm2CertSN;
    private String rootCertContent;
    private X509Certificate cert;
    private ConcurrentHashMap<String, X509Certificate> alipayPublicCertMap;
    private ConcurrentHashMap<String, String> alipayPublicKeyMap;
 
    protected boolean loadTest = false;
 
    static {
        //清除安全设置
        Security.setProperty("jdk.certpath.disabledAlgorithms", "");
 
    }
 
    /**
     * 批量API默认分隔符
     **/
    private static final String BATCH_API_DEFAULT_SPLIT = "#S#";
 
    public MyAbstractAlipayClient(String serverUrl, String appId, String format,
                                  String charset, String signType) {
        this.serverUrl = serverUrl;
        this.appId = appId;
        if (!StringUtils.isEmpty(format)) {
            this.format = format;
        }
        this.charset = charset;
        if (!StringUtils.isEmpty(signType)) {
            this.signType = signType;
        }
    }
 
    public MyAbstractAlipayClient(String serverUrl, String appId, String format,
                                  String charset, String signType, InputStream certInput,
                                  InputStream alipayPublicCertInput, InputStream rootCertInput, String proxyHost,
                                  int proxyPort, String encryptType) throws AlipayApiException {
        this(serverUrl, appId, format, charset, signType);
        if (!StringUtils.isEmpty(encryptType)) {
            this.encryptType = encryptType;
        }
        this.proxyHost = proxyHost;
        this.proxyPort = proxyPort;
        //读取根证书(用来校验本地支付宝公钥证书失效后自动从网关下载的新支付宝公钥证书是否有效)
        this.rootCertContent = readStreamToString(rootCertInput);
        //alipayRootCertSN根证书序列号
        if (AlipayConstants.SIGN_TYPE_SM2.equals(signType)) {
            this.alipayRootSm2CertSN = AntCertificationUtil.getRootCertSN(this.rootCertContent, "SM2");
        } else {
            this.alipayRootCertSN = AntCertificationUtil.getRootCertSN(this.rootCertContent);
            if (StringUtils.isEmpty(this.alipayRootCertSN)) {
                throw new AlipayApiException("AlipayRootCert Is Invalid");
            }
        }
        //获取应用证书
        this.cert = getCert(certInput);
        //获取支付宝公钥证书
        X509Certificate alipayPublicCert = getCert(alipayPublicCertInput);
 
        //appCertSN为最终发送给网关的应用证书序列号
        this.appCertSN = getCertSN(cert);
        if (StringUtils.isEmpty(this.appCertSN)) {
            throw new AlipayApiException("AppCert Is Invalid");
        }
        //alipayCertSN为支付宝公钥证书序列号
        this.alipayCertSN = getCertSN(alipayPublicCert);
        //将公钥证书以序列号为key存入map
        ConcurrentHashMap<String, X509Certificate> alipayPublicCertMap = new ConcurrentHashMap<String, X509Certificate>();
        alipayPublicCertMap.put(alipayCertSN, alipayPublicCert);
        this.alipayPublicCertMap = alipayPublicCertMap;
        //获取支付宝公钥以序列号为key存入map
        PublicKey publicKey = alipayPublicCert.getPublicKey();
        ConcurrentHashMap<String, String> alipayPublicKeyMap = new ConcurrentHashMap<String, String>();
        alipayPublicKeyMap.put(alipayCertSN, Base64.encodeBase64String(publicKey.getEncoded()));
        this.alipayPublicKeyMap = alipayPublicKeyMap;
    }
 
    /**
     * @param inputStream 证书路径
     * @return
     * @throws AlipayApiException
     */
    private X509Certificate getCert(InputStream inputStream) throws AlipayApiException {
        try {
            Security.addProvider(new BouncyCastleProvider());
            CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");
            X509Certificate cert = (X509Certificate) cf.generateCertificate(inputStream);
            return cert;
 
        } catch (NoSuchProviderException e) {
            throw new AlipayApiException(e);
        } catch (CertificateException e) {
            throw new AlipayApiException(e);
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                throw new AlipayApiException(e);
            }
        }
    }
 
    private String getCertSN(X509Certificate cf) throws AlipayApiException {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update((cf.getIssuerX500Principal().getName() + cf.getSerialNumber()).getBytes());
            String certSN = new BigInteger(1, md.digest()).toString(16);
            //BigInteger会把0省略掉,需补全至32位
            certSN = fillMD5(certSN);
            return certSN;
        } catch (NoSuchAlgorithmException e) {
            throw new AlipayApiException(e);
        }
    }
 
    private static String fillMD5(String md5) {
        return md5.length() == 32 ? md5 : fillMD5("0" + md5);
    }
 
    private String readFileToString(String rootCertPath) throws AlipayApiException {
        try {
            File file = new File(rootCertPath);
            String client = FileUtils.readFileToString(file);
            return client;
        } catch (IOException e) {
            throw new AlipayApiException(e);
        }
 
    }
 
    private String readStreamToString(InputStream inputStream) throws AlipayApiException {
        try {
            return IOUtils.toString(inputStream, Charsets.toCharset(Charset.defaultCharset()));
        } catch (IOException e) {
            throw new AlipayApiException(e);
        }
    }
 
    //校验证书有效期以及是否支付宝颁发
    private boolean verifyCert(String cert) {
        return AntCertificationUtil.isTrusted(cert, this.rootCertContent);
    }
 
    public <T extends AlipayResponse> T certificateExecute(AlipayRequest<T> request) throws AlipayApiException {
        return certificateExecute(request, null);
    }
 
    public <T extends AlipayResponse> T certificateExecute(AlipayRequest<T> request, String accessToken) throws AlipayApiException {
 
        return certificateExecute(request, accessToken, null);
    }
 
    public <T extends AlipayResponse> T certificateExecute(AlipayRequest<T> request, String accessToken,
                                                           String appAuthToken) throws AlipayApiException {
 
        return _certificateExecute(request, accessToken, appAuthToken, null);
    }
 
    public <T extends AlipayResponse> T certificateExecute(AlipayRequest<T> request, String accessToken,
                                                           String appAuthToken, String targetAppId) throws AlipayApiException {
 
        return _certificateExecute(request, accessToken, appAuthToken, targetAppId);
    }
 
    public <T extends AlipayResponse> T _certificateExecute(AlipayRequest<T> request, String accessToken,
                                                            String appAuthToken, String targetAppId) throws AlipayApiException {
        T tRsp = null;
        try {
            long beginTime = System.currentTimeMillis();
            Map<String, Object> rt = doPost(request, accessToken, appAuthToken, this.appCertSN, targetAppId);
 
            Map<String, Long> costTimeMap = new HashMap<String, Long>();
            if (rt.containsKey("prepareTime")) {
                costTimeMap.put("prepareCostTime", (Long) (rt.get("prepareTime")) - beginTime);
                if (rt.containsKey("requestTime")) {
                    costTimeMap.put("requestCostTime", (Long) (rt.get("requestTime")) - (Long) (rt.get("prepareTime")));
                }
            }
            AlipayParser<T> parser = null;
            if (AlipayConstants.FORMAT_XML.equals(this.format)) {
                parser = new ObjectXmlParser<T>(request.getResponseClass());
            } else {
                parser = new ObjectJsonParser<T>(request.getResponseClass());
            }
            // 若需要解密则先解密
            ResponseEncryptItem responseItem = decryptResponse(request, rt, parser);
            // 解析实际串
            tRsp = parser.parse(responseItem.getRealContent());
            tRsp.setBody(responseItem.getRealContent());
            checkResponseCertSign(request, parser, responseItem.getRespContent(), tRsp.isSuccess());
 
            if (costTimeMap.containsKey("requestCostTime")) {
                costTimeMap.put("postCostTime", System.currentTimeMillis() - (Long) (rt.get("requestTime")));
            }
 
            tRsp.setParams((AlipayHashMap) rt.get("textParams"));
            if (!tRsp.isSuccess()) {
                AlipayLogger.logErrorScene(rt, tRsp, "", costTimeMap);
            } else {
                AlipayLogger.logBizSummary(rt, tRsp, costTimeMap);
            }
            return tRsp;
        } catch (RuntimeException e) {
            AlipayLogger.logBizError(e);
            throw new AlipayApiException(e);
        } catch (AlipayApiException e) {
            AlipayLogger.logBizError(e);
            throw new AlipayApiException(e);
        }
    }
 
    /**
     * 检查响应签名
     *
     * @param request
     * @param parser
     * @param responseBody
     * @param responseIsSuccess
     * @throws AlipayApiException
     */
    private <T extends AlipayResponse> void checkResponseCertSign(AlipayRequest<T> request,
                                                                  AlipayParser<T> parser,
                                                                  String responseBody,
                                                                  boolean responseIsSuccess) throws AlipayApiException {
        CertItem certItem = parser.getCertItem(request, responseBody);
        if (certItem == null) {
            throw new AlipayApiException("cert check fail: Body is Empty!");
        }
        if (certItem.getCert() == null && responseIsSuccess
                && !request.getApiMethodName().equals(AlipayOpenAppAlipaycertDownloadRequest.ALIPAYCERT_DOWNLOAD)) {
            throw new AlipayApiException("cert check fail: ALIPAY_CERT_SN is Empty!");
        }
        String alipayPublicKey = null;
        if (certItem.getCert() != null) {
            if (!alipayPublicCertMap.containsKey(certItem.getCert())) {
                //如果返回的支付宝公钥证书序列号与本地支付宝公钥证书序列号不匹配,通过返回的支付宝公钥证书序列号去网关拉取新的支付宝公钥证书
                AlipayOpenAppAlipaycertDownloadRequest alipayRequest = new AlipayOpenAppAlipaycertDownloadRequest();
                alipayRequest.setBizContent("{" +
                        "\"alipay_cert_sn\":\"" + certItem.getCert() + "\"" +
                        "  }");
 
                Map<String, Object> rt = doPost(alipayRequest, null, null, this.appCertSN, null);
                // 解析实际串
                String respContent = rt.get("rsp").toString();
                AlipayParser<AlipayOpenAppAlipaycertDownloadResponse> parserCert = null;
                parserCert = new ObjectJsonParser<AlipayOpenAppAlipaycertDownloadResponse>(alipayRequest.getResponseClass());
                AlipayOpenAppAlipaycertDownloadResponse alipayResponse = parserCert.parse(respContent);
                if (!alipayResponse.isSuccess()) {
                    throw new AlipayApiException("支付宝公钥证书校验失败,请确认是否为支付宝签发的有效公钥证书");
                }
                String alipayCertContent = alipayResponse.getAlipayCertContent();
 
                InputStream inputStream = null;
                try {
                    byte[] alipayCert = Base64.decodeBase64String(alipayCertContent);
                    String alipayPublicCertStr = new String(alipayCert);
                    if (!verifyCert(alipayPublicCertStr)) {
                        throw new AlipayApiException("支付宝公钥证书校验失败,请确认是否为支付宝签发的有效公钥证书");
                    }
                    inputStream = new ByteArrayInputStream(alipayCert);
                    CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");
                    X509Certificate alipayPublicCertNew = (X509Certificate) cf.generateCertificate(inputStream);
                    //获取新证书和公钥添加到map中
                    String alipayCertSNNew = getCertSN(alipayPublicCertNew);
                    this.alipayPublicCertMap.put(alipayCertSNNew, alipayPublicCertNew);
                    PublicKey publicKey = alipayPublicCertNew.getPublicKey();
                    String alipayPublicKeyNew = Base64.encodeBase64String(publicKey.getEncoded());
                    this.alipayPublicKeyMap.put(alipayCertSNNew, alipayPublicKeyNew);
 
                } catch (NoSuchProviderException e) {
                    throw new AlipayApiException(e);
                } catch (CertificateException e) {
                    throw new AlipayApiException(e);
                } finally {
                    try {
                        if (inputStream != null) {
                            inputStream.close();
                        }
                    } catch (IOException e) {
                        throw new AlipayApiException(e);
                    }
                }
            } else if (!alipayPublicKeyMap.containsKey(certItem.getCert())) {
                PublicKey publicKey = alipayPublicCertMap.get(certItem.getCert()).getPublicKey();
                this.alipayPublicKeyMap.put(certItem.getCert(), Base64.encodeBase64String(publicKey.getEncoded()));
            }
 
            // 针对成功结果且有支付宝公钥的进行验签
            if (alipayPublicCertMap.containsKey(certItem.getCert())) {
                alipayPublicKey = this.alipayPublicKeyMap.get(certItem.getCert());
                if (responseIsSuccess
                        || (!responseIsSuccess && !StringUtils.isEmpty(certItem.getSign()))) {
                    signChecker = new DefaultSignChecker(alipayPublicKey);
                    boolean rsaCheckContent = signChecker.checkCert(certItem.getSignSourceDate(),
                            certItem.getSign(), this.signType, this.charset, alipayPublicKey);
                    if (!rsaCheckContent) {
 
                        // 针对JSON \/问题,替换/后再尝试做一次验证
                        if (!StringUtils.isEmpty(certItem.getSignSourceDate())
                                && certItem.getSignSourceDate().contains("\\/")) {
                            String srouceData = certItem.getSignSourceDate().replace("\\/", "/");
 
                            boolean jsonCheck = getSignChecker().check(srouceData, certItem.getSign(),
                                    this.signType, this.charset);
                            if (!jsonCheck) {
                                throw new AlipayApiException(
                                        "cert check fail: check Cert and Data Fail!JSON also!");
                            }
                        } else {
 
                            throw new AlipayApiException("cert check fail: check Cert and Data Fail!");
                        }
                    }
                }
            } else {
 
                throw new AlipayApiException("cert check fail: check Cert and Data Fail! CertSN non-existent");
            }
        }
 
    }
 
    public <T extends AlipayResponse> T execute(AlipayRequest<T> request) throws AlipayApiException {
        return execute(request, null);
    }
 
    public <T extends AlipayResponse> T execute(AlipayRequest<T> request,
                                                String accessToken) throws AlipayApiException {
 
        return execute(request, accessToken, null);
    }
 
    public <T extends AlipayResponse> T execute(AlipayRequest<T> request, String accessToken,
                                                String appAuthToken) throws AlipayApiException {
        return execute(request, accessToken, appAuthToken, null);
    }
 
    public <T extends AlipayResponse> T execute(AlipayRequest<T> request, String accessToken,
                                                String appAuthToken, String targetAppId) throws AlipayApiException {
 
        //如果根证书序列号非空,抛异常提示开发者使用certificateExecute
        if (!StringUtils.isEmpty(this.alipayRootCertSN)) {
            throw new AlipayApiException("检测到证书相关参数已初始化,证书模式下请改为调用certificateExecute");
        }
 
        AlipayParser<T> parser = null;
        if (AlipayConstants.FORMAT_XML.equals(this.format)) {
            parser = new ObjectXmlParser<T>(request.getResponseClass());
        } else {
            parser = new ObjectJsonParser<T>(request.getResponseClass());
        }
 
        return _execute(request, parser, accessToken, appAuthToken, targetAppId);
    }
 
    public BatchAlipayResponse execute(BatchAlipayRequest request) throws AlipayApiException {
 
        long beginTime = System.currentTimeMillis();
 
        //发送请求
        Map<String, Object> rt = doPost(request);
        if (rt == null) {
            return null;
        }
        Map<String, Long> costTimeMap = new HashMap<String, Long>();
        if (rt.containsKey("prepareTime")) {
            costTimeMap.put("prepareCostTime", (Long) (rt.get("prepareTime")) - beginTime);
            if (rt.containsKey("requestTime")) {
                costTimeMap.put("requestCostTime", (Long) (rt.get("requestTime")) - (Long) (rt.get("prepareTime")));
            }
        }
 
        AlipayParser<BatchAlipayResponse> parser = null;
        if (AlipayConstants.FORMAT_XML.equals(this.format)) {
            parser = new ObjectXmlParser<BatchAlipayResponse>(request.getResponseClass());
        } else {
            parser = new ObjectJsonParser<BatchAlipayResponse>(request.getResponseClass());
        }
 
        BatchAlipayResponse batchAlipayResponse = null;
        try {
 
            // 若需要解密则先解密
            ResponseEncryptItem responseItem = decryptResponse(request, rt, parser);
 
            // 解析实际串
            batchAlipayResponse = parser.parse(responseItem.getRealContent());
            batchAlipayResponse.setBody(responseItem.getRealContent());
 
            // 验签是对请求返回原始串
            checkResponseSign(request, parser, responseItem.getRespContent(), batchAlipayResponse.isSuccess());
 
            if (costTimeMap.containsKey("requestCostTime")) {
                costTimeMap.put("postCostTime", System.currentTimeMillis() - (Long) (rt.get("requestTime")));
            }
 
            // 构造响应解释器
            List<AlipayParser<?>> parserList = new ArrayList<AlipayParser<?>>();
            List<AlipayRequestWrapper> requestList = request.getRequestList();
            if (AlipayConstants.FORMAT_XML.equals(this.format)) {
                for (AlipayRequestWrapper aRequestList : requestList) {
                    parserList.add(new ObjectXmlParser(aRequestList.getAlipayRequest().getResponseClass()));
                }
            } else {
                for (AlipayRequestWrapper aRequestList : requestList) {
                    parserList.add(new ObjectJsonParser(aRequestList.getAlipayRequest().getResponseClass()));
                }
            }
 
            //批量调用失败,直接返回
            if (!batchAlipayResponse.isSuccess()) {
                return batchAlipayResponse;
            }
            String[] responseArray = batchAlipayResponse.getResponseBody().split(BATCH_API_DEFAULT_SPLIT);
            //循环解析业务API响应
            for (int index = 0; index < responseArray.length; index++) {
                AlipayResponse alipayResponse = parserList.get(index).parse(responseArray[index]);
                alipayResponse.setBody(responseArray[index]);
                batchAlipayResponse.addResponse(alipayResponse);
            }
            AlipayLogger.logBizDebug((String) rt.get("rsp"));
            return batchAlipayResponse;
        } catch (RuntimeException e) {
 
            AlipayLogger.logBizError((String) rt.get("rsp"), costTimeMap);
            throw e;
        } catch (AlipayApiException e) {
 
            AlipayLogger.logBizError((String) rt.get("rsp"), costTimeMap);
            throw new AlipayApiException(e);
        }
    }
 
    /**
     * @param request
     * @return
     * @throws AlipayApiException
     */
    private Map<String, Object> doPost(BatchAlipayRequest request) throws AlipayApiException {
 
        Map<String, Object> result = new HashMap<String, Object>();
        RequestParametersHolder requestHolder = getRequestHolderWithSign(request);
 
        String url = getRequestUrl(requestHolder);
 
        // 打印完整请求报文
        if (AlipayLogger.isBizDebugEnabled()) {
            AlipayLogger.logBizDebug(getRedirectUrl(requestHolder));
        }
        result.put("prepareTime", System.currentTimeMillis());
 
        String rsp = null;
        try {
            rsp = WebUtils.doPost(url, requestHolder.getApplicationParams(), charset,
                    connectTimeout, readTimeout, proxyHost, proxyPort);
        } catch (IOException e) {
            throw new AlipayApiException(e);
        }
        result.put("requestTime", System.currentTimeMillis());
        result.put("rsp", rsp);
        result.put("textParams", requestHolder.getApplicationParams());
        result.put("protocalMustParams", requestHolder.getProtocalMustParams());
        result.put("protocalOptParams", requestHolder.getProtocalOptParams());
        result.put("url", url);
        return result;
    }
 
    /**
     * 组装批量请求接口参数,处理加密、签名逻辑
     *
     * @param request
     * @return
     * @throws AlipayApiException
     */
    private <T extends AlipayResponse> RequestParametersHolder getRequestHolderWithSign(BatchAlipayRequest request)
            throws AlipayApiException {
 
        List<AlipayRequestWrapper> requestList = request.getRequestList();
        //校验接口列表非空
        if (requestList == null || requestList.isEmpty()) {
            throw new AlipayApiException("40", "client-error:api request list is empty");
        }
 
        RequestParametersHolder requestHolder = new RequestParametersHolder();
 
        //添加协议必须参数
        AlipayHashMap protocalMustParams = new AlipayHashMap();
        protocalMustParams.put(AlipayConstants.METHOD, request.getApiMethodName());
        protocalMustParams.put(AlipayConstants.APP_ID, this.appId);
        protocalMustParams.put(AlipayConstants.SIGN_TYPE, this.signType);
        protocalMustParams.put(AlipayConstants.CHARSET, charset);
        protocalMustParams.put(AlipayConstants.VERSION, request.getApiVersion());
 
        if (request.isNeedEncrypt()) {
            protocalMustParams.put(AlipayConstants.ENCRYPT_TYPE, this.encryptType);
        }
 
        //添加协议可选参数
        AlipayHashMap protocalOptParams = new AlipayHashMap();
        protocalOptParams.put(AlipayConstants.FORMAT, format);
        protocalOptParams.put(AlipayConstants.ALIPAY_SDK, AlipayConstants.SDK_VERSION);
        requestHolder.setProtocalOptParams(protocalOptParams);
 
        Long timestamp = System.currentTimeMillis();
        DateFormat df = new SimpleDateFormat(AlipayConstants.DATE_TIME_FORMAT);
        df.setTimeZone(TimeZone.getTimeZone(AlipayConstants.DATE_TIMEZONE));
        protocalMustParams.put(AlipayConstants.TIMESTAMP, df.format(new Date(timestamp)));
        requestHolder.setProtocalMustParams(protocalMustParams);
 
        //设置业务参数
        AlipayHashMap appParams = new AlipayHashMap();
 
        //构造请求主题
        StringBuilder requestBody = new StringBuilder();
        // 组装每个API的请求参数
        for (int index = 0; index < requestList.size(); index++) {
            AlipayRequestWrapper alipayRequestWrapper = requestList.get(index);
            AlipayRequest alipayRequest = alipayRequestWrapper.getAlipayRequest();
            Map<String, Object> apiParams = alipayRequest.getTextParams();
            apiParams.put(AlipayConstants.METHOD, alipayRequest.getApiMethodName());
            apiParams.put(AlipayConstants.APP_AUTH_TOKEN, alipayRequestWrapper.getAppAuthToken());
            apiParams.put(AlipayConstants.ACCESS_TOKEN, alipayRequestWrapper.getAccessToken());
            apiParams.put(AlipayConstants.TARGET_APP_ID, alipayRequestWrapper.getTargetAppId());
            apiParams.put(AlipayConstants.PROD_CODE, alipayRequest.getProdCode());
            apiParams.put(AlipayConstants.NOTIFY_URL, alipayRequest.getNotifyUrl());
            apiParams.put(AlipayConstants.RETURN_URL, alipayRequest.getReturnUrl());
            apiParams.put(AlipayConstants.TERMINAL_INFO, alipayRequest.getTerminalInfo());
            apiParams.put(AlipayConstants.TERMINAL_TYPE, alipayRequest.getTerminalType());
            apiParams.put(AlipayConstants.BATCH_REQUEST_ID, String.valueOf(index));
 
            // 仅当API包含biz_content参数且值为空时,序列化bizModel填充bizContent
            try {
                if (alipayRequest.getClass().getMethod("getBizContent") != null
                        && StringUtils.isEmpty(appParams.get(AlipayConstants.BIZ_CONTENT_KEY))
                        && alipayRequest.getBizModel() != null) {
                    apiParams.put(AlipayConstants.BIZ_CONTENT_KEY,
                            new JSONWriter().write(alipayRequest.getBizModel(), true));
                }
            } catch (NoSuchMethodException e) {
                // 找不到getBizContent则什么都不做
            } catch (SecurityException e) {
                AlipayLogger.logBizError(e);
            }
            requestBody.append(new JSONWriter().write(apiParams, false));
            if (index != requestList.size() - 1) {
                requestBody.append(BATCH_API_DEFAULT_SPLIT);
            }
        }
        appParams.put(AlipayConstants.BIZ_CONTENT_KEY, requestBody.toString());
 
        // 只有新接口和设置密钥才能支持加密
        if (request.isNeedEncrypt()) {
 
            if (StringUtils.isEmpty(appParams.get(AlipayConstants.BIZ_CONTENT_KEY))) {
 
                throw new AlipayApiException("当前API不支持加密请求");
            }
 
            // 需要加密必须设置密钥和加密算法
            if (StringUtils.isEmpty(this.encryptType) || getEncryptor() == null) {
 
                throw new AlipayApiException("API请求要求加密,则必须设置密钥类型和加密器");
            }
 
            String encryptContent = getEncryptor().encrypt(
                    appParams.get(AlipayConstants.BIZ_CONTENT_KEY), this.encryptType, this.charset);
 
            appParams.put(AlipayConstants.BIZ_CONTENT_KEY, encryptContent);
        }
 
        requestHolder.setApplicationParams(appParams);
 
        if (!StringUtils.isEmpty(this.signType)) {
 
            String signContent = AlipaySignature.getSignatureContent(requestHolder);
            protocalMustParams.put(AlipayConstants.SIGN,
                    getSigner().sign(signContent, this.signType, charset));
 
        } else {
            protocalMustParams.put(AlipayConstants.SIGN, "");
        }
        return requestHolder;
    }
 
    public <T extends AlipayResponse> T pageExecute(AlipayRequest<T> request) throws AlipayApiException {
        return pageExecute(request, "POST");
    }
 
    public <T extends AlipayResponse> T pageExecute(AlipayRequest<T> request,
                                                    String httpMethod) throws AlipayApiException {
        RequestParametersHolder requestHolder = getRequestHolderWithSign(request, null, null,
                this.appCertSN, null);
        // 打印完整请求报文
        if (AlipayLogger.isBizDebugEnabled()) {
            AlipayLogger.logBizDebug(getRedirectUrl(requestHolder));
        }
        T rsp = null;
        try {
            Class<T> clazz = request.getResponseClass();
            rsp = clazz.newInstance();
        } catch (InstantiationException e) {
            AlipayLogger.logBizError(e);
        } catch (IllegalAccessException e) {
            AlipayLogger.logBizError(e);
        }
        if ("GET".equalsIgnoreCase(httpMethod)) {
            rsp.setBody(getRedirectUrl(requestHolder));
        } else {
            String baseUrl = getRequestUrl(requestHolder);
            rsp.setBody(WebUtils.buildForm(baseUrl, requestHolder.getApplicationParams()));
        }
        return rsp;
    }
 
    public <T extends AlipayResponse> T sdkExecute(AlipayRequest<T> request) throws AlipayApiException {
        RequestParametersHolder requestHolder = getRequestHolderWithSign(request, null, null,
                this.appCertSN, null);
        // 打印完整请求报文
        if (AlipayLogger.isBizDebugEnabled()) {
            AlipayLogger.logBizDebug(getSdkParams(requestHolder));
        }
        T rsp = null;
        try {
            Class<T> clazz = request.getResponseClass();
            rsp = clazz.newInstance();
        } catch (InstantiationException e) {
            AlipayLogger.logBizError(e);
        } catch (IllegalAccessException e) {
            AlipayLogger.logBizError(e);
        }
        rsp.setBody(getSdkParams(requestHolder));
        return rsp;
    }
 
    public <TR extends AlipayResponse, T extends AlipayRequest<TR>> TR parseAppSyncResult(Map<String, String> result,
                                                                                          Class<T> requsetClazz) throws AlipayApiException {
        TR tRsp = null;
        String rsp = result.get("result");
 
        try {
            T request = requsetClazz.newInstance();
            Class<TR> responseClazz = request.getResponseClass();
 
            //result为空直接返回SYSTEM_ERROR
            if (StringUtils.isEmpty(rsp)) {
                tRsp = responseClazz.newInstance();
                tRsp.setCode("20000");
                tRsp.setSubCode("ACQ.SYSTEM_ERROR");
                tRsp.setSubMsg(result.get("memo"));
            } else {
                AlipayParser<TR> parser = null;
                if (AlipayConstants.FORMAT_XML.equals(this.format)) {
                    parser = new ObjectXmlParser<TR>(responseClazz);
                } else {
                    parser = new ObjectJsonParser<TR>(responseClazz);
                }
 
                // 解析实际串
                tRsp = parser.parse(rsp);
                tRsp.setBody(rsp);
 
                // 验签是对请求返回原始串
                checkResponseSign(request, parser, rsp, tRsp.isSuccess());
                if (!tRsp.isSuccess()) {
                    AlipayLogger.logBizError(rsp);
                }
            }
        } catch (RuntimeException e) {
            AlipayLogger.logBizError(rsp);
            throw e;
        } catch (AlipayApiException e) {
            AlipayLogger.logBizError(rsp);
            throw new AlipayApiException(e);
        } catch (InstantiationException e) {
            AlipayLogger.logBizError(rsp);
            throw new AlipayApiException(e);
        } catch (IllegalAccessException e) {
            AlipayLogger.logBizError(rsp);
            throw new AlipayApiException(e);
        }
        return tRsp;
    }
 
    /**
     * 组装接口参数,处理加密、签名逻辑
     *
     * @param request
     * @param accessToken
     * @param appAuthToken
     * @param appCertSN    应用证书序列号
     * @return
     * @throws AlipayApiException
     */
    private <T extends AlipayResponse> RequestParametersHolder getRequestHolderWithSign(AlipayRequest<?> request,
                                                                                        String accessToken, String appAuthToken,
                                                                                        String appCertSN, String targetAppId)
            throws AlipayApiException {
        RequestParametersHolder requestHolder = new RequestParametersHolder();
        AlipayHashMap appParams = new AlipayHashMap(request.getTextParams());
 
        // 仅当API包含biz_content参数且值为空时,序列化bizModel填充bizContent
        try {
            if (request.getClass().getMethod("getBizContent") != null
                    && StringUtils.isEmpty(appParams.get(AlipayConstants.BIZ_CONTENT_KEY))
                    && request.getBizModel() != null) {
                appParams.put(AlipayConstants.BIZ_CONTENT_KEY,
                        new JSONWriter().write(request.getBizModel(), true));
            }
        } catch (NoSuchMethodException e) {
            // 找不到getBizContent则什么都不做
        } catch (SecurityException e) {
            AlipayLogger.logBizError(e);
        }
 
        // 只有新接口和设置密钥才能支持加密
        if (request.isNeedEncrypt()) {
 
            if (StringUtils.isEmpty(appParams.get(AlipayConstants.BIZ_CONTENT_KEY))) {
 
                throw new AlipayApiException("当前API不支持加密请求");
            }
 
            // 需要加密必须设置密钥和加密算法
            if (StringUtils.isEmpty(this.encryptType) || getEncryptor() == null) {
 
                throw new AlipayApiException("API请求要求加密,则必须设置密钥类型和加密器");
            }
 
            String encryptContent = getEncryptor().encrypt(
                    appParams.get(AlipayConstants.BIZ_CONTENT_KEY), this.encryptType, this.charset);
 
            appParams.put(AlipayConstants.BIZ_CONTENT_KEY, encryptContent);
        }
 
        if (!StringUtils.isEmpty(appAuthToken)) {
            appParams.put(AlipayConstants.APP_AUTH_TOKEN, appAuthToken);
        }
 
        requestHolder.setApplicationParams(appParams);
 
        if (StringUtils.isEmpty(charset)) {
            charset = AlipayConstants.CHARSET_UTF8;
        }
 
        AlipayHashMap protocalMustParams = new AlipayHashMap();
        protocalMustParams.put(AlipayConstants.METHOD, request.getApiMethodName());
        protocalMustParams.put(AlipayConstants.VERSION, request.getApiVersion());
        protocalMustParams.put(AlipayConstants.APP_ID, this.appId);
        protocalMustParams.put(AlipayConstants.SIGN_TYPE, this.signType);
        protocalMustParams.put(AlipayConstants.TERMINAL_TYPE, request.getTerminalType());
        protocalMustParams.put(AlipayConstants.TERMINAL_INFO, request.getTerminalInfo());
        protocalMustParams.put(AlipayConstants.NOTIFY_URL, request.getNotifyUrl());
        protocalMustParams.put(AlipayConstants.RETURN_URL, request.getReturnUrl());
        protocalMustParams.put(AlipayConstants.CHARSET, charset);
 
        if (!StringUtils.isEmpty(targetAppId)) {
            protocalMustParams.put(AlipayConstants.TARGET_APP_ID, targetAppId);
        }
 
        if (request.isNeedEncrypt()) {
            protocalMustParams.put(AlipayConstants.ENCRYPT_TYPE, this.encryptType);
        }
        //如果应用证书序列号非空,添加应用证书序列号
        if (!StringUtils.isEmpty(appCertSN)) {
            protocalMustParams.put(AlipayConstants.APP_CERT_SN, appCertSN);
        }
        //如果根证书序列号非空,添加根证书序列号
        if (!StringUtils.isEmpty(this.alipayRootCertSN)) {
            protocalMustParams.put(AlipayConstants.ALIPAY_ROOT_CERT_SN, this.alipayRootCertSN);
        }
        //如果SM2根证书序列号非空,添加SM2根证书序列号
        if (!StringUtils.isEmpty(this.alipayRootSm2CertSN)) {
            protocalMustParams.put(AlipayConstants.ALIPAY_ROOT_CERT_SN, this.alipayRootSm2CertSN);
        }
 
        Long timestamp = System.currentTimeMillis();
        DateFormat df = new SimpleDateFormat(AlipayConstants.DATE_TIME_FORMAT);
        df.setTimeZone(TimeZone.getTimeZone(AlipayConstants.DATE_TIMEZONE));
        protocalMustParams.put(AlipayConstants.TIMESTAMP, df.format(new Date(timestamp)));
        requestHolder.setProtocalMustParams(protocalMustParams);
 
        AlipayHashMap protocalOptParams = new AlipayHashMap();
        protocalOptParams.put(AlipayConstants.FORMAT, format);
        protocalOptParams.put(AlipayConstants.ACCESS_TOKEN, accessToken);
        protocalOptParams.put(AlipayConstants.ALIPAY_SDK, AlipayConstants.SDK_VERSION);
        protocalOptParams.put(AlipayConstants.PROD_CODE, request.getProdCode());
        requestHolder.setProtocalOptParams(protocalOptParams);
 
        if (!StringUtils.isEmpty(this.signType)) {
 
            String signContent = AlipaySignature.getSignatureContent(requestHolder);
            protocalMustParams.put(AlipayConstants.SIGN,
                    getSigner().sign(signContent, this.signType, charset));
 
        } else {
            protocalMustParams.put(AlipayConstants.SIGN, "");
        }
        return requestHolder;
    }
 
    /**
     * 获取POST请求的base url
     *
     * @param requestHolder
     * @return
     * @throws AlipayApiException
     */
    private String getRequestUrl(RequestParametersHolder requestHolder) throws AlipayApiException {
        StringBuilder urlSb = new StringBuilder(serverUrl);
        try {
            String sysMustQuery = WebUtils.buildQuery(loadTest ?
                    LoadTestUtil.getParamsWithLoadTestFlag(requestHolder.getProtocalMustParams())
                    : requestHolder.getProtocalMustParams(), charset);
            String sysOptQuery = WebUtils.buildQuery(requestHolder.getProtocalOptParams(), charset);
 
            urlSb.append("?");
            urlSb.append(sysMustQuery);
            if (sysOptQuery != null && sysOptQuery.length() > 0) {
                urlSb.append("&");
                urlSb.append(sysOptQuery);
            }
        } catch (IOException e) {
            throw new AlipayApiException(e);
        }
 
        return urlSb.toString();
    }
 
    /**
     * GET模式下获取跳转链接
     *
     * @param requestHolder
     * @return
     * @throws AlipayApiException
     */
    private String getRedirectUrl(RequestParametersHolder requestHolder) throws AlipayApiException {
        StringBuilder urlSb = new StringBuilder(serverUrl);
        try {
            Map<String, String> sortedMap = AlipaySignature.getSortedMap(requestHolder);
            String sortedQuery = WebUtils.buildQuery(loadTest ?
                    LoadTestUtil.getParamsWithLoadTestFlag(sortedMap) : sortedMap, charset);
            urlSb.append("?");
            urlSb.append(sortedQuery);
        } catch (IOException e) {
            throw new AlipayApiException(e);
        }
 
        return urlSb.toString();
    }
 
    /**
     * 拼装sdk调用时所传参数
     *
     * @param requestHolder
     * @return
     * @throws AlipayApiException
     */
    private String getSdkParams(RequestParametersHolder requestHolder) throws AlipayApiException {
        StringBuilder urlSb = new StringBuilder();
        try {
            Map<String, String> sortedMap = AlipaySignature.getSortedMap(requestHolder);
            String sortedQuery = WebUtils.buildQuery(loadTest ?
                    LoadTestUtil.getParamsWithLoadTestFlag(sortedMap) : sortedMap, charset);
            urlSb.append(sortedQuery);
        } catch (IOException e) {
            throw new AlipayApiException(e);
        }
 
        return urlSb.toString();
    }
 
    private <T extends AlipayResponse> T _execute(AlipayRequest<T> request, AlipayParser<T> parser,
                                                  String authToken, String appAuthToken,
                                                  String targetAppId) throws AlipayApiException {
 
        long beginTime = System.currentTimeMillis();
        //适配新增证书序列号的请求
        Map<String, Object> rt = doPost(request, authToken, appAuthToken, null, targetAppId);
        if (rt == null) {
            return null;
        }
        Map<String, Long> costTimeMap = new HashMap<String, Long>();
        if (rt.containsKey("prepareTime")) {
            costTimeMap.put("prepareCostTime", (Long) (rt.get("prepareTime")) - beginTime);
            if (rt.containsKey("requestTime")) {
                costTimeMap.put("requestCostTime", (Long) (rt.get("requestTime")) - (Long) (rt.get("prepareTime")));
            }
        }
 
        T tRsp = null;
 
        try {
 
            // 若需要解密则先解密
            ResponseEncryptItem responseItem = decryptResponse(request, rt, parser);
 
            // 解析实际串
            tRsp = parser.parse(responseItem.getRealContent());
            tRsp.setBody(responseItem.getRealContent());
 
            // 验签是对请求返回原始串
            checkResponseSign(request, parser, responseItem.getRespContent(), tRsp.isSuccess());
 
            if (costTimeMap.containsKey("requestCostTime")) {
                costTimeMap.put("postCostTime", System.currentTimeMillis() - (Long) (rt.get("requestTime")));
            }
        } catch (RuntimeException e) {
 
            AlipayLogger.logBizError((String) rt.get("rsp"), costTimeMap);
            throw e;
        } catch (AlipayApiException e) {
 
            AlipayLogger.logBizError((String) rt.get("rsp"), costTimeMap);
            throw new AlipayApiException(e);
        }
 
        tRsp.setParams((AlipayHashMap) rt.get("textParams"));
        if (!tRsp.isSuccess()) {
            AlipayLogger.logErrorScene(rt, tRsp, "", costTimeMap);
        } else {
            AlipayLogger.logBizSummary(rt, tRsp, costTimeMap);
        }
        return tRsp;
    }
 
    /**
     * @param request
     * @param accessToken
     * @param appAuthToken
     * @param appCertSN    应用证书序列号
     * @return
     * @throws AlipayApiException
     */
    private <T extends AlipayResponse> Map<String, Object> doPost(AlipayRequest<T> request,
                                                                  String accessToken, String appAuthToken,
                                                                  String appCertSN, String targetAppId) throws AlipayApiException {
        Map<String, Object> result = new HashMap<String, Object>();
        RequestParametersHolder requestHolder = getRequestHolderWithSign(request, accessToken,
                appAuthToken, appCertSN, targetAppId);
 
        String url = getRequestUrl(requestHolder);
 
        // 打印完整请求报文
        if (AlipayLogger.isBizDebugEnabled()) {
            AlipayLogger.logBizDebug(getRedirectUrl(requestHolder));
        }
        result.put("prepareTime", System.currentTimeMillis());
 
        String rsp = null;
        try {
            if (request instanceof AlipayUploadRequest) {
                AlipayUploadRequest<T> uRequest = (AlipayUploadRequest<T>) request;
                Map<String, FileItem> fileParams = AlipayUtils.cleanupMap(uRequest.getFileParams());
                rsp = WebUtils.doPost(url, requestHolder.getApplicationParams(), fileParams,
                        charset, connectTimeout, readTimeout, proxyHost, proxyPort);
            } else {
                rsp = WebUtils.doPost(url, requestHolder.getApplicationParams(), charset,
                        connectTimeout, readTimeout, proxyHost, proxyPort);
            }
        } catch (SSLException e) {
            if (e.getMessage().contains("the trustAnchors parameter must be non-empty")
                    || e.getMessage().contains("PKIX path building failed")) {
                throw new AlipayApiException("SDK已默认开启SSL服务端证书校验,"
                        + "请确认本地JRE默认自带的CA证书库是否正确(JRE主目录下的lib/security/cacerts是否存在。" + e.getMessage(), e);
            }
            throw new AlipayApiException(e);
        } catch (IOException e) {
            throw new AlipayApiException(e);
        }
        result.put("requestTime", System.currentTimeMillis());
        result.put("rsp", rsp);
        result.put("textParams", requestHolder.getApplicationParams());
        result.put("protocalMustParams", requestHolder.getProtocalMustParams());
        result.put("protocalOptParams", requestHolder.getProtocalOptParams());
        result.put("url", url);
        return result;
    }
 
    /**
     * 检查响应签名
     *
     * @param request
     * @param parser
     * @param responseBody
     * @param responseIsSucess
     * @throws AlipayApiException
     */
    private <T extends AlipayResponse> void checkResponseSign(AlipayRequest<T> request,
                                                              AlipayParser<T> parser,
                                                              String responseBody,
                                                              boolean responseIsSucess) throws AlipayApiException {
        // 针对成功结果且有支付宝公钥的进行验签
        if (getSignChecker() != null) {
 
            SignItem signItem = parser.getSignItem(request, responseBody);
 
            if (signItem == null) {
 
                throw new AlipayApiException("sign check fail: Body is Empty!");
            }
 
            if (responseIsSucess
                    || (!responseIsSucess && !StringUtils.isEmpty(signItem.getSign()))) {
 
                boolean rsaCheckContent = getSignChecker().check(signItem.getSignSourceDate(),
                        signItem.getSign(), this.signType, this.charset);
 
                if (!rsaCheckContent) {
 
                    // 针对JSON \/问题,替换/后再尝试做一次验证
                    if (!StringUtils.isEmpty(signItem.getSignSourceDate())
                            && signItem.getSignSourceDate().contains("\\/")) {
 
                        String srouceData = signItem.getSignSourceDate().replace("\\/", "/");
 
                        boolean jsonCheck = getSignChecker().check(srouceData, signItem.getSign(),
                                this.signType, this.charset);
 
                        if (!jsonCheck) {
                            throw new AlipayApiException(
                                    "sign check fail: check Sign and Data Fail!JSON also!");
                        }
                    } else {
 
                        throw new AlipayApiException("sign check fail: check Sign and Data Fail!");
                    }
                }
            }
 
        }
    }
 
    /**
     * 解密响应
     *
     * @param request
     * @param rt
     * @param parser
     * @return
     * @throws AlipayApiException
     */
    private <T extends AlipayResponse> ResponseEncryptItem decryptResponse(AlipayRequest<T> request,
                                                                           Map<String, Object> rt,
                                                                           AlipayParser<T> parser) throws AlipayApiException {
 
        String responseBody = (String) rt.get("rsp");
 
        String realBody = null;
 
        // 解密
        if (request.isNeedEncrypt()) {
 
            // 解密原始串
            realBody = parser.decryptSourceData(request, responseBody, this.format,
                    getDecryptor(), this.encryptType, this.charset);
        } else {
 
            // 解析原内容串
            realBody = (String) rt.get("rsp");
        }
 
        return new ResponseEncryptItem(responseBody, realBody);
 
    }
 
    void setServerUrl(String serverUrl) {
        this.serverUrl = serverUrl;
    }
 
    void setAppId(String appId) {
        this.appId = appId;
    }
 
    void setProdCode(String prodCode) {
        this.prodCode = prodCode;
    }
 
    void setFormat(String format) {
        this.format = format;
    }
 
    void setSignType(String signType) {
        this.signType = signType;
    }
 
    void setEncryptType(String encryptType) {
        this.encryptType = encryptType;
    }
 
    void setCharset(String charset) {
        this.charset = charset;
    }
 
    public void setConnectTimeout(int connectTimeout) {
        this.connectTimeout = connectTimeout;
    }
 
    public void setReadTimeout(int readTimeout) {
        this.readTimeout = readTimeout;
    }
 
    void setProxyHost(String proxyHost) {
        this.proxyHost = proxyHost;
    }
 
    void setProxyPort(int proxyPort) {
        this.proxyPort = proxyPort;
    }
 
    void setCert(X509Certificate cert) {
        this.cert = cert;
    }
 
    void setAlipayPublicCertMap(ConcurrentHashMap<String, X509Certificate> alipayPublicCertMap) {
        this.alipayPublicCertMap = alipayPublicCertMap;
    }
 
    public abstract Signer getSigner();
 
    public abstract SignChecker getSignChecker();
 
    public abstract Encryptor getEncryptor();
 
    public abstract Decryptor getDecryptor();
}