zhengyuxuan
2025-03-28 182c7edd7c70eddbf33e2358f1f1aba96eb58cb3
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
using Alipay.EasySDK.Factory;
using Alipay.EasySDK.Kernel;
using Alipay.EasySDK.Payment.Common.Models;
using Alipay.EasySDK.Payment.FaceToFace.Models;
using LifePayment.Domain.Shared;
using Microsoft.Extensions.Options;
using Nest;
using Spire.Pdf;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using Tea;
 
namespace LifePayment.Domain
{
    public class AliPayApi : IAliPayApi
    {
        private readonly Config _options;
 
        public const string SDKVERSION = "alipay-easysdk-net-2.0.0";
        protected Alipay.EasySDK.Kernel.Client _kernel;
        public AliPayApi(
               IOptionsMonitor<Config> optionsMonitor, string optionsName = null)
        {
            Alipay.EasySDK.Kernel.Context context = new Alipay.EasySDK.Kernel.Context(optionsName.IsNullOrEmpty() ? optionsMonitor.CurrentValue : optionsMonitor.Get(optionsName), SDKVERSION);
            _options = optionsMonitor.CurrentValue;
            this._kernel = new Client(context);
        }
 
        public async Task<AlipayTradePrecreateResponse> GetAliPayQRCode(GetPayQrCodeInput input)
        {
            AlipayTradePrecreateResponse response = Factory.Payment.FaceToFace()
                                                                   .AsyncNotify($"{_options.NotifyUrl}{LifePaymentConstant.AliRechargeNotifySectionUrl}")
                                                                   .PreCreate(input.Subject,
                                                                              input.OutTradeNo,
                                                                              input.TotalAmount.ToString());
            return response;
        }
 
        /// <summary>
        /// 查询支付宝支付订单信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<AlipayTradeQueryResponse> OrderInQuiry(OrderInQuiryInput input)
        {
            AlipayTradeQueryResponse response = Factory.Payment.Common().Query(input.OutTradeNo);
            return response;
        }
 
        /// <summary>
        /// 查询支付宝退款订单信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<AlipayTradeFastpayRefundQueryResponse> QueryAlipayTradeRefund(OrderInQuiryInput input)
        {
            AlipayTradeFastpayRefundQueryResponse response = await Factory.Payment.Common().QueryRefundAsync(input.OutTradeNo, input.OutTradeNo);
            return response;
        }
 
        public async Task<AlipayTradeRefundResponse> TradeRefund(AlipayTradeRefundRequest input)
        {
            AlipayTradeRefundResponse response = await TradeRefund(input.OutTradeNo,input.OutRefundNo, input.RefundAmount);
            return response;
        }
 
        private async Task<AlipayTradeRefundResponse> TradeRefund(string outTradeNo, string outRefundNo, string refundAmount)
        {
            Dictionary<string, object> runtime_ = new Dictionary<string, object>
        {
            {
                "ignoreSSL",
                _kernel.GetConfig("ignoreSSL")
            },
            {
                "httpProxy",
                _kernel.GetConfig("httpProxy")
            },
            { "connectTimeout", 15000 },
            { "readTimeout", 15000 },
            {
                "retry",
                new Dictionary<string, int?> { { "maxAttempts", 0 } }
            }
        };
            TeaRequest _lastRequest = null;
            Exception innerException = null;
            long _now = DateTime.Now.Millisecond;
            int _retryTimes = 0;
            while (TeaCore.AllowRetry((IDictionary)runtime_["retry"], _retryTimes, _now))
            {
                if (_retryTimes > 0)
                {
                    int backoffTime = TeaCore.GetBackoffTime((IDictionary)runtime_["backoff"], _retryTimes);
                    if (backoffTime > 0)
                    {
                        TeaCore.Sleep(backoffTime);
                    }
                }
 
                _retryTimes++;
                try
                {
                    TeaRequest teaRequest = new TeaRequest();
                    Dictionary<string, string> dictionary = new Dictionary<string, string>
                {
                    { "method", "alipay.trade.refund" },
                    {
                        "app_id",
                        _kernel.GetConfig("appId")
                    },
                    {
                        "timestamp",
                        _kernel.GetTimestamp()
                    },
                    { "format", "json" },
                    { "version", "1.0" },
                    {
                        "alipay_sdk",
                        _kernel.GetSdkVersion()
                    },
                    { "charset", "UTF-8" },
                    {
                        "sign_type",
                        _kernel.GetConfig("signType")
                    },
                    {
                        "app_cert_sn",
                        _kernel.GetMerchantCertSN()
                    },
                    {
                        "alipay_root_cert_sn",
                        _kernel.GetAlipayRootCertSN()
                    }
                };
                    Dictionary<string, object> bizParams = new Dictionary<string, object>
                {
                    { "out_trade_no", outTradeNo },
                    { "out_request_no", outRefundNo },
                    { "refund_amount", refundAmount }
                };
                    Dictionary<string, string> dictionary2 = new Dictionary<string, string>();
                    teaRequest.Protocol = _kernel.GetConfig("protocol");
                    teaRequest.Method = "POST";
                    teaRequest.Pathname = "/gateway.do";
                    teaRequest.Headers = new Dictionary<string, string>
                {
                    {
                        "host",
                        _kernel.GetConfig("gatewayHost")
                    },
                    { "content-type", "application/x-www-form-urlencoded;charset=utf-8" }
                };
                    teaRequest.Query = _kernel.SortMap(TeaConverter.merge<string>(new object[3]
                    {
                    new Dictionary<string, string> {
                    {
                        "sign",
                        _kernel.Sign(dictionary, bizParams, dictionary2, _kernel.GetConfig("merchantPrivateKey"))
                    } },
                    dictionary,
                    dictionary2
                    }));
                    teaRequest.Body = TeaCore.BytesReadable(_kernel.ToUrlEncodedRequestBody(bizParams));
                    _lastRequest = teaRequest;
                    TeaResponse response = await TeaCore.DoActionAsync(teaRequest, runtime_);
                    Dictionary<string, object> respMap = await _kernel.ReadAsJsonAsync(response, "alipay.trade.refund");
                    if (_kernel.IsCertMode())
                    {
                        if (_kernel.Verify(respMap, _kernel.ExtractAlipayPublicKey(_kernel.GetAlipayCertSN(respMap))))
                        {
                            return TeaModel.ToObject<AlipayTradeRefundResponse>(_kernel.ToRespModel(respMap));
                        }
                    }
                    else if (_kernel.Verify(respMap, _kernel.GetConfig("alipayPublicKey")))
                    {
                        return TeaModel.ToObject<AlipayTradeRefundResponse>(_kernel.ToRespModel(respMap));
                    }
 
                    throw new TeaException(new Dictionary<string, string> { { "message", "验签失败,请检查支付宝公钥设置是否正确。" } });
                }
                catch (Exception ex)
                {
                    if (TeaCore.IsRetryable(ex))
                    {
                        innerException = ex;
                        continue;
                    }
 
                    throw ex;
                }
            }
 
            throw new TeaUnretryableException(_lastRequest, innerException);
        }
 
    }
}