Пример #1
0
        /// <summary>
        /// 生成RSA签名后的订单字符串
        /// </summary>
        /// <param name="price"></param>
        /// <param name="description"></param>
        /// <returns></returns>
        public static string createRSASignedOrderString(double price, string description)
        {
            Dictionary <string, string> orderStringDict = new Dictionary <string, string>();

            orderStringDict.Add("app_id", APP_ID);
            orderStringDict.Add("method", "alipay.trade.app.pay");
            orderStringDict.Add("format", "JSON");
            orderStringDict.Add("charset", "utf-8");
            orderStringDict.Add("sign_type", "RSA");
            orderStringDict.Add("timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            orderStringDict.Add("version", "1.0");
            orderStringDict.Add("notify_url", "");
            orderStringDict.Add("biz_content", generateBizContentString(price.ToString(), description));

            // 排序拼接成字符串
            string orderInfo        = AlipaySignature.GetSignContent(orderStringDict);
            string orderInfoEncoded = Core.CreateLinkStringUrlencode(orderStringDict, (new System.Text.UTF8Encoding()));

            // 签名
            string privateKeyPem = GetCurrentPath() + "rsa_private_key.pem";
            string signString    = AlipaySignature.RSASign(orderInfo, privateKeyPem, null, "RSA");

            signString = HttpUtility.UrlEncode(signString, new UTF8Encoding());

            // 加上sign
            string orderString = orderInfoEncoded + "&sign=" + signString;

            // 拼接最终返回给客户端的字符串
            return(orderString);
        }
Пример #2
0
    public static string com_alipay_account_auth()
    {
        IDictionary <string, string> paramsMap = new Dictionary <string, string>();

        paramsMap.Add("scope", "kuaijie");
        paramsMap.Add("product_id", "APP_FAST_LOGIN");
        paramsMap.Add("pid", Pid);
        paramsMap.Add("apiname", "com.alipay.account.auth");
        paramsMap.Add("auth_type", "AUTHACCOUNT");
        paramsMap.Add("biz_type", "openservice");
        paramsMap.Add("app_id", appId);
        paramsMap.Add("target_id", "RSA");
        paramsMap.Add("app_name", "mc");
        paramsMap.Add("sign_type", "RSA");


        string privateKeyPem = merchant_private_key;
        string sign          = AlipaySignature.RSASign(paramsMap, privateKeyPem, null, false, "RSA");

        paramsMap.Add("sign", System.Web.HttpUtility.UrlEncode(sign));

        var str = AlipaySignature.GetSignContent(paramsMap);

        return(str);
    }
Пример #3
0
        /// <summary>
        /// 统一下单并支付页面接口-alipay.acquire.page.createandpay(首次扣款和签约合并)
        /// </summary>
        /// <returns></returns>
        public string AlipayAcquirePageCreateandpay()
        {
            Dictionary <string, string> dic = new Dictionary <string, string>();

            // 基本参数
            dic.Add("service", "alipay.acquire.page.createandpay");
            dic.Add("partner", AlipayConfig.Pid);
            dic.Add("product_code", "GENERAL_WITHHOLDING");
            dic.Add("integration_type", "ALIAPP");
            dic.Add("_input_charset", "utf-8");
            // 业务参数
            dic.Add("out_trade_no", "DX" + DateTime.Now.ToString("yyyyMMddHHssmmffff")); //商户网站唯一订单号
            dic.Add("subject", "TestOrder");                                             //订单标题
            dic.Add("total_fee", "0.01");                                                // 订单金额
            dic.Add("agreement_sign_parameters", "{\"productCode\":\"GENERAL_WITHHOLDING_P\",\"scene\":\"INDUSTRY|APPSTORE\",\"notifyUrl\":\"https://www.gingergo.cn/api/alipay/signed\",\"externalAgreementNo\":\"\"}");
            dic.Add("notify_url", "https://www.gingergo.cn/api/alipay/signed");
            dic.Add("request_from_url", "https://www.gingergo.cn/api/alipay/signed");
            dic.Add("return_url", "https://www.gingergo.cn/api/alipay/signed");
            dic.Add("seller_id", AlipayConfig.Pid);


            var @params = AlipaySignature.GetSignContent(dic);
            var sign    = Md5Sign(@params, AlipayConfig.Md5Key, "utf-8");

            dic.Add("sign", sign);
            dic.Add("sign_type", "MD5");
            var content = AlipaySignature.GetSignContent(dic);

            return(content);
        }
Пример #4
0
        public Task <T> SdkExecuteAsync <T>(IAlipayRequest <T> request, string optionsName) where T : AlipayResponse
        {
            var options = string.IsNullOrEmpty(optionsName) ? _optionsSnapshotAccessor.Value : _optionsSnapshotAccessor.Get(optionsName);

            // 构造请求参数
            var requestParams = BuildRequestParams(request, null, null, options);

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

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

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

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

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

            rsp.Body = signedResult;
            return(Task.FromResult(rsp));
        }
Пример #5
0
        public string AcquirePageCreateandpay()
        {
            Dictionary <string, string> dic = new Dictionary <string, string>();

            dic.Add("service", "alipay.dut.customer.agreement.page.sign");
            dic.Add("partner", AlipayConfig.Pid);
            dic.Add("product_code", "GENERAL_WITHHOLDING_P");
            //dic.Add("access_info", "{\"channel\":\"ALIPAYAPP\"}");
            dic.Add("access_info", "{\"channel\":\"PC\"}");
            dic.Add("_input_charset", "utf-8");

            //dic.Add("scene", "INDUSTRY|CARRENTAL");
            //dic.Add("agreement_sign_parameters", Newtonsoft.Json.JsonConvert.SerializeObject(dic));
            //dic.Add("notify_url", AlipayConfig.NotifyUrl);
            //dic.Add("out_trade_no", "201601010001x");
            //dic.Add("request_from_url", "test");
            //dic.Add("seller_id", AlipayConfig.SellerId);
            //var sign = AlipaySignature.RSASign(dic,AlipayConfig.AliPayHzhbPrivateKey, AlipayConfig.Charset,false, AliPaySignType.RSA.ToString());
            var @params = AlipaySignature.GetSignContent(dic);
            var sign    = Md5Sign(@params, AlipayConfig.Md5Key, "utf-8");

            dic.Add("sign", sign);
            dic.Add("sign_type", "MD5");
            var content = AlipaySignature.GetSignContent(dic);

            return(content);
        }
Пример #6
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));
        }
