예제 #1
0
        private void CheckResponseSign <T>(IAlipayRequest <T> request, string responseBody, bool isError, IAlipayParser <T> parser, AlipayOptions options) where T : AlipayResponse
        {
            var signItem = parser.GetSignItem(request, responseBody);

            if (signItem == null)
            {
                throw new AlipayException("sign check fail: Body is Empty!");
            }

            if (!isError || isError && !string.IsNullOrEmpty(signItem.Sign))
            {
                var rsaCheckContent = AlipaySignature.RSACheckContent(signItem.SignSourceDate, signItem.Sign, options.AlipayPublicKey, options.SignType);
                if (!rsaCheckContent)
                {
                    if (!string.IsNullOrEmpty(signItem.SignSourceDate) && signItem.SignSourceDate.Contains("\\/"))
                    {
                        var srouceData = signItem.SignSourceDate.Replace("\\/", "/");
                        var jsonCheck  = AlipaySignature.RSACheckContent(srouceData, signItem.Sign, options.AlipayPublicKey, options.SignType);
                        if (!jsonCheck)
                        {
                            throw new AlipayException("sign check fail: check Sign and Data Fail JSON also");
                        }
                    }
                    else
                    {
                        throw new AlipayException("sign check fail: check Sign and Data Fail!");
                    }
                }
            }
        }
        public static void CheckResponseSign <T>(IAopRequest <T> request, string responseBody, bool isError, IAopParser <T> parser, string alipayPublicKey, string charset, string signType, bool keyFromFile) where T : AopResponse
        {
            if (string.IsNullOrEmpty(alipayPublicKey) || string.IsNullOrEmpty(charset))
            {
                return;
            }
            SignItem signItem = parser.GetSignItem(request, responseBody);

            if (signItem == null)
            {
                throw new AopException("sign check fail: Body is Empty!");
            }
            if ((!isError || (isError && !string.IsNullOrEmpty(signItem.Sign))) && !AlipaySignature.RSACheckContent(signItem.SignSourceDate, signItem.Sign, alipayPublicKey, charset, signType, keyFromFile))
            {
                if (string.IsNullOrEmpty(signItem.SignSourceDate) || !signItem.SignSourceDate.Contains("\\/"))
                {
                    throw new AopException("sign check fail: check Sign and Data Fail!");
                }
                string signContent = signItem.SignSourceDate.Replace("\\/", "/");
                if (!AlipaySignature.RSACheckContent(signContent, signItem.Sign, alipayPublicKey, charset, signType, keyFromFile))
                {
                    throw new AopException("sign check fail: check Sign and Data Fail JSON also");
                }
            }
        }
예제 #3
0
        private void CheckNotifySign(IDictionary <string, string> parameters, RSAParameters publicRSAParameters, string signType)
        {
            try
            {
                logger?.LogDebug($"{DateTime.Now} 支付宝回调CheckNotifySign");

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

                if (!parameters.TryGetValue("sign", out var sign))
                {
                    throw new Exception("sign check fail: sign is Empty!");
                }

                var prestr = GetSignContent(parameters);
                if (!AlipaySignature.RSACheckContent(prestr, sign, publicRSAParameters, signType))
                {
                    throw new Exception("sign check fail: check Sign Data Fail!");
                }
            }
            catch (Exception ex)
            {
                logger?.LogError($"{DateTime.Now} 支付宝回调CheckNotifySign报错", ex.Message);
            }
        }
예제 #4
0
        /// <summary>
        /// 获取返回时的签名验证结果
        /// </summary>
        /// <param name="inputPara">通知返回参数数组</param>
        /// <param name="sign">对比的签名结果</param>
        /// <returns>签名验证结果</returns>
        private bool GetSignVeryfy(SortedDictionary <string, string> inputPara, string sign)
        {
            Dictionary <string, string> sPara = new Dictionary <string, string>();

            //过滤空值、sign与sign_type参数
            sPara = Core.FilterPara(inputPara);

            //获取待签名字符串
            string preSignStr = Core.CreateLinkString(sPara);

            //获得签名验证结果
            bool isSign = false;

            if (sign != null && sign != "")
            {
                switch (_sign_type)
                {
                //isSgin = AlipayMD5.Verify(preSignStr, sign, _key, charset);

                case "RSA":
                    isSign = AlipaySignature.RSACheckContent(preSignStr, sign, Config.alipay_public_key, _charset);
                    break;

                default:
                    break;
                }
            }

            return(isSign);
        }
예제 #5
0
        public void Check()
        {
            string publickey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDIgHnOn7LLILlKETd6BFRJ0GqgS2Y3mn1wMQmyh9zEyWlz5p1zrahRahbXAfCfSqshSNfqOmAQzSHRVjCqjsAw1jyqrXaPdKBmr90DIpIxmIyKXv4GGAkPyJ/6FTFY99uhpiq0qadD/uSzQsefWo0aTvP/65zi3eof7TcZ32oWpwIDAQAB";

            string sign = "jKRnSXLbf1d+KSv8xIWO3gDRUKcmOemLt0laeIZDelZqETRa/bGlmqFQmt/CF2sRxuXHqZx3Gs5MG+X3dFCUp+ypm5dRlvmKqEi/Pz0XV2/E7eva42gltNx76i2MPA83SlB7zS+N+0ZkARLok4KRofHl72vtGIWCxCZFJhHIlsE=";

            string signcontent = "app_id=2016092600603929&body=phone&buyer_id=2088102169336131&gmt_create=2016-10-30 17:50:12&gmt_payment=2016-10-30 17:50:13&notify_id=f3690a28885f22b325723e5f6bc6df4h06&notify_time=2016-10-30 17:50:13&notify_type=trade_status_sync&out_trade_no=2016102912137&seller_id=2088102177423285&subject=phone8&total_amount=20.21&trade_no=2016103021001004130200039530&trade_status=TRADE_SUCCESS";

            bool istrue = AlipaySignature.RSACheckContent(signcontent, sign, publickey, "utf-8", "RSA", false);

            Assert.IsTrue(istrue);
        }
예제 #6
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));
        }
예제 #7
0
        /// <summary>
        /// 获取返回时的签名验证结果
        /// </summary>
        /// <param name="inputPara">通知返回参数数组</param>
        /// <returns>签名验证结果</returns>
        bool GetSignVeryfy(SortedDictionary <string, string> inputPara)
        {
            var sign  = ValidateSign(inputPara["sign"]);
            var sPara = FilterPara(inputPara);
            //获取待签名字符串
            var preSignStr = CreateLinkString(inputPara);
            //获得签名验证结果
            var isSign = false;

            if (!string.IsNullOrEmpty(sign))
            {
                isSign = AlipaySignature.RSACheckContent(preSignStr, sign, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type, true);
            }
            return(isSign);
        }
예제 #8
0
        public static bool GetSynYanQian(bool isget)
        {
            ALIPAY_PUBLIC_KEY = GetCurrentPathByAbs() + "rsa_alipay_public_key.pem";

            string str      = "";
            string sign     = "";
            string signtype = "RSA";//签名类型

            string[] allkeys;
            if (isget)
            {
                allkeys = HttpContext.Current.Request.QueryString.AllKeys;
            }
            else
            {
                allkeys = HttpContext.Current.Request.Form.AllKeys;
            }
            Dictionary <string, string> dic = new Dictionary <string, string>();

            foreach (var item in allkeys)
            {
                if (item != "sign" & item != "sign_type")
                {
                    dic.Add(item, HttpContext.Current.Request[item]);
                }
                if (item == "sign")
                {
                    sign = HttpContext.Current.Request[item];
                }
                else if (item == "sign_type")
                {
                    signtype = HttpContext.Current.Request[item];
                }
            }

            var newdic = dic.OrderBy(u => u.Key);

            foreach (var item in newdic)
            {
                str = str + item.Key + "=" + item.Value + "&";
            }
            str = str.Substring(0, str.Length - 1);
            return(AlipaySignature.RSACheckContent(str, sign, ALIPAY_PUBLIC_KEY, "utf-8", signtype, true));
        }
예제 #9
0
        private 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("sign", out var sign))
            {
                throw new AlipayException("sign check fail: sign is Empty!");
            }

            var prestr = GetSignContent(dictionary);

            if (!AlipaySignature.RSACheckContent(prestr, sign, options.AlipayPublicKey, options.SignType))
            {
                throw new AlipayException("sign check fail: check Sign Data Fail!");
            }
        }
예제 #10
0
        public static String GetSign(Dictionary <String, String> map)
        {
            string query_string = GetOrderParam(map);
            //string query_string = "app_id=2015052600090779&biz_content={\"timeout_express\":\"30m\",\"seller_id\":\"\",\"product_code\":\"QUICK_MSECURITY_PAY\",\"total_amount\":\"0.01\",\"subject\":\"1\",\"body\":\"test2\",\"out_trade_no\":\"IQJZSRC1YMQB5HU\"}&charset=utf-8&format=json&method=alipay.trade.app.pay&notify_url=http://domain.merchant.com/payment_notify&sign_type=RSA2&timestamp=2017-1-10 17:58:01&version=1.0";
            // string s = RSAFromPkcs8.sign(query_string, map["pri_key"], "UTF-8");

            //   string query_string = AlipaySignature.GetSignContent(map);



            string sign = AlipaySignature.RSASignCharSet(query_string, map["pri_key"], "UTF-8", false, "RSA");


            bool isd = AlipaySignature.RSACheckContent(query_string, sign, "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC3Sz3pHsjBUFPrnWhps2ksCfdrkxw7yBRasR1iqGyq95HUG0RzZVwwE4DhBCDZb/1/hAchRC8wdJtPttVrGSGIqwRFG7x/srvKtMRcBwQsK0z87rqJxeew3jHB7RDvq8xVKAHFfd9MCyohU9W/Ngz2PeiNsd+fVLU/nsFciCdqkwIDAQAB", "UTF-8", "RSA", false);



            return(sign);
        }
예제 #11
0
        private void CheckNotifySign(IDictionary <string, string> para, RSAParameters parameters, string signType)
        {
            if (para.Count == 0)
            {
                throw new AlipayException("sign check fail: content is Empty!");
            }

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

            var prestr = GetSignContent(para);

            if (!AlipaySignature.RSACheckContent(prestr, sign, parameters, signType))
            {
                throw new AlipayException("sign check fail: check Sign and Data Fail JSON also");
            }
        }
        private void CheckNotifySign(IDictionary <string, string> parameters, RSAParameters publicRSAParameters, string signType)
        {
            if (parameters == null || parameters.Count == 0)
            {
                throw new Exception("sign check fail: content is Empty!");
            }

            if (!parameters.TryGetValue("sign", out var sign))
            {
                throw new Exception("sign check fail: sign is Empty!");
            }

            var prestr = GetSignContent(parameters);

            if (!AlipaySignature.RSACheckContent(prestr, sign, publicRSAParameters, signType))
            {
                throw new Exception("sign check fail: check Sign Data Fail!");
            }
        }
예제 #13
0
        public static void CheckResponseSign <T>(IAopRequest <T> request, string responseBody, bool isError,
                                                 IAopParser <T> parser, string alipayPublicKey, string charset, string signType) where T : AopResponse
        {
            if (string.IsNullOrEmpty(alipayPublicKey) || string.IsNullOrEmpty(charset))
            {
                return;
            }

            var signItem = parser.GetSignItem(request, responseBody);

            if (signItem == null)
            {
                throw new AopException("sign check fail: Body is Empty!");
            }

            if (!isError ||
                isError && !string.IsNullOrEmpty(signItem.Sign))
            {
                var rsaCheckContent = AlipaySignature.RSACheckContent(signItem.SignSourceDate, signItem.Sign,
                                                                      alipayPublicKey, charset, signType);
                if (!rsaCheckContent)
                {
                    if (!string.IsNullOrEmpty(signItem.SignSourceDate) && signItem.SignSourceDate.Contains("\\/"))
                    {
                        var srouceData = signItem.SignSourceDate.Replace("\\/", "/");
                        var jsonCheck  = AlipaySignature.RSACheckContent(srouceData, signItem.Sign, alipayPublicKey,
                                                                         charset, signType);
                        if (!jsonCheck)
                        {
                            throw new AopException(
                                      "sign check fail: check Sign and Data Fail JSON also");
                        }
                    }
                    else
                    {
                        throw new AopException(
                                  "sign check fail: check Sign and Data Fail!");
                    }
                }
            }
        }
예제 #14
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!");
            }
        }
예제 #15
0
        private void CheckNotifySign(IDictionary <string, string> content, RSAParameters parameters, string signType)
        {
            if (content.Count == 0)
            {
                throw new AlipayException("sign check fail: Body is Empty!");
            }

            var sign = content["sign"];

            if (string.IsNullOrEmpty(sign))
            {
                throw new AlipayException("sign check fail: sign is Empty!");
            }

            var prestr = GetSignContent(content);

            if (!AlipaySignature.RSACheckContent(prestr, sign, parameters, signType))
            {
                throw new AlipayException("sign check fail: check Sign and Data Fail JSON also");
            }
        }
예제 #16
0
        private void CheckResponseSign <T>(IAlipayRequest <T> request, string responseBody, bool isError, IAlipayParser <T> parser, RSAParameters parameters, string signType) where T : AlipayResponse
        {
            try
            {
                logger?.LogDebug($"{DateTime.Now} 支付宝CheckResponseSign");

                var signItem = parser.GetSignItem(request, responseBody);
                if (signItem == null)
                {
                    throw new Exception("sign check fail: Body is Empty!");
                }

                if (!isError || (isError && !string.IsNullOrEmpty(signItem.Sign)))
                {
                    var rsaCheckContent = AlipaySignature.RSACheckContent(signItem.SignSourceDate, signItem.Sign, parameters, signType);
                    if (!rsaCheckContent)
                    {
                        if (!string.IsNullOrEmpty(signItem.SignSourceDate) && signItem.SignSourceDate.Contains("\\/"))
                        {
                            var srouceData = signItem.SignSourceDate.Replace("\\/", "/");
                            var jsonCheck  = AlipaySignature.RSACheckContent(srouceData, signItem.Sign, parameters, signType);
                            if (!jsonCheck)
                            {
                                throw new Exception("sign check fail: check Sign and Data Fail JSON also");
                            }
                        }
                        else
                        {
                            throw new Exception("sign check fail: check Sign and Data Fail!");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger?.LogError($"{DateTime.Now} 支付宝CheckResponseSign报错", ex.Message);
            }
        }
예제 #17
0
        private async Task CheckResponseCertSignAsync <T>(IAlipayRequest <T> request, string responseBody, bool isError, IAlipayParser <T> parser, AlipayOptions options) where T : AlipayResponse
        {
            if (request is AlipayOpenAppAlipaycertDownloadRequest)
            {
                return;
            }

            var certItem = parser.GetCertItem(request, responseBody);

            if (certItem == null)
            {
                throw new AlipayException("sign check fail: Body is Empty!");
            }

            if (!isError || isError && !string.IsNullOrEmpty(certItem.Sign))
            {
                var currentAlipayPublicKey = await LoadAlipayPublicKeyAsync(certItem, options);

                var rsaCheckContent = AlipaySignature.RSACheckContent(certItem.SignSourceDate, certItem.Sign, currentAlipayPublicKey, options.SignType);
                if (!rsaCheckContent)
                {
                    if (!string.IsNullOrEmpty(certItem.SignSourceDate) && certItem.SignSourceDate.Contains("\\/"))
                    {
                        var srouceData = certItem.SignSourceDate.Replace("\\/", "/");
                        var jsonCheck  = AlipaySignature.RSACheckContent(srouceData, certItem.Sign, currentAlipayPublicKey, options.SignType);
                        if (!jsonCheck)
                        {
                            throw new AlipayException("sign check fail: check Sign and Data Fail JSON also");
                        }
                    }
                    else
                    {
                        throw new AlipayException("sign check fail: check Sign and Data Fail!");
                    }
                }
            }
        }
예제 #18
0
        private void CheckResponseCertSign <T>(IAopRequest <T> request, string responseBody, bool isError, IAopParser <T> parser) where T : AopResponse
        {
            if (request.GetApiName().Equals("alipay.open.app.alipaycert.download"))
            {
                return;
            }

            CertItem certItem = parser.GetCertItem(request, responseBody);

            if (certItem == null)
            {
                throw new AopException("sign check fail: Body is Empty!");
            }

            if (!isError || (isError && !string.IsNullOrEmpty(certItem.Sign)))
            {
                String currentAlipayPublicKey = LoadAlipayPublicKey(certItem);

                bool rsaCheckContent = AlipaySignature.RSACheckContent(certItem.SignSourceDate, certItem.Sign, currentAlipayPublicKey, charset, signType, false);
                if (!rsaCheckContent)
                {
                    if (!string.IsNullOrEmpty(certItem.SignSourceDate) && certItem.SignSourceDate.Contains("\\/"))
                    {
                        string sourceData = certItem.SignSourceDate.Replace("\\/", "/");
                        bool   jsonCheck  = AlipaySignature.RSACheckContent(sourceData, certItem.Sign, currentAlipayPublicKey, charset, signType, false);
                        if (!jsonCheck)
                        {
                            throw new AopException("sign check fail: check Sign and Data Fail JSON also");
                        }
                    }
                    else
                    {
                        throw new AopException("sign check fail: check Sign and Data Fail!");
                    }
                }
            }
        }
예제 #19
0
        private async Task CheckResponseCertSignAsync <T>(IAlipayRequest <T> request, string responseBody, bool isError, IAlipayParser <T> parser, AlipayOptions options) where T : AlipayResponse
        {
            var certItem = parser.GetCertItem(request, responseBody);

            if (certItem == null)
            {
                throw new AlipayException("cert check fail: Body is Empty!");
            }

            if (!string.IsNullOrEmpty(certItem.CertSN))
            {
                // 为空时添加本地支付宝公钥证书密钥
                if (_alipayPublicKeyManager.IsEmpty)
                {
                    _alipayPublicKeyManager.TryAdd(options.AlipayPublicCertSN, options.AlipayPublicKey);
                }

                // 如果返回的支付宝公钥证书序列号与本地支付宝公钥证书序列号不匹配,通过返回的支付宝公钥证书序列号去网关拉取新的支付宝公钥证书
                if (!_alipayPublicKeyManager.ContainsKey(certItem.CertSN))
                {
                    var model = new AlipayOpenAppAlipaycertDownloadModel
                    {
                        AlipayCertSn = certItem.CertSN
                    };

                    var req = new AlipayOpenAppAlipaycertDownloadRequest();
                    req.SetBizModel(model);

                    var response = await CertificateExecuteAsync(req, options);

                    if (response.IsError)
                    {
                        throw new AlipayException("支付宝公钥证书校验失败,请确认是否为支付宝签发的有效公钥证书");
                    }

                    if (!AntCertificationUtil.IsTrusted(response.AlipayCertContent, options.RootCert))
                    {
                        throw new AlipayException("支付宝公钥证书校验失败,请确认是否为支付宝签发的有效公钥证书");
                    }

                    var alipayCert          = AntCertificationUtil.ParseCert(response.AlipayCertContent);
                    var alipayCertSN        = AntCertificationUtil.GetCertSN(alipayCert);
                    var alipayCertPublicKey = AntCertificationUtil.ExtractPemPublicKeyFromCert(alipayCert);

                    _alipayPublicKeyManager.TryAdd(alipayCertSN, alipayCertPublicKey);
                }

                // 针对成功结果且有支付宝公钥的进行验签
                if (_alipayPublicKeyManager.TryGetValue(certItem.CertSN, out var alipayPublicKey))
                {
                    if (!isError || isError && !string.IsNullOrEmpty(certItem.Sign))
                    {
                        var rsaCheckContent = AlipaySignature.RSACheckContent(certItem.SignSourceDate, certItem.Sign, alipayPublicKey, options.Charset, options.SignType);
                        if (!rsaCheckContent)
                        {
                            // 针对JSON \/问题,替换/后再尝试做一次验证
                            if (!string.IsNullOrEmpty(certItem.SignSourceDate) && certItem.SignSourceDate.Contains("\\/"))
                            {
                                var srouceData = certItem.SignSourceDate.Replace("\\/", "/");
                                var jsonCheck  = AlipaySignature.RSACheckContent(srouceData, certItem.Sign, alipayPublicKey, options.Charset, options.SignType);
                                if (!jsonCheck)
                                {
                                    throw new AlipayException("cert check fail: check Cert and Data Fail JSON also");
                                }
                            }
                            else
                            {
                                throw new AlipayException("cert check fail: check Cert and Data Fail!");
                            }
                        }
                    }
                }
                else
                {
                    throw new AlipayException("cert check fail: check Cert and Data Fail! CertSN non-existent");
                }
            }
        }
예제 #20
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("支付宝返回结果无返回参数");
            }
        }
예제 #21
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());
            }
        }
예제 #22
0
        private bool Verify(HttpRequestBase request, NameValueCollection requestVal, out AliPayReturnModel model)
        {
            bool result = false;
            SortedDictionary <string, string> sortedDic = new SortedDictionary <string, string>();

            foreach (var item in requestVal.AllKeys)
            {
                if (item.ToLower() != "sign" && item.ToLower() != "sign_type" && !string.IsNullOrEmpty(item))
                {
                    sortedDic.Add(item, requestVal[item]);
                }
            }

            string requestSign     = requestVal["sign"];
            string requestSigntype = requestVal["sign_type"];
            string param           = CreateURLParamString(sortedDic);

            EnumSignType signType = requestSigntype == "MD5" ? EnumSignType.MD5
                                    : requestSigntype == "RSA" ? EnumSignType.RSA
                                    : requestSigntype == "RSA2" ? EnumSignType.RSA2 : EnumSignType.MD5;

            if (signType == EnumSignType.MD5)
            {
                string sign = BuildRequestsign(param, signType);
                if (requestSign.Equals(sign))
                {
                    result = true;
                }
            }
            else if (signType == EnumSignType.RSA2)
            {
                result = AlipaySignature.RSACheckContent(param, requestSign, AlipayConfig.ALIPay_RSA2_ALI_PUBLICKEY, requestVal["charset"], requestSigntype, false);
            }
            else
            {
                result = RSAFromPkcs8.verify(param, requestSign, AlipayConfig.ALIPay_RSA_ALI_PUBLICKEY, "utf-8");
            }

            string responseText = GetResponseTxt(requestVal["notify_id"]);

            bool resultVal = result && responseText == "true";

            if (resultVal)
            {
                model = new AliPayReturnModel()
                {
                    OutTradeNo  = request.Form["out_trade_no"],
                    TradeNo     = request.Form["trade_no"],
                    TradeStatus = request.Form["trade_status"]
                };
                model.RequestForm = request.Form.ToString();
                decimal total_fee;
                decimal.TryParse(request.Form["total_fee"], out total_fee);
                model.TotalFee = total_fee;
            }
            else
            {
                model = new AliPayReturnModel()
                {
                    RequestForm = param
                };
            }

            return(resultVal);
        }
예제 #23
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("支付宝无通知参数");
            }
        }
예제 #24
0
        public PaymentStatusResponse checkStatus(PaymentRequest request)
        {
            PaymentStatusResponse result = new PaymentStatusResponse();

            if (request == null || request.Id == default(Guid) || this.Setting == null)
            {
                return(result);
            }

            try
            {
                var biz = new AopDictionary();
                biz.Add("out_trade_no", request.Id.ToString("N"));

                var dic = new AopDictionary();
                dic.Add("app_id", Setting.APPId);
                dic.Add("method", "alipay.trade.query");
                dic.Add("charset", "utf-8");
                dic.Add("alipay_sdk", "alipay-easysdk-net-2.0.0");
                dic.Add("sign_type", Setting.SignType);
                dic.Add("timestamp", DateTime.UtcNow.AddHours(8).ToString("yyyy-MM-dd HH:mm:ss"));
                dic.Add("version", "1.0");
                dic.Add("biz_content", JsonHelper.Serialize(biz));

                var data = new AlipayData();
                var sign = data.RSASign(dic, Setting.PrivateKey, "UTF-8", Setting.SignType);
                dic.Add("sign", sign);

                var response        = HttpService.DoPost(Setting.ServerUrl, dic, "UTF-8");
                var jobject         = JsonHelper.Deserialize <JObject>(response);
                var rsaCheckContent = AlipaySignature.RSACheckContent(AlipayData.GetSignSourceData(response), jobject.Value <string>("sign"), Setting.PublicKey,
                                                                      "UTF-8", Setting.SignType);
                if (!rsaCheckContent)
                {
                    throw new AliPayException("sign check fail: check Sign and Data Fail!");
                }
                var res         = jobject["alipay_trade_query_response"];
                var trade_state = res["trade_status"];
                //交易状态:WAIT_BUYER_PAY(交易创建,等待买家付款)、TRADE_CLOSED(未付款交易超时关闭,或支付完成后全额退款)、TRADE_SUCCESS(交易支付成功)、TRADE_FINISHED(交易结束,不可退款)

                if (trade_state != null)
                {
                    result.HasResult = true;
                    var code = trade_state.ToString().ToUpper();
                    if (code == "TRADE_SUCCESS" || code == "TRADE_FINISHED")
                    {
                        result.Status = PaymentStatus.Paid;
                    }
                    else if (code == "TRADE_CLOSED")
                    {
                        result.Status = PaymentStatus.Cancelled;
                    }
                    else if (code == "WAIT_BUYER_PAY")
                    {
                        result.Status = PaymentStatus.Pending;
                    }
                }
            }
            catch (Exception ex)
            {
                Kooboo.Data.Log.Instance.Exception.WriteException(ex);
            }

            return(result);
        }