Exemple #1
0
        public async Task <T> ExecuteAsync <T>(HttpRequest request) where T : LianLianPayNotifyResponse
        {
            if (request.HasFormContentType)
            {
                var parameters = await GetParametersAsync(request);

                var query = HttpClientEx.BuildQuery(parameters);
                Logger.LogInformation(0, "Request:{query}", query);

                var parser = new LianLianPayDictionaryParser <T>();
                var rsp    = parser.Parse(parameters);
                CheckNotifySign(parameters);
                return(rsp);
            }
            else if (request.HasTextJsonContentType())
            {
                var body = await new StreamReader(request.Body).ReadToEndAsync();
                Logger.LogInformation(0, "Request:{body}", body);

                var parser = new LianLianPayJsonParser <T>();
                var rsp    = parser.Parse(body);
                CheckNotifySign(rsp.Parameters);
                return(rsp);
            }
            else
            {
                throw new Exception("sign check fail: check Sign and Data Fail!");
            }
        }
Exemple #2
0
        public Task <T> SdkExecuteAsync <T>(IAlipayRequest <T> request) where T : AlipayResponse
        {
            // 构造请求参数
            var requestParams = BuildRequestParams(request, null, null);

            // 字典排序
            var sortedParams    = new SortedDictionary <string, string>(requestParams);
            var sortedAlipayDic = new AlipayDictionary(sortedParams);

            // 参数签名
            var signContent = AlipaySignature.GetSignContent(sortedAlipayDic);
            var signResult  = AlipaySignature.RSASignContent(signContent, PrivateRSAParameters, Options.SignType);

            // 添加签名结果参数
            sortedAlipayDic.Add(SIGN, signResult);

            // 参数拼接
            var signedResult = HttpClientEx.BuildQuery(sortedAlipayDic);

            // 构造结果
            var rsp = Activator.CreateInstance <T>();

            rsp.Body = signedResult;
            return(Task.FromResult(rsp));
        }
Exemple #3
0
        public Task <T> PageExecuteAsync <T>(IJDPayRequest <T> request, string reqMethod) where T : JDPayResponse
        {
            // 字典排序
            var sortedTxtParams = new JDPayDictionary(request.GetParameters());
            var encyptParams    = BuildEncryptDic(request, sortedTxtParams);
            var rsp             = Activator.CreateInstance <T>();

            var url = request.GetRequestUrl();

            if (reqMethod == "GET")
            {
                //拼接get请求的url
                var tmpUrl = url;
                if (encyptParams != null && encyptParams.Count > 0)
                {
                    if (tmpUrl.Contains("?"))
                    {
                        tmpUrl = tmpUrl + "&" + HttpClientEx.BuildQuery(encyptParams);
                    }
                    else
                    {
                        tmpUrl = tmpUrl + "?" + HttpClientEx.BuildQuery(encyptParams);
                    }
                }
                rsp.Body = tmpUrl;
            }
            else
            {
                //输出post表单
                rsp.Body = BuildHtmlRequest(url, encyptParams);
            }

            return(Task.FromResult(rsp));
        }
Exemple #4
0
        public Task <T> PageExecuteAsync <T>(IUnionPayRequest <T> request, string reqMethod) where T : UnionPayResponse
        {
            var version = string.Empty;

            if (!string.IsNullOrEmpty(request.GetApiVersion()))
            {
                version = request.GetApiVersion();
            }
            else
            {
                version = Options.Version;
            }

            var txtParams = new UnionPayDictionary(request.GetParameters())
            {
                { VERSION, version },
                { ENCODING, Options.Encoding },
                { SIGNMETHOD, Options.SignMethod },

                { TXNTYPE, request.GetTxnType() },
                { TXNSUBTYPE, request.GetTxnSubType() },
                { BIZTYPE, request.GetBizType() },
                { CHANNELTYPE, request.GetChannelType() },

                { ACCESSTYPE, Options.AccessType },
                { MERID, Options.MerId },
            };

            UnionPaySignature.Sign(txtParams, SignCertificate.certId, SignCertificate.key, Options.SecureKey);

            var rsp = Activator.CreateInstance <T>();

            var url = request.GetRequestUrl(Options.TestMode);

            if (reqMethod == "GET")
            {
                //拼接get请求的url
                var tmpUrl = url;
                if (txtParams != null && txtParams.Count > 0)
                {
                    if (tmpUrl.Contains("?"))
                    {
                        tmpUrl = tmpUrl + "&" + HttpClientEx.BuildQuery(txtParams);
                    }
                    else
                    {
                        tmpUrl = tmpUrl + "?" + HttpClientEx.BuildQuery(txtParams);
                    }
                }
                rsp.Body = tmpUrl;
            }
            else
            {
                //输出post表单
                rsp.Body = BuildHtmlRequest(url, txtParams, reqMethod);
            }

            return(Task.FromResult(rsp));
        }
Exemple #5
0
        public Task <T> ExecuteAsync <T>(HttpRequest request) where T : AlipayNotifyResponse
        {
            var parameters = GetParameters(request);
            var parser     = new AlipayDictionaryParser <T>();
            var rsp        = parser.Parse(parameters);

            var query = HttpClientEx.BuildQuery(parameters);

            Logger.LogInformation(0, "Request Content:{query}", query);

            CheckNotifySign(parameters, RSAPublicParameters, Options.SignType);
            return(Task.FromResult(rsp));
        }
        public async Task <T> ExecuteAsync <T>(HttpRequest request) where T : UnionPayNotifyResponse
        {
            var parameters = await GetParametersAsync(request);

            var query = HttpClientEx.BuildQuery(parameters);

            Logger?.LogTrace(0, "Request:{query}", query);

            var parser = new UnionPayDictionaryParser <T>();
            var rsp    = parser.Parse(parameters);

            CheckNotifySign(parameters);
            return(rsp);
        }
Exemple #7
0
        public Task <T> PageExecuteAsync <T>(ILianLianPayRequest <T> request, string reqMethod) where T : LianLianPayResponse
        {
            var txtParams = new LianLianPayDictionary(request.GetParameters())
            {
                { OID_PARTNER, Options.OidPartner },
                { SIGN_TYPE, Options.SignType },
                { BUSI_PARTNER, Options.BusiPartner },
                { TIMESTAMP, DateTime.Now },
            };

            // 添加签名
            var signContent = LianLianPaySecurity.GetSignContent(txtParams);

            txtParams.Add(SIGN, MD5WithRSA.SignData(signContent, PrivateKey));

            var body = string.Empty;

            if (reqMethod == "GET")
            {
                //拼接get请求的url
                var tmpUrl = request.GetRequestUrl();
                if (txtParams != null && txtParams.Count > 0)
                {
                    if (tmpUrl.Contains("?"))
                    {
                        tmpUrl = tmpUrl + "&" + HttpClientEx.BuildQuery(txtParams);
                    }
                    else
                    {
                        tmpUrl = tmpUrl + "?" + HttpClientEx.BuildQuery(txtParams);
                    }
                }
                body = tmpUrl;
                Logger.LogInformation(0, "Request Url:{body}", body);
            }
            else
            {
                //输出post表单
                body = BuildHtmlRequest(request.GetRequestUrl(), txtParams);
                Logger.LogInformation(0, "Request Html:{body}", body);
            }

            var parser = new LianLianPayJsonParser <T>();
            var rsp    = parser.Parse(body);

            return(Task.FromResult(rsp));
        }
Exemple #8
0
        private async Task <AlipayResponse> DoGetAsync(AlipayDictionary parameters, Stream outStream)
        {
            AlipayMobilePublicMultiMediaDownloadResponse response = null;

            var url = Options.ServerUrl;

            if (parameters != null && parameters.Count > 0)
            {
                if (url.Contains("?"))
                {
                    url = url + "&" + HttpClientEx.BuildQuery(parameters);
                }
                else
                {
                    url = url + "?" + HttpClientEx.BuildQuery(parameters);
                }
            }


            using (var clientResponse = await Client.GetAsync(url))
            {
                if (clientResponse.StatusCode == HttpStatusCode.OK)
                {
                    using (var content = clientResponse.Content)
                    {
                        if (content.Headers.ContentType.ToString().ToLower().Contains("text/plain"))
                        {
                            var body = await content.ReadAsStringAsync();

                            IAlipayParser <AlipayMobilePublicMultiMediaDownloadResponse> tp = new AlipayJsonParser <AlipayMobilePublicMultiMediaDownloadResponse>();
                            response = tp.Parse(body);
                        }
                        else
                        {
                            outStream = await content.ReadAsStreamAsync();

                            response = new AlipayMobilePublicMultiMediaDownloadResponse();
                        }
                    }
                }
            }

            return(response);
        }
Exemple #9
0
        public async Task <T> ExecuteAsync <T>(IJDPayNPP10Request <T> request) where T : JDPayResponse
        {
            var sortedTxtParams = new JDPayDictionary(request.GetParameters())
            {
                { Contants.CUSTOMER_NO, Options.CustomerNo },
                { Contants.SIGN_TYPE, Options.SignType }
            };

            var isEncrypt = false;

            if (request is JDPayDefrayPayRequest)
            {
                isEncrypt = true;
            }

            var encryptDic = JDPaySecurity.EncryptData(Options.PrivateCret, Options.Password, Options.PublicCert, sortedTxtParams, Options.SingKey, Options.EncryptType, isEncrypt);

            var content = HttpClientEx.BuildQuery(encryptDic);

            Logger?.LogTrace(0, "Request:{content}", content);

            var body = await Client.DoPostAsync(request.GetRequestUrl(), content, "application/x-www-form-urlencoded");

            Logger?.LogTrace(1, "Response:{content}", body);

            var rsp = JsonConvert.DeserializeObject <T>(body);

            // 验签
            var dic = JsonConvert.DeserializeObject <JDPayDictionary>(body);

            if (!JDPaySecurity.VerifySign(dic, Options.SingKey))
            {
                throw new Exception("sign check fail: check Sign and Data Fail!");
            }

            rsp.Body = body;
            return(rsp);
        }
Exemple #10
0
        public async Task <T> ExecuteAsync <T>(HttpRequest request) where T : JdPayNotifyResponse
        {
            if (request.ContentType == "application/x-www-form-urlencoded")
            {
                var dic = new JdPayDictionary();
                foreach (var item in request.Form)
                {
                    if (!string.IsNullOrEmpty(item.Value))
                    {
                        if (item.Key == "sign")
                        {
                            dic.Add(item.Key, item.Value);
                        }
                        else
                        {
                            dic.Add(item.Key, DES3.DecryptECB(DesKey, item.Value));
                        }
                    }
                }

                var query = HttpClientEx.BuildQuery(dic);
                Logger.LogInformation(1, "Request Content:{query}", query);

                var parser = new JdPayDictionaryParser <T>();
                var rsp    = parser.Parse(dic);

                CheckNotifySign(dic, RSAPrivateParameters);
                return(rsp);
            }
            else
            {
                var body = await new StreamReader(request.Body).ReadToEndAsync();
                Logger.LogInformation(1, "Request Content:{body}", body);

                var rsp = DecryptResponseXml <T>(JdPayUtil.FotmatXmlString(body));
                return(rsp);
            }
        }
        public async Task <T> ExecuteAsync <T>(HttpRequest request) where T : AlipayNotifyResponse
        {
            try
            {
                logger?.LogDebug($"{DateTime.Now} 支付宝回调ExecuteAsync");

                var parameters = await GetParametersAsync(request);

                var query = HttpClientEx.BuildQuery(parameters);

                logger?.LogDebug($"{DateTime.Now} 支付宝回调ExecuteAsync Request:{query}");

                var parser = new AlipayDictionaryParser <T>();
                var rsp    = parser.Parse(parameters);
                CheckNotifySign(parameters, PublicRSAParameters, Options.SignType);
                return(rsp);
            }
            catch (Exception ex)
            {
                logger?.LogError($"{DateTime.Now} 支付宝回调ExecuteAsync报错", ex.Message);
                return(null);
            }
        }
Exemple #12
0
        public T SdkExecute <T>(IAlipayRequest <T> request) where T : AlipayResponse
        {
            // 构造请求参数
            var requestParams = BuildRequestParams(request, null, null);

            // 字典排序
            var sortedParams    = new SortedDictionary <string, string>(requestParams);
            var sortedAlipayDic = new AlipayDictionary(sortedParams);

            // 参数签名
            var signResult = AlipaySignature.RSASign(sortedAlipayDic, Options.RsaPrivateKey, Options.SignType);

            // 添加签名结果参数
            sortedAlipayDic.Add(SIGN, signResult);

            // 参数拼接
            var signedResult = HttpClientEx.BuildQuery(sortedAlipayDic);

            // 构造结果
            var rsp = (T)Activator.CreateInstance(typeof(T));

            rsp.Body = signedResult;
            return(rsp);
        }
Exemple #13
0
        public async Task <T> ExecuteAsync <T>(IAlipayRequest <T> request, string accessToken, string appAuthToken) where T : AlipayResponse
        {
            var apiVersion = string.Empty;

            if (!string.IsNullOrEmpty(request.GetApiVersion()))
            {
                apiVersion = request.GetApiVersion();
            }
            else
            {
                apiVersion = Options.Version;
            }

            // 添加协议级请求参数
            var txtParams = new AlipayDictionary(request.GetParameters())
            {
                // 序列化BizModel
                { BIZ_CONTENT, Serialize(request.GetBizModel()) },
                // 添加协议级请求参数
                { METHOD, request.GetApiName() },
                { VERSION, apiVersion },
                { APP_ID, Options.AppId },
                { FORMAT, Options.Format },
                { TIMESTAMP, DateTime.Now },
                { ACCESS_TOKEN, accessToken },
                { SIGN_TYPE, Options.SignType },
                { TERMINAL_TYPE, request.GetTerminalType() },
                { TERMINAL_INFO, request.GetTerminalInfo() },
                { PROD_CODE, request.GetProdCode() },
                { CHARSET, Options.Charset }
            };

            if (!string.IsNullOrEmpty(request.GetNotifyUrl()))
            {
                txtParams.Add(NOTIFY_URL, request.GetNotifyUrl());
            }

            if (!string.IsNullOrEmpty(appAuthToken))
            {
                txtParams.Add(APP_AUTH_TOKEN, appAuthToken);
            }

            if (request.GetNeedEncrypt())
            {
                if (string.IsNullOrEmpty(txtParams[BIZ_CONTENT]))
                {
                    throw new Exception("api request Fail ! The reason: encrypt request is not supported!");
                }

                if (string.IsNullOrEmpty(Options.EncyptKey) || string.IsNullOrEmpty(Options.EncyptType))
                {
                    throw new Exception("encryptType or encryptKey must not null!");
                }

                if (!"AES".Equals(Options.EncyptType))
                {
                    throw new Exception("api only support Aes!");
                }

                var encryptContent = AES.Encrypt(txtParams[BIZ_CONTENT], Options.EncyptKey, AlipaySignature.AES_IV, AESCipherMode.CBC, AESPaddingMode.PKCS7);
                txtParams.Remove(BIZ_CONTENT);
                txtParams.Add(BIZ_CONTENT, encryptContent);
                txtParams.Add(ENCRYPT_TYPE, Options.EncyptType);
            }

            // 添加签名参数
            var signContent = AlipaySignature.GetSignContent(txtParams);

            txtParams.Add(SIGN, AlipaySignature.RSASignContent(signContent, PrivateRSAParameters, Options.SignType));

            var query = HttpClientEx.BuildQuery(txtParams);

            Logger?.LogTrace(0, "Request:{query}", query);

            // 是否需要上传文件
            var body = string.Empty;

            if (request is IAlipayUploadRequest <T> uRequest)
            {
                var fileParams = AlipayUtility.CleanupDictionary(uRequest.GetFileParameters());
                body = await Client.DoPostAsync(Options.ServerUrl, txtParams, fileParams);
            }
            else
            {
                body = await Client.DoPostAsync(Options.ServerUrl, query);
            }

            Logger?.LogTrace(1, "Response:{body}", body);

            T rsp = null;
            IAlipayParser <T> parser = null;

            if ("xml".Equals(Options.Format))
            {
                parser = new AlipayXmlParser <T>();
                rsp    = parser.Parse(body);
            }
            else
            {
                parser = new AlipayJsonParser <T>();
                rsp    = parser.Parse(body);
            }

            var item = ParseRespItem(request, body, parser, Options.EncyptKey, Options.EncyptType);

            rsp = parser.Parse(item.realContent);

            CheckResponseSign(request, item.respContent, rsp.IsError, parser, PublicRSAParameters, Options.SignType);

            return(rsp);
        }
Exemple #14
0
        public async Task <T> ExecuteAsync <T>(HttpRequest request) where T : JDPayNotifyResponse
        {
            if (request.HasFormContentType || request.Method == "GET")
            {
                var parameters = await GetParametersAsync(request);

                var query = HttpClientEx.BuildQuery(parameters);
                Logger?.LogTrace(0, "Request:{query}", query);

                var parser = new JDPayDictionaryParser <T>();
                var rsp    = parser.Parse(parameters);

                CheckNotifySign(rsp.Parameters);
                return(rsp);
            }
            else if (request.HasTextXmlContentType())
            {
                var body = await new StreamReader(request.Body).ReadToEndAsync();
                Logger?.LogTrace(0, "Request:{body}", body);

                var parser = new JDPayXmlParser <T>();
                var rsp    = parser.Parse(JDPayUtility.FotmatXmlString(body));
                if (!string.IsNullOrEmpty(rsp.Encrypt))
                {
                    var encrypt          = rsp.Encrypt;
                    var base64EncryptStr = Encoding.UTF8.GetString(Convert.FromBase64String(encrypt));
                    var reqBody          = JDPaySecurity.DecryptECB(base64EncryptStr, DesKey);
                    Logger?.LogTrace(1, "Encrypt Content:{reqBody}", reqBody);

                    var reqBodyDoc = new XmlDocument();
                    reqBodyDoc.LoadXml(reqBody);

                    var sign     = JDPayUtility.GetValue(reqBodyDoc, "sign");
                    var rootNode = reqBodyDoc.SelectSingleNode("jdpay");
                    var signNode = rootNode.SelectSingleNode("sign");
                    rootNode.RemoveChild(signNode);

                    var reqBodyStr = JDPayUtility.ConvertXmlToString(reqBodyDoc);
                    var xmlh       = rsp.Body.Substring(0, rsp.Body.IndexOf("<jdpay>"));
                    if (!string.IsNullOrEmpty(xmlh))
                    {
                        reqBodyStr = reqBodyStr.Replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", xmlh);
                    }
                    var sha256SourceSignString = SHA256.Compute(reqBodyStr);
                    var decryptByte            = RSA_ECB_PKCS1Padding.Decrypt(Convert.FromBase64String(sign), PublicKey);
                    var decryptStr             = JDPaySecurity.BytesToString(decryptByte);
                    if (sha256SourceSignString == decryptStr)
                    {
                        rsp         = parser.Parse(reqBody);
                        rsp.Encrypt = encrypt;
                        return(rsp);
                    }
                    else
                    {
                        throw new Exception("sign check fail: check Sign and Data Fail!");
                    }
                }
                else
                {
                    throw new Exception("encrypt is Empty!");
                }
            }
            else
            {
                throw new Exception("Content type is not supported!");
            }
        }
        public async Task <T> PageExecuteAsync <T>(IAlipayRequest <T> request, string accessToken, string reqMethod) where T : AlipayResponse
        {
            try
            {
                logger?.LogDebug($"{DateTime.Now} 支付宝PageExecuteAsync");

                string apiVersion = null;

                if (!string.IsNullOrEmpty(request.GetApiVersion()))
                {
                    apiVersion = request.GetApiVersion();
                }
                else
                {
                    apiVersion = Options.Version;
                }

                var txtParams = new AlipayDictionary(request.GetParameters())
                {
                    // 序列化BizModel
                    { BIZ_CONTENT, Serialize(request.GetBizModel()) },
                    // 添加协议级请求参数
                    { METHOD, request.GetApiName() },
                    { VERSION, apiVersion },
                    { APP_ID, Options.AppId },
                    { FORMAT, Options.Format },
                    { TIMESTAMP, DateTime.Now },
                    { ACCESS_TOKEN, accessToken },
                    { SIGN_TYPE, Options.SignType },
                    { TERMINAL_TYPE, request.GetTerminalType() },
                    { TERMINAL_INFO, request.GetTerminalInfo() },
                    { PROD_CODE, request.GetProdCode() },
                    { NOTIFY_URL, request.GetNotifyUrl() },
                    { CHARSET, Options.Charset },
                    { RETURN_URL, request.GetReturnUrl() }
                };

                // 添加签名参数
                var signContent = AlipaySignature.GetSignContent(txtParams);
                txtParams.Add(SIGN, AlipaySignature.RSASignContent(signContent, PrivateRSAParameters, Options.SignType));

                // 是否需要上传文件
                var body = string.Empty;

                if (request is IAlipayUploadRequest <T> uRequest)
                {
                    var fileParams = AlipayUtility.CleanupDictionary(uRequest.GetFileParameters());
                    body = await Client.DoPostAsync(Options.ServerUrl, txtParams, fileParams);
                }
                else
                {
                    if (reqMethod.ToUpper() == "GET")
                    {
                        //拼接get请求的url
                        var tmpUrl = Options.ServerUrl;
                        if (txtParams != null && txtParams.Count > 0)
                        {
                            if (tmpUrl.Contains("?"))
                            {
                                tmpUrl = tmpUrl + "&" + HttpClientEx.BuildQuery(txtParams);
                            }
                            else
                            {
                                tmpUrl = tmpUrl + "?" + HttpClientEx.BuildQuery(txtParams);
                            }
                        }
                        body = tmpUrl;
                        logger?.LogDebug(0, "Request Url:{body}", body);
                    }
                    else
                    {
                        //输出post表单
                        body = BuildHtmlRequest(txtParams, reqMethod);
                        logger?.LogDebug(0, "Request Html:{body}", body);
                    }
                }

                T rsp = null;
                IAlipayParser <T> parser = null;
                if ("xml".Equals(Options.Format))
                {
                    parser = new AlipayXmlParser <T>();
                    rsp    = parser.Parse(body);
                }
                else
                {
                    parser = new AlipayJsonParser <T>();
                    rsp    = parser.Parse(body);
                }
                return(rsp);
            }
            catch (Exception ex)
            {
                logger?.LogError($"{DateTime.Now} 支付宝PageExecuteAsync报错", ex.Message);
                return(null);
            }
        }
Exemple #16
0
        public async Task <T> ExecuteAsync <T>(IUnionPayRequest <T> request) where T : UnionPayResponse
        {
            var version = string.Empty;

            if (!string.IsNullOrEmpty(request.GetApiVersion()))
            {
                version = request.GetApiVersion();
            }
            else
            {
                version = Options.Version;
            }

            var merId = Options.MerId;

            if (Options.TestMode && (request is UnionPayForm05_7_FileTransferRequest || request is UnionPayForm_6_6_FileTransferRequest))
            {
                merId = "700000000000001";
            }

            var txtParams = new UnionPayDictionary(request.GetParameters())
            {
                { VERSION, version },
                { ENCODING, Options.Encoding },
                { SIGNMETHOD, Options.SignMethod },

                { TXNTYPE, request.GetTxnType() },
                { TXNSUBTYPE, request.GetTxnSubType() },
                { BIZTYPE, request.GetBizType() },
                { CHANNELTYPE, request.GetChannelType() },

                { ACCESSTYPE, Options.AccessType },
                { MERID, merId },
            };

            UnionPaySignature.Sign(txtParams, SignCertificate.certId, SignCertificate.key, Options.SecureKey);
            var query = HttpClientEx.BuildQuery(txtParams);

            Logger.LogInformation(0, "Request Content:{query}", query);

            var rspContent = await Client.DoPostAsync(request.GetRequestUrl(Options.TestMode), query);

            Logger.LogInformation(1, "Response Content:{content}", rspContent.Content);

            if (rspContent.ContentType.Contains("text/plain"))
            {
                throw new Exception(rspContent.Content);
            }

            var dic = ParseQueryString(rspContent.Content);

            if (dic == null || dic.Count == 0)
            {
                throw new Exception("sign check fail: Body is Empty!");
            }

            var ifValidateCNName = !Options.TestMode;

            if (!UnionPaySignature.Validate(dic, RootCertificate.cert, MiddleCertificate.cert, Options.SecureKey, ifValidateCNName))
            {
                throw new Exception("sign check fail: check Sign and Data Fail!");
            }

            var parser = new UnionPayDictionaryParser <T>();
            var rsp    = parser.Parse(dic);

            rsp.Body = rspContent.Content;
            return(rsp);
        }
Exemple #17
0
        public async Task <T> PageExecuteAsync <T>(IAlipayRequest <T> request, string accessToken, string reqMethod) where T : AlipayResponse
        {
            string apiVersion = null;

            if (!string.IsNullOrEmpty(request.GetApiVersion()))
            {
                apiVersion = request.GetApiVersion();
            }
            else
            {
                apiVersion = Options.Version;
            }

            var txtParams = new AlipayDictionary(request.GetParameters())
            {
                // 序列化BizModel
                { BIZ_CONTENT, JsonConvert.SerializeObject(request.GetBizModel(), new JsonSerializerSettings()
                    {
                        NullValueHandling = NullValueHandling.Ignore
                    }) },
                // 添加协议级请求参数
                { METHOD, request.GetApiName() },
                { VERSION, apiVersion },
                { APP_ID, Options.AppId },
                { FORMAT, Options.Format },
                { TIMESTAMP, DateTime.Now },
                { ACCESS_TOKEN, accessToken },
                { SIGN_TYPE, Options.SignType },
                { TERMINAL_TYPE, request.GetTerminalType() },
                { TERMINAL_INFO, request.GetTerminalInfo() },
                { PROD_CODE, request.GetProdCode() },
                { NOTIFY_URL, request.GetNotifyUrl() },
                { CHARSET, Options.Charset },
                { RETURN_URL, request.GetReturnUrl() }
            };

            // 添加签名参数
            txtParams.Add(SIGN, AlipaySignature.RSASign(txtParams, Options.RsaPrivateKey, Options.SignType));

            // 是否需要上传文件
            string body;

            if (request is IAlipayUploadRequest <T> uRequest)
            {
                var fileParams = AlipayUtility.CleanupDictionary(uRequest.GetFileParameters());
                body = await Client.DoPostAsync(Options.ServerUrl, txtParams, fileParams);
            }
            else
            {
                if (reqMethod.Equals("GET"))
                {
                    //拼接get请求的url
                    var tmpUrl = Options.ServerUrl;
                    if (txtParams != null && txtParams.Count > 0)
                    {
                        if (tmpUrl.Contains("?"))
                        {
                            tmpUrl = tmpUrl + "&" + HttpClientEx.BuildQuery(txtParams);
                        }
                        else
                        {
                            tmpUrl = tmpUrl + "?" + HttpClientEx.BuildQuery(txtParams);
                        }
                    }
                    body = tmpUrl;
                }
                else
                {
                    //输出post表单
                    body = BuildHtmlRequest(txtParams, reqMethod, reqMethod);
                }
            }

            T rsp = null;
            IAlipayParser <T> parser = null;

            if ("json".Equals(Options.Format))
            {
                parser = new AlipayJsonParser <T>();
                rsp    = parser.Parse(body);
            }
            return(rsp);
        }
Exemple #18
0
        public async Task <T> ExecuteAsync <T>(IUnionPayRequest <T> request) where T : UnionPayResponse
        {
            var version = string.Empty;

            if (!string.IsNullOrEmpty(request.GetApiVersion()))
            {
                version = request.GetApiVersion();
            }
            else
            {
                version = Options.Version;
            }

            var merId = Options.MerId;

            if (Options.TestMode && (request is UnionPayForm05_7_FileTransferRequest || request is UnionPayForm_6_6_FileTransferRequest))
            {
                merId = "700000000000001";
            }

            var txtParams = new UnionPayDictionary(request.GetParameters())
            {
                { VERSION, version },
                { ENCODING, Options.Encoding },
                { SIGNMETHOD, Options.SignMethod },
                { ACCESSTYPE, Options.AccessType },
                { MERID, merId },
            };

            if (request.HasEncryptCertId())
            {
                txtParams.Add(ENCRYPTCERTID, EncryptCertificate.certId);
            }

            UnionPaySignature.Sign(txtParams, SignCertificate.certId, SignCertificate.key, Options.SecureKey);

            var query = HttpClientEx.BuildQuery(txtParams);

            Logger?.LogTrace(0, "Request:{query}", query);

            var body = await Client.DoPostAsync(request.GetRequestUrl(Options.TestMode), query);

            Logger?.LogTrace(1, "Response:{content}", body.Content);

            var dic = ParseQueryString(body.Content);

            if (string.IsNullOrEmpty(body.Content))
            {
                throw new Exception("sign check fail: Body is Empty!");
            }

            var ifValidateCNName = !Options.TestMode;

            if (!UnionPaySignature.Validate(dic, RootCertificate.cert, MiddleCertificate.cert, Options.SecureKey, ifValidateCNName))
            {
                throw new Exception("sign check fail: check Sign and Data Fail!");
            }

            var parser = new UnionPayDictionaryParser <T>();
            var rsp    = parser.Parse(dic);

            rsp.Body = body.Content;
            return(rsp);
        }