Пример #7
0
        /// <summary>
        /// 检查支付宝返回的参数签名
        /// </summary>
        /// <param name="parameters">参数列表</param>
        /// <returns></returns>
        public virtual bool CheckSign(SortedDictionary <string, string> parameters)
        {
            var publicKey = UseSandBox ? SandBoxAlipayPublicKey : AlipayPublicKey;
            var sign      = parameters["sign"];

            parameters.Remove("sign");
            parameters.Remove("sign_type");
            // RSACheckV1和RSACheckV2的key参数是文件路径
            // 以下的函数只支持RSA + SHA1
            return(AlipaySignature.RSACheckContent(
                       AlipaySignature.GetSignContent(parameters), sign, publicKey, "utf-8", false));
        }
Пример #8
0
        public Task <T> SdkExecuteAsync <T>(IAlipayRequest <T> request, AlipayOptions options) where T : AlipayResponse
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            if (string.IsNullOrEmpty(options.AppId))
            {
                throw new ArgumentNullException(nameof(options.AppId));
            }

            if (string.IsNullOrEmpty(options.SignType))
            {
                throw new ArgumentNullException(nameof(options.SignType));
            }

            if (string.IsNullOrEmpty(options.AppPrivateKey))
            {
                throw new ArgumentNullException(nameof(options.AppPrivateKey));
            }

            if (string.IsNullOrEmpty(options.ServerUrl))
            {
                throw new ArgumentNullException(nameof(options.ServerUrl));
            }

            // 构造请求参数
            var requestParams = BuildRequestParams(request, null, null, options);

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

            // 参数签名
            var signContent = AlipaySignature.GetSignContent(sortedDic);
            var signResult  = AlipaySignature.RSASignContent(signContent, options.AppPrivateKey, options.SignType);

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

            // 参数拼接
            var signedResult = AlipayUtility.BuildQuery(sortedDic);

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

            rsp.ResponseBody = signedResult;
            return(Task.FromResult(rsp));
        }
Пример #9
0
        private static void CheckNotifySign(IDictionary <string, string> dictionary, AlipayOptions options)
        {
            if (dictionary == null || dictionary.Count == 0)
            {
                throw new AlipayException("sign check fail: dictionary)} is Empty!");
            }

            if (!dictionary.TryGetValue(AlipayConstants.SIGN, out var sign))
            {
                throw new AlipayException("sign check fail: sign)} is Empty!");
            }

            dictionary.Remove(AlipayConstants.SIGN);
            dictionary.Remove(AlipayConstants.SIGN_TYPE);
            var content = AlipaySignature.GetSignContent(dictionary);

            if (!AlipaySignature.RSACheckContent(content, sign, options.AlipayPublicKey, options.SignType))
            {
                throw new AlipayException("sign check fail: check Sign and Data Fail!");
            }
        }
Пример #10
0
        public IHttpActionResult AliPaySign(int OrderID)
        {
            WebApi_BLL.T_Product_Orders   bll   = new WebApi_BLL.T_Product_Orders();
            WebApi_Model.T_Product_Orders order = bll.GetModel(OrderID);

            if (order == null)
            {
                return(Ok(ReturnJsonResult.GetJsonResult(-1, "Error", "找不到订单")));
            }
            else if (order.Status != 0)
            {
                return(Ok(ReturnJsonResult.GetJsonResult(-1, "Error", "找不到需要支付的订单")));
            }
            else
            {
                Dictionary <string, string> parameters = new Dictionary <string, string>();
                parameters.Add("app_id", ConfigurationManager.AppSettings["app_id"].ToString());
                parameters.Add("biz_content", "{\"timeout_express\":\"30m\",\"seller_id\":\"" + ConfigurationManager.AppSettings["seller_id"].ToString() + "\",\"product_code\":\"QUICK_MSECURITY_PAY\",\"total_amount\":\"" + order.TotalAmount + "\",\"subject\":\"商品支付" + order.OrderID + "\",\"body\":\"支付\",\"out_trade_no\":\"" + order.OrderNum + "\"}");
                parameters.Add("charset", "utf-8");
                parameters.Add("format", "json");
                parameters.Add("method", "alipay.trade.app.pay");
                parameters.Add("notify_url", ConfigurationManager.AppSettings["notify_url"].ToString());
                parameters.Add("sign_type", "RSA");
                parameters.Add("timestamp", DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));
                parameters.Add("version", "1.0");

                string strSignContent = AlipaySignature.GetSignContent(parameters);
                string strSign        = AlipaySignature.RSASign(parameters, System.Web.Hosting.HostingEnvironment.MapPath("~/Content/Key/rsa_private_key.pem"), "", "RSA");

                //parameters.Add("sign", strSign);

                string strRet = Decode(parameters) + "&sign=" + HttpUtility.UrlEncode(strSign);
                //string str = strSignContent + "&sign=" + strSign;
                return(Ok(ReturnJsonResult.GetJsonResult(1, "OK", strRet)));
            }
        }
Пример #11
0
        public async Task <T> PageExecuteAsync <T>(IAlipayRequest <T> request, string optionsName, string accessToken, string reqMethod) where T : AlipayResponse
        {
            var options    = _optionsSnapshotAccessor.Get(optionsName);
            var apiVersion = string.IsNullOrEmpty(request.GetApiVersion()) ? options.Version : request.GetApiVersion();

            // 添加协议级请求参数
            var txtParams = new AlipayDictionary(request.GetParameters())
            {
                { 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() }
            };

            // 序列化BizModel
            txtParams = SerializeBizModel(txtParams, request);

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

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

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

            if (request is IAlipayUploadRequest <T> uRequest)
            {
                var fileParams = AlipayUtility.CleanupDictionary(uRequest.GetFileParameters());

                using (var client = _clientFactory.CreateClient())
                {
                    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 + "&" + AlipayUtility.BuildQuery(txtParams);
                        }
                        else
                        {
                            tmpUrl = tmpUrl + "?" + AlipayUtility.BuildQuery(txtParams);
                        }
                    }
                    body = tmpUrl;
                    _logger.Log(options.LogLevel, "Request Url:{body}", body);
                }
                else
                {
                    //输出post表单
                    body = BuildHtmlRequest(txtParams, reqMethod, options);
                    _logger.Log(options.LogLevel, "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);
        }
Пример #12
0
        public async Task <T> PageExecuteAsync <T>(IAlipayRequest <T> request, AlipayOptions options, string accessToken, string reqMethod) where T : AlipayResponse
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            if (string.IsNullOrEmpty(options.AppId))
            {
                throw new ArgumentNullException(nameof(options.AppId));
            }

            if (string.IsNullOrEmpty(options.SignType))
            {
                throw new ArgumentNullException(nameof(options.SignType));
            }

            if (string.IsNullOrEmpty(options.AppPrivateKey))
            {
                throw new ArgumentNullException(nameof(options.AppPrivateKey));
            }

            if (string.IsNullOrEmpty(options.ServerUrl))
            {
                throw new ArgumentNullException(nameof(options.ServerUrl));
            }

            var apiVersion = string.IsNullOrEmpty(request.GetApiVersion()) ? options.Version : request.GetApiVersion();

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

            // 序列化BizModel
            txtParams = SerializeBizModel(txtParams, request);

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

            txtParams.Add(AlipayConstants.SIGN, AlipaySignature.RSASignContent(signContent, options.AppPrivateKey, options.SignType));

            string body;

            // 是否需要上传文件
            if (request is IAlipayUploadRequest <T> uploadRequest)
            {
                var fileParams = AlipayUtility.CleanupDictionary(uploadRequest.GetFileParameters());

                var client = _httpClientFactory.CreateClient(nameof(AlipayClient));
                body = await client.PostAsync(options.ServerUrl, txtParams, fileParams);
            }
            else
            {
                if (reqMethod.ToUpperInvariant() == "GET")
                {
                    var url = options.ServerUrl;
                    if (txtParams != null && txtParams.Count > 0)
                    {
                        if (url.Contains("?"))
                        {
                            url += "&" + AlipayUtility.BuildQuery(txtParams);
                        }
                        else
                        {
                            url += "?" + AlipayUtility.BuildQuery(txtParams);
                        }
                    }
                    body = url;
                }
                else
                {
                    body = BuildHtmlRequest(txtParams, options.ServerUrl, options.Charset, reqMethod);
                }
            }

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

            return(rsp);
        }
Пример #13
0
        public async Task <T> CertificateExecuteAsync <T>(IAlipayRequest <T> request, AlipayOptions options, string accessToken, string appAuthToken) where T : AlipayResponse
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            if (string.IsNullOrEmpty(options.AppId))
            {
                throw new ArgumentNullException(nameof(options.AppId));
            }

            if (string.IsNullOrEmpty(options.SignType))
            {
                throw new ArgumentNullException(nameof(options.SignType));
            }

            if (string.IsNullOrEmpty(options.AppPrivateKey))
            {
                throw new ArgumentNullException(nameof(options.AppPrivateKey));
            }

            if (string.IsNullOrEmpty(options.AppCert))
            {
                throw new ArgumentNullException(nameof(options.AppCert));
            }

            if (string.IsNullOrEmpty(options.AlipayPublicCert))
            {
                throw new ArgumentNullException(nameof(options.AlipayPublicCert));
            }

            if (string.IsNullOrEmpty(options.RootCert))
            {
                throw new ArgumentNullException(nameof(options.RootCert));
            }

            if (string.IsNullOrEmpty(options.ServerUrl))
            {
                throw new ArgumentNullException(nameof(options.ServerUrl));
            }

            var apiVersion = string.IsNullOrEmpty(request.GetApiVersion()) ? options.Version : request.GetApiVersion();

            // 添加协议级请求参数
            var txtParams = new AlipayDictionary(request.GetParameters())
            {
                { AlipayConstants.METHOD, request.GetApiName() },
                { AlipayConstants.VERSION, apiVersion },
                { AlipayConstants.APP_ID, options.AppId },
                { AlipayConstants.FORMAT, options.Format },
                { AlipayConstants.TIMESTAMP, DateTime.Now },
                { AlipayConstants.ACCESS_TOKEN, accessToken },
                { AlipayConstants.SIGN_TYPE, options.SignType },
                { AlipayConstants.TERMINAL_TYPE, request.GetTerminalType() },
                { AlipayConstants.TERMINAL_INFO, request.GetTerminalInfo() },
                { AlipayConstants.PROD_CODE, request.GetProdCode() },
                { AlipayConstants.CHARSET, options.Charset },
                { AlipayConstants.APP_CERT_SN, options.AppCertSN },
                { AlipayConstants.ALIPAY_ROOT_CERT_SN, options.RootCertSN }
            };

            // 序列化BizModel
            txtParams = SerializeBizModel(txtParams, request);

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

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

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

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

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

                var encryptContent = AlipaySignature.AESEncrypt(txtParams[AlipayConstants.BIZ_CONTENT], options.EncyptKey);
                txtParams.Remove(AlipayConstants.BIZ_CONTENT);
                txtParams.Add(AlipayConstants.BIZ_CONTENT, encryptContent);
                txtParams.Add(AlipayConstants.ENCRYPT_TYPE, options.EncyptType);
            }

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

            txtParams.Add(AlipayConstants.SIGN, AlipaySignature.RSASignContent(signContent, options.AppPrivateKey, options.SignType));

            string body;
            var    client = _httpClientFactory.CreateClient(nameof(AlipayClient));

            // 是否需要上传文件
            if (request is IAlipayUploadRequest <T> uRequest)
            {
                var fileParams = AlipayUtility.CleanupDictionary(uRequest.GetFileParameters());

                body = await client.PostAsync(options.ServerUrl, txtParams, fileParams);
            }
            else
            {
                body = await client.PostAsync(options.ServerUrl, txtParams);
            }

            var parser = new AlipayJsonParser <T>();
            var item   = ParseRespItem(request, body, parser, options.EncyptKey, options.EncyptType);
            var rsp    = parser.Parse(item.RealContent);

            await CheckResponseCertSignAsync(request, item.RespContent, rsp.IsError, parser, options);

            return(rsp);
        }
        public async Task <T> ExecuteAsync <T>(IAlipayRequest <T> request, AlipayOptions options, string accessToken, string appAuthToken) where T : AlipayResponse
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            if (string.IsNullOrEmpty(options.AppId))
            {
                throw new AlipayException("options.AppId is Empty!");
            }

            if (string.IsNullOrEmpty(options.SignType))
            {
                throw new AlipayException("options.SignType is Empty!");
            }

            if (string.IsNullOrEmpty(options.AppPrivateKey))
            {
                throw new AlipayException("options.AppPrivateKey is Empty!");
            }

            if (string.IsNullOrEmpty(options.ServerUrl))
            {
                throw new AlipayException("options.ServerUrl is Empty!");
            }

            var multiMediaDownloadRequest = (AlipayMobilePublicMultiMediaDownloadRequest)request;

            var apiVersion = string.IsNullOrEmpty(request.GetApiVersion()) ? options.Version : request.GetApiVersion();

            // 添加协议级请求参数
            var txtParams = new AlipayDictionary(request.GetParameters())
            {
                { AlipayConstants.METHOD, request.GetApiName() },
                { AlipayConstants.VERSION, apiVersion },
                { AlipayConstants.APP_ID, options.AppId },
                { AlipayConstants.FORMAT, options.Format },
                { AlipayConstants.TIMESTAMP, DateTime.Now },
                { AlipayConstants.ACCESS_TOKEN, accessToken },
                { AlipayConstants.APP_AUTH_TOKEN, appAuthToken },
                { AlipayConstants.SIGN_TYPE, options.SignType },
                { AlipayConstants.TERMINAL_TYPE, request.GetTerminalType() },
                { AlipayConstants.TERMINAL_INFO, request.GetTerminalInfo() },
                { AlipayConstants.PROD_CODE, request.GetProdCode() }
            };

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

            txtParams.Add(AlipayConstants.SIGN, AlipaySignature.RSASignContent(signContent, options.AppPrivateKey, options.SignType));

            var url = options.ServerUrl;

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

            var client = _httpClientFactory.CreateClient(nameof(AlipayMobilePublicMultiMediaClient));

            T   response = null;
            var rsp      = await client.GetAsync(url);

            if (rsp.StatusCode == HttpStatusCode.OK)
            {
                if (rsp.Content.Headers.ContentType.ToString().ToLower().Contains("text/plain"))
                {
                    var body = await rsp.Content.ReadAsStringAsync();

                    var tp = new AlipayJsonParser <T>();
                    response = tp.Parse(body);
                }
                else
                {
                    multiMediaDownloadRequest.Stream = await rsp.Content.ReadAsStreamAsync();

                    response = Activator.CreateInstance <T>();
                }
            }

            return(response);
        }
Пример #15
0
        protected void Page_Load(object sender, EventArgs e)
        {
            WebApiConfig.log.Info(Request.RawUrl);
            SortedDictionary <string, string> sPara = GetRequestGet();

            if (sPara.Count > 0)//判断是否有带返回参数
            {
                Notify aliNotify = new Notify();
                //bool verifyResult = aliNotify.Verify(sPara, Request.QueryString["notify_id"], Request.QueryString["sign"]);

                string sign = sPara["sign"];

                sPara.Remove("sign");
                sPara.Remove("sign_type");
                string signContent  = AlipaySignature.GetSignContent(sPara);
                var    verifyResult = AlipaySignature.RSACheckContent(signContent, sign, ConfigurationManager.AppSettings["alipay.publicKey"], Request.QueryString["charset"], "RSA", false);
                if (verifyResult)//验证成功
                {
                    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
                    //请在这里加上商户的业务逻辑程序代码


                    //——请根据您的业务逻辑来编写程序(以下代码仅作参考)——
                    //获取支付宝的通知返回参数,可参考技术文档中页面跳转同步通知参数列表

                    //商户订单号

                    string out_trade_no = Request.QueryString["out_trade_no"];

                    //支付宝交易号

                    string trade_no = Request.QueryString["trade_no"];

                    //交易状态
                    string  trade_status = Request.QueryString["trade_status"] ?? string.Empty;
                    JObject localResult;
                    int     resultCode;
                    if (Request.QueryString["trade_status"] == "TRADE_FINISHED")
                    {
                        //判断该笔订单是否在商户网站中已经做过处理
                        //如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序
                        //如果有做过处理,不执行商户的业务程序
                        WebApiConfig.log.Info(out_trade_no + "-" + trade_no + "支付宝返回订单完成");
                        if (!TradeBusiness.UpdateTradeStatusSeveralTimes(out_trade_no, trade_no, PaymentType.Alipay, trade_status, TradeStatus.RETURNFINISHED, out localResult))
                        {
                            WebApiConfig.log.Error(out_trade_no + "-" + trade_no + "支付宝返回订单完成,本地数据库状态维护失败");
                        }

                        resultCode = (int)TradeStatus.RETURNFINISHED;
                    }
                    else if (Request.QueryString["trade_status"] == "TRADE_SUCCESS")
                    {
                        WebApiConfig.log.Info(out_trade_no + "-" + trade_no + "支付宝返回订单支付成功");
                        if (!TradeBusiness.UpdateTradeStatusSeveralTimes(out_trade_no, trade_no, PaymentType.Alipay, trade_status, TradeStatus.RETURNSUCCESS, out localResult))
                        {
                            WebApiConfig.log.Error(out_trade_no + "-" + trade_no + "支付宝返回订单支付成功,本地数据库状态维护失败");
                        }

                        resultCode = (int)TradeStatus.RETURNSUCCESS;
                    }
                    else
                    {
                        WebApiConfig.log.Error(out_trade_no + "-" + trade_no + "支付宝沒有返回订单支付結果");
                        // ? 新接口return 沒有trade_status
                        //TradeBusiness.UpdateTradeStatusSeveralTimes(out_trade_no, trade_no, PaymentType.Alipay, trade_status, TradeStatus.RETURNISSUE, out localResult);
                        //resultCode = (int)TradeStatus.RETURNISSUE;
                        TradeBusiness.UpdateTradeStatusSeveralTimes(out_trade_no, trade_no, PaymentType.Alipay, trade_status, TradeStatus.RETURNISSUE, out localResult);
                        resultCode = (int)TradeStatus.RETURNSUCCESS;
                    }

                    var returnUrl = localResult.GetValue("ReturnUrl") == null ? string.Empty : localResult.GetValue("ReturnUrl").ToString();
                    if (string.IsNullOrEmpty(returnUrl))
                    {
                        //打印页面
                        Response.Write(out_trade_no + "订单处理完毕");
                    }
                    else
                    {
                        var fee = localResult.GetValue("Fee").ToString();
                        Response.Clear();
                        Response.Write("<script>top.postMessage('{\"url\":\"" + string.Format("{0}?result={1}&tradeNo={2}&fee={3}\"", returnUrl, resultCode, out_trade_no, fee) + "}', '*');</script>");
                        Response.End();
                    }

                    //——请根据您的业务逻辑来编写程序(以上代码仅作参考)——
                    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
                }
                else//验证失败
                {
                    WebApiConfig.log.Error("支付宝返回结果验证失败");
                    Response.Write("支付宝返回结果验证失败");
                }
            }
            else
            {
                WebApiConfig.log.Error("支付宝返回结果无返回参数");
                Response.Write("支付宝返回结果无返回参数");
            }
        }
Пример #16
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);
        }
Пример #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, 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?.LogTrace(0, "Request Url:{body}", body);
                }
                else
                {
                    //输出post表单
                    body = BuildHtmlRequest(txtParams, reqMethod);
                    Logger?.LogTrace(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);
        }
Пример #18
0
        protected void Page_Load(object sender, EventArgs e)
        {
            WxPayAPI.Log.Info(this.GetType().ToString(), "--异步回调处理开始--");
            Dictionary <string, string> data = GetRequestPost();
            string notify_id    = Request.Form["notify_id"]; //获取notify_id
            string sign         = Request.Form["sign"];      //获取sign
            string SerialNo     = Request.Form["out_trade_no"];
            string TradeNo      = Request.Form["trade_no"];
            string price        = Request.Form["buyer_pay_amount"];
            string trade_status = Request.Form["trade_status"];
            string gmt_payment  = Request.Form["notify_time"];

            WxPayAPI.Log.Info("Form:", AlipaySignature.GetSignContent(data));
            if (notify_id == null || notify_id == "")
            {
                WxPayAPI.Log.Info("", "参数错误");
                return;
            }
            Notify aliNotify = new Notify();

            if (aliNotify.GetResponseTxt(notify_id) != "true")
            {
                WxPayAPI.Log.Info("", "参数错误");
                return;
            }
            WxPayAPI.Log.Info("订单号:", SerialNo);
            bool flag = aliNotify.GetSignVeryfy(data, sign);     //AlipaySignature.RSACheckV1(sPara, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, "RSA", false);

            // bool checkSign = AlipaySignature.RSACheckV2(data, AlipayConfig.ALIPAY_PUBLIC_KEY);
            if (flag)
            {
                WxPayAPI.Log.Info("", "验签成功");
                _database = new Database("ecard");
                using (var _databaseInstance = new DatabaseInstance(_database))
                {
                    var sql  = "select * from fz_Orders where orderNo=@orderNo";
                    var item = new QueryObject <Ecard.Models.Order>(_databaseInstance, sql, new { orderNo = SerialNo }).FirstOrDefault();
                    if (item != null)
                    {
                        if (item.payState == Ecard.Models.PayStates.non_payment && item.orderState == Ecard.Models.OrderStates.awaitPay)
                        {
                            WxPayAPI.Log.Info("payAmount", item.payAmount.ToString());
                            WxPayAPI.Log.Info("price", price);
                            decimal amount = 0;
                            decimal.TryParse(price, out amount);
                            WxPayAPI.Log.Info("amount", amount.ToString());
                            if (item.payAmount == amount)
                            {
                                WxPayAPI.Log.Info("金额", "成功");
                                _databaseInstance.BeginTransaction();
                                item.payState   = Ecard.Models.PayStates.paid;
                                item.orderState = Ecard.Models.OrderStates.paid;
                                item.payType    = PayTypes.Alipay;
                                item.submitTime = DateTime.Now;
                                _databaseInstance.Update(item, "fz_Orders");



                                var sql2  = "select * from fz_Accounts where accountId=@accountId";
                                var item2 = new QueryObject <Ecard.Models.Account>(_databaseInstance, sql2, new { accountId = item.userId }).FirstOrDefault();
                                if (item2 != null)
                                {
                                    if (!string.IsNullOrWhiteSpace(item2.openID))
                                    {
                                        var message = new Fz_Messages();
                                        message.accountId  = item2.accountId;
                                        message.openId     = item2.openID;
                                        message.state      = MessagesState.staySend;
                                        message.submitTime = DateTime.Now;
                                        message.keyword1   = item.orderNo;
                                        message.keyword2   = "已付款";
                                        message.msgType    = MsgType.orderState;
                                        _databaseInstance.Insert(message, "Fz_Messages");
                                    }
                                }

                                _databaseInstance.Commit();
                            }
                        }
                    }
                }
                WxPayAPI.Log.Info("交易", "成功");
                //交易成功
                Response.Write("success");
            }
            else
            {
                WxPayAPI.Log.Info("", "验签失败");
            }
        }
Пример #19
0
        public BaseResult AliPay(AliPayModel aliModel)
        {
            BaseResult br = new BaseResult();

            try
            {
                #region 构建支付宝调用数据
                var paramters = new Dictionary <string, string>();
                paramters.Add("app_id", aliModel.app_id);       //开发者帐号
                paramters.Add("method", aliModel.method);       //接口名称
                paramters.Add("charset", aliModel.charset);     //请求使用的编码格式,如utf - 8,gbk,gb2312等
                paramters.Add("sign_type", aliModel.sign_type); //商户生成签名字符串所使用的签名算法类型,目前支持RSA
                paramters.Add("timestamp", aliModel.timestamp); //发送请求的时间,格式"yyyy-MM-dd HH:mm:ss"
                paramters.Add("version", aliModel.version);     //调用的接口版本,固定为:1.0

                if (string.IsNullOrEmpty(aliModel.store_id))
                {
                    aliModel.store_id = "-999";
                }

                string bizContent = "{" +
                                    "    \"out_trade_no\":\"" + aliModel.out_trade_no + "\"," +
                                    "    \"scene\":\"" + aliModel.scene + "\"," +
                                    "    \"auth_code\":\"" + aliModel.auth_code + "\"," +
                                    "    \"total_amount\":" + aliModel.total_amount + "," +
                                    "    \"subject\":\"" + aliModel.subject + "\"," +
                                    "    \"store_id\":\"" + aliModel.store_id + "\"" +
                                    " }";
                bizContent = bizContent.Trim();
                paramters.Add("biz_content", bizContent);

                string mySign = AlipaySignature.RSASign(paramters, aliModel.sign, "utf-8", false, "RSA");//生成签名 其中aliModel.sign为定义的私钥值
                paramters.Add("sign", mySign);

                #endregion
                #region 构建调用内部接口数据
                var dataContent = AlipaySignature.GetSignContent(paramters);
                paramters.Clear();
                //paramters.Add("data",   dataContent);
                var eData = HttpUtility.UrlEncode(dataContent, Encoding.UTF8);
                paramters.Add("data", dataContent);
                string myNewSign = CYUtils.SignRequestNew(paramters, PublicSign.localKey);
                paramters.Add("sign", myNewSign);
                paramters.Remove("data");
                paramters.Add("data", eData);
                paramters.Add("amount", aliModel.total_amount.ToString());

                #endregion

                var result = new WebUtils().DoPost(PublicSign.aliPayUrl, paramters, 200000);
                AliPayResultModel retPayModel = Utility.JSON.Deserialize <AliPayResultModel>(result);
                if (retPayModel.alipay_trade_pay_response.code == "10000" && retPayModel.alipay_trade_pay_response.msg == "Success")
                {
                    retPayModel.out_trade_no = retPayModel.alipay_trade_pay_response.out_trade_no;
                    retPayModel.trade_no     = retPayModel.alipay_trade_pay_response.trade_no;
                    br.Success = true;
                    br.Data    = retPayModel;
                    return(br);
                }
                else
                {
                    if (retPayModel.alipay_trade_pay_response.sub_code == "ACQ.TRADE_HAS_SUCCESS")
                    {
                        br.Success = true;
                        br.Message.Add(string.Format("订单已被支付 描述:" + retPayModel.alipay_trade_pay_response.sub_msg));
                        retPayModel.out_trade_no = retPayModel.alipay_trade_pay_response.out_trade_no;
                        retPayModel.trade_no     = retPayModel.alipay_trade_pay_response.trade_no;
                        br.Success = true;
                        br.Data    = retPayModel;
                        return(br);
                    }
                    else if (retPayModel.alipay_trade_pay_response.sub_code == "ACQ.SYSTEM_ERROR")
                    {
                        br.Success = false;
                        br.Message.Add(string.Format("支付宝异常接口返回错误 需要查询订单结果 描述:" + retPayModel.alipay_trade_pay_response.sub_msg));
                        br.Level = ErrorLevel.Warning;
                        return(br);
                    }
                    else if (retPayModel.alipay_trade_pay_response.sub_code == "ACQ.USER_FACE_PAYMENT_SWITCH_OFF")
                    {
                        br.Success = false;
                        br.Message.Add(string.Format("用户当面付付款开关关闭 需要让用户在手机上打开当面付付款开关 描述:" + retPayModel.alipay_trade_pay_response.sub_msg));
                        br.Level = ErrorLevel.Warning;
                        return(br);
                    }
                    else
                    {
                        br.Success = false;
                        br.Message.Add(string.Format("支付宝支付 操作返回失败! 描述:" + retPayModel.alipay_trade_pay_response.sub_msg));
                        return(br);
                    }
                }
            }
            catch (Exception ex)
            {
                br.Success = false;
                br.Message.Add(string.Format("支付宝支付时发生异常 单号:" + aliModel.out_trade_no + " 请查询确定结果 以免带来损失!"));
                br.Level = ErrorLevel.Warning;
                return(br);
            }
        }
Пример #20
0
        public async Task <IActionResult> Gateway()
        {
            try
            {
                var service = Request.Form["service"].ToString();
                switch (service)
                {
                // 激活开发者模式
                case "alipay.service.check":
                {
                    var options = _optionsAccessor.Value;

                    // 获取参数
                    var parameters = _client.GetParameters(Request);
                    var sign       = parameters["sign"];
                    parameters.Remove("sign");

                    var signContent = AlipaySignature.GetSignContent(parameters);

                    // 验签
                    var isSuccess = AlipaySignature.RSACheckContent(signContent, sign, options.AlipayPublicKey, "GBK", options.SignType);

                    // 组XML响应内容
                    var response = MakeVerifyGWResponse(isSuccess, options.AlipayPublicKey, options.AppPrivateKey, "GBK", options.SignType);

                    return(Content(response, "text/xml"));
                }
                }

                var msg_method = Request.Form["msg_method"].ToString();
                switch (msg_method)
                {
                // 资金单据状态变更通知
                case "alipay.fund.trans.order.changed":
                {
                    var notify = await _client.CertificateExecuteAsync <AlipayFundTransOrderChangedNotify>(Request, _optionsAccessor.Value);

                    return(AlipayNotifyResult.Success);
                }

                // 第三方应用授权取消消息
                case "alipay.open.auth.appauth.cancelled":
                {
                    var notify = await _client.CertificateExecuteAsync <AlipayOpenAuthAppauthCancelledNotify>(Request, _optionsAccessor.Value);

                    return(AlipayNotifyResult.Success);
                }

                // 用户授权取消消息
                case "alipay.open.auth.userauth.cancelled":
                {
                    var notify = await _client.CertificateExecuteAsync <AlipayOpenAuthUserauthCancelledNotify>(Request, _optionsAccessor.Value);

                    return(AlipayNotifyResult.Success);
                }

                // 小程序审核通过通知
                case "alipay.open.mini.version.audit.passed":
                {
                    var notify = await _client.CertificateExecuteAsync <AlipayOpenMiniVersionAuditPassedNotify>(Request, _optionsAccessor.Value);

                    return(AlipayNotifyResult.Success);
                }

                // 用户授权取消消息
                case "alipay.open.mini.version.audit.rejected":
                {
                    var notify = await _client.CertificateExecuteAsync <AlipayOpenMiniVersionAuditRejectedNotify>(Request, _optionsAccessor.Value);

                    return(AlipayNotifyResult.Success);
                }

                // 收单资金结算到银行账户,结算退票的异步通知
                case "alipay.trade.settle.dishonoured":
                {
                    var notify = await _client.CertificateExecuteAsync <AlipayTradeSettleDishonouredNotify>(Request, _optionsAccessor.Value);

                    return(AlipayNotifyResult.Success);
                }

                // 收单资金结算到银行账户,结算失败的异步通知
                case "alipay.trade.settle.fail":
                {
                    var notify = await _client.CertificateExecuteAsync <AlipayTradeSettleFailNotify>(Request, _optionsAccessor.Value);

                    return(AlipayNotifyResult.Success);
                }

                // 收单资金结算到银行账户,结算成功的异步通知
                case "alipay.trade.settle.success":
                {
                    var notify = await _client.CertificateExecuteAsync <AlipayTradeSettleSuccessNotify>(Request, _optionsAccessor.Value);

                    return(AlipayNotifyResult.Success);
                }
                }

                return(NoContent());
            }
            catch
            {
                return(NoContent());
            }
        }
Пример #21
0
        protected void Page_Load(object sender, EventArgs e)
        {
            SortedDictionary <string, string> sPara = GetRequestPost();

            if (sPara.Count > 0)//判断是否有带返回参数
            {
                var str = string.Empty;
                foreach (var item in sPara)
                {
                    str += string.Format("{0}:{1},", item.Key, item.Value);
                }

                WebApiConfig.log.Info(str);

                Notify aliNotify = new Notify();
                //bool verifyResult = aliNotify.Verify(sPara, Request.Form["notify_id"], Request.Form["sign"]);
                string sign = sPara["sign"];
                sPara.Remove("sign");
                sPara.Remove("sign_type");
                string signContent  = AlipaySignature.GetSignContent(sPara);
                var    verifyResult = AlipaySignature.RSACheckContent(signContent, sign, ConfigurationManager.AppSettings["alipay.publicKey"], Request.QueryString["charset"], "RSA", false);
                if (verifyResult)//验证成功
                {
                    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
                    //请在这里加上商户的业务逻辑程序代码


                    //——请根据您的业务逻辑来编写程序(以下代码仅作参考)——
                    //获取支付宝的通知返回参数,可参考技术文档中服务器异步通知参数列表

                    //商户订单号

                    string out_trade_no = Request.Form["out_trade_no"];

                    //支付宝交易号

                    string trade_no = Request.Form["trade_no"];

                    //交易状态
                    string  trade_status = Request.Form["trade_status"];
                    JObject localResult;
                    int     resultCode;
                    if (Request.Form["trade_status"] == "TRADE_FINISHED")
                    {
                        //判断该笔订单是否在商户网站中已经做过处理
                        //如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序
                        //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
                        //如果有做过处理,不执行商户的业务程序

                        //注意:
                        //退款日期超过可退款期限后(如三个月可退款),支付宝系统发送该交易状态通知
                        WebApiConfig.log.Info(out_trade_no + "-" + trade_no + "支付宝通知订单完成");
                        if (!TradeBusiness.UpdateTradeStatusSeveralTimes(out_trade_no, trade_no, PaymentType.Alipay, trade_status, TradeStatus.NOTIFYFINISHED, out localResult))
                        {
                            WebApiConfig.log.Error(out_trade_no + "-" + trade_no + "支付宝通知订单完成,本地数据库状态维护失败");
                        }

                        resultCode = (int)TradeStatus.NOTIFYFINISHED;
                    }
                    else if (Request.Form["trade_status"] == "TRADE_SUCCESS")
                    {
                        //判断该笔订单是否在商户网站中已经做过处理
                        //如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序
                        //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
                        //如果有做过处理,不执行商户的业务程序

                        //注意:
                        //付款完成后,支付宝系统发送该交易状态通知
                        WebApiConfig.log.Info(out_trade_no + "-" + trade_no + "支付宝通知订单支付成功");
                        if (!TradeBusiness.UpdateTradeStatusSeveralTimes(out_trade_no, trade_no, PaymentType.Alipay, trade_status, TradeStatus.NOTIFYSUCCESS, out localResult))
                        {
                            WebApiConfig.log.Error(out_trade_no + "-" + trade_no + "支付宝通知订单支付成功,本地数据库状态维护失败");
                        }

                        resultCode = (int)TradeStatus.NOTIFYSUCCESS;
                    }
                    else
                    {
                        TradeBusiness.UpdateTradeStatusSeveralTimes(out_trade_no, trade_no, PaymentType.Alipay, trade_status, TradeStatus.NOTIFYISSUE, out localResult);
                        WebApiConfig.log.Error(out_trade_no + "-" + trade_no + "支付宝通知失败");
                        resultCode = (int)TradeStatus.NOTIFYISSUE;
                    }

                    // 通知患者端
                    PatientCustomerBusiness.NotifyPatient(localResult);
                    Response.Clear();
                    Response.Write("success");
                    Response.End();
                    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
                }
                else//验证失败
                {
                    WebApiConfig.log.Error("支付宝通知验证失败");
                    Response.Write("支付宝通知验证失败");
                }
            }
            else
            {
                WebApiConfig.log.Error("支付宝无通知参数");
                Response.Write("支付宝无通知参数");
            }
        }