/// <summary>
        /// 检查支付状态
        /// </summary>
        public override void CheckPayState(PayParameter parameter)
        {
            try
            {
                WxPayConfig config          = new WxPayAPI.WxPayConfig(PayFactory.GetInterfaceXmlConfig(PayInterfaceType.WeiXinScanQRCode, parameter.TradeID));
                WxPayData   queryOrderInput = new WxPayData();
                queryOrderInput.SetValue("out_trade_no", parameter.TradeID);
                WxPayData result = WxPayApi.OrderQuery(queryOrderInput, config);
                string    xml    = result.ToXml();
                PayFactory.OnLog(parameter.TradeID, xml);

                if (result.GetValue("return_code").ToString() == "SUCCESS" &&
                    result.GetValue("result_code").ToString() == "SUCCESS")
                {
                    //支付成功
                    if (result.GetValue("trade_state").ToString() == "SUCCESS")
                    {
                        //触发回调函数
                        PayFactory.OnPaySuccessed(parameter.TradeID, xml);
                        return;
                    }
                    else if (result.GetValue("trade_state").ToString() == "NOTPAY")
                    {
                        //这是一开始生成二维码后,会是这个状态
                        return;
                    }
                }
            }
            catch
            {
            }
        }
Exemple #2
0
        /// <summary>
        /// 创建支付
        /// </summary>
        /// <returns>返回二维码内容</returns>
        public override string StartPay(PayParameter parameter)
        {
            if (parameter.TradeID.IsNullOrEmpty())
            {
                throw new Exception("交易编号为空");
            }

            Config config = new Alipay.Config(PayFactory.GetInterfaceXmlConfig(PayInterfaceType.AlipayScanQRCode, parameter.TradeID));
            IAlipayTradeService serviceClient = config.AppConfig.CreateClientInstance();

            AlipayTradePrecreateContentBuilder builder = BuildPrecreateContent(config, parameter);
            string out_trade_no = builder.out_trade_no;

            //回掉通知页面
            string notifyUrl = string.Format("http://{0}/{1}", HttpContext.Current.Request.Url.Authority, Alipay_ScanPay_HttpModule.NotifyPageName);

            AlipayF2FPrecreateResult precreateResult = serviceClient.tradePrecreate(builder, notifyUrl);

            PayFactory.OnLog(parameter.TradeID, precreateResult.response.Body);
            if (precreateResult.response.QrCode.IsNullOrEmpty())
            {
                //如果没有生成二维码内容,认为失败
                throw new Exception(precreateResult.response.SubMsg);
            }

            if (precreateResult.Status == ResultEnum.FAILED)
            {
                throw new Exception(precreateResult.response.SubMsg);
            }

            return(precreateResult.response.QrCode);
        }
Exemple #3
0
        public override string BeginPay(PayParameter parameter)
        {
            var config = PayFactory.GetConfig <Config>(this.GetType(), parameter.TradeID);

            var head = new Dictionary <string, object>();

            head["service"] = ServiceType;

            var body = new Dictionary <string, object>();

            body["merchant_no"]      = config.merchant_id;
            body["channel_type"]     = ChannelType;
            body["out_trade_no"]     = parameter.TradeID;
            body["total_amount"]     = parameter.Amount.ToString();
            body["subject"]          = parameter.TradeName;
            body["spbill_create_ip"] = "8.8.8.8";
            body["auth_code"]        = parameter.AuthCode;

            var strResult = LianTuo_Helper.PostJsonReturnString(config, URL, head, body, parameter.RequestTimeout);

            PayFactory.OnLog(parameter.TradeID, LogEventType.ReceivePayResult, strResult);

            var responseObj = Newtonsoft.Json.JsonConvert.DeserializeObject <ResponseObject>(strResult);

            string serverSign = responseObj.head["sign"].ToString();

            if (LianTuo_Helper.Sign(config.key, responseObj.head, responseObj.body) != serverSign)
            {
                throw new Exception("服务器返回信息签名检验失败");
            }

            if ((string)responseObj.body["is_success"] == "S")
            {
                double?receipt_amount = null;
                try
                {
                    if (responseObj.body["receipt_amount"] != null)
                    {
                        receipt_amount = Convert.ToDouble(responseObj.body["receipt_amount"]);
                    }
                }
                catch
                {
                }
                PayFactory.OnPaySuccessed(parameter.TradeID, receipt_amount, null, strResult);
            }
            else if ((string)responseObj.body["is_success"] == "F")
            {
                throw new Exception((string)responseObj.body["message"]);
            }
            else if ((string)responseObj.body["is_success"] == "P")
            {
                new Thread(() =>
                {
                    CheckPayStateInLoop(parameter);
                }).Start();
            }
            return(null);
        }
        public override string BeginPay(PayParameter parameter)
        {
            var config = new Config(PayFactory.GetInterfaceXmlConfig(PayInterfaceType.WeiXinBarcode, parameter.TradeID));
            SortedDictionary <string, string> postDict = new SortedDictionary <string, string>();

            postDict["appid"]            = config.AppID;
            postDict["mch_id"]           = config.MchID;
            postDict["nonce_str"]        = Guid.NewGuid().ToString().Replace("-", ""); //随机字符串
            postDict["body"]             = parameter.Description;                      //商品描述
            postDict["out_trade_no"]     = parameter.TradeID;
            postDict["total_fee"]        = ((int)(parameter.Amount * 100)).ToString(); //单位:分
            postDict["spbill_create_ip"] = "8.8.8.8";                                  //终端ip
            postDict["auth_code"]        = parameter.AuthCode;
            postDict["sign_type"]        = "MD5";
            postDict["sign"]             = Helper.GetMd5Hash(postDict, config.Key);

            var xml = ToXml(postDict);

            var result = Helper.PostXml(ServerUrl, xml, parameter.RequestTimeout);

            PayFactory.OnLog(parameter.TradeID, LogEventType.ReceivePayResult, result);

            XDocument xmldoc = XDocument.Parse(result);

            WeiXinScanQRCode.CheckSign(xmldoc, config);

            var return_code = xmldoc.Root.XPathSelectElement("return_code").Value;
            var return_msg  = xmldoc.Root.XPathSelectElement("return_msg").Value;

            if (return_code == "FAIL")
            {
                throw new Exception(return_msg);
            }
            else if (return_code == "SUCCESS" && return_msg == "OK")
            {
                if (xmldoc.Root.XPathSelectElement("result_code").Value == "SUCCESS")
                {
                    //确定付款成功
                    PayFactory.OnPaySuccessed(parameter.TradeID, null, null, result);
                }
                else if (xmldoc.Root.XPathSelectElement("err_code").Value != "USERPAYING" &&
                         xmldoc.Root.XPathSelectElement("result_code").Value == "FAIL" && xmldoc.Root.XPathSelectElement("err_code_des") != null)
                {
                    throw new PayServerReportException(xmldoc.Root.XPathSelectElement("err_code_des").Value);
                }
                else
                {
                    new Thread(() => {
                        CheckPayStateInLoop(parameter);
                    }).Start();
                }
            }
            return(null);
        }
Exemple #5
0
        private void handleNotify()
        {
            using (CLog log = new CLog("weixin scan handleNotify "))
            {
                WxPayData notifyData = GetNotifyData();
                string    json       = notifyData.ToJson();
                log.Log("xml:{0}", json);

                string out_trade_no = notifyData.GetValue("out_trade_no").ToString();

                PayFactory.OnLog(out_trade_no, json);

                WxPayConfig config = new WxPayAPI.WxPayConfig(PayFactory.GetInterfaceXmlConfig(PayInterfaceType.WeiXinScanQRCode, out_trade_no));

                try
                {
                    notifyData.CheckSign(config);
                }
                catch (WxPayException ex)
                {
                    log.Log("签名错误");
                    //若签名错误,则立即返回结果给微信支付后台
                    WxPayData res = new WxPayData();
                    res.SetValue("return_code", "FAIL");
                    res.SetValue("return_msg", ex.Message);

                    Response.Write(res.ToXml());
                    Response.End();
                }

                string result_code = notifyData.GetValue("result_code").ToString();
                string return_code = notifyData.GetValue("return_code").ToString();
                //out_trade_no  result_code  return_code
                if (result_code == "SUCCESS" && return_code == "SUCCESS")
                {
                    PayFactory.OnPaySuccessed(out_trade_no, json);

                    WxPayData data = new WxPayData();
                    data.SetValue("return_code", "SUCCESS");
                    data.SetValue("return_msg", "OK");
                    data.SetValue("appid", config.APPID);
                    data.SetValue("mch_id", config.MCHID);
                    data.SetValue("result_code", "SUCCESS");
                    data.SetValue("err_code_des", "OK");
                    data.SetValue("sign", data.MakeSign(config));

                    //log.Log("write to weixin:{0}", data.ToJson());

                    Response.Write(data.ToXml());
                }
            }
        }
Exemple #6
0
        bool checkPayStateByConfig(PayParameter parameter, Config config)
        {
            IAlipayTradeService serviceClient = config.AppConfig.CreateClientInstance();
            var result = serviceClient.tradeQuery(parameter.TradeID);

            PayFactory.OnLog(parameter.TradeID, result.response.Body);
            if (result.Status == ResultEnum.SUCCESS)
            {
                PayFactory.OnPaySuccessed(parameter.TradeID, result.response.Body);
                return(true);
            }
            return(false);
        }
        public override bool CheckPayState(PayParameter parameter)
        {
            var config = new Config(PayFactory.GetInterfaceXmlConfig(PayInterfaceType.AlipayBarcode, parameter.TradeID));
            SortedDictionary <string, string> postDict = new SortedDictionary <string, string>();

            postDict["app_id"]    = config.appid;
            postDict["method"]    = "alipay.trade.query";
            postDict["charset"]   = "utf-8";
            postDict["sign_type"] = "RSA";
            postDict["timestamp"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            postDict["version"]   = "1.0";

            var bizParameters = new SortedDictionary <string, string>
            {
                { "out_trade_no", parameter.TradeID },
            };

            postDict["biz_content"] = Newtonsoft.Json.JsonConvert.SerializeObject(bizParameters);

            //获取签名的内容
            var signContent = Helper.GetUrlString(postDict);

            var rsa = Way.Lib.RSA.CreateRsaFromPrivateKey(config.merchantPrivateKey, Way.Lib.RSAKeyType.PKCS1);

            rsa.KeySize = 1024;

            var signatureBytes = rsa.SignData(Encoding.UTF8.GetBytes(signContent), HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);

            // 把密文加入提交的参数列表中
            postDict["sign"] = Convert.ToBase64String(signatureBytes);

            var result = Helper.PostQueryString(ServerUrl, Helper.BuildQuery(postDict), parameter.RequestTimeout);

            PayFactory.OnLog(parameter.TradeID, LogEventType.ReceivePayResult, result);

            // 把json结果转为对象
            var payResult = Newtonsoft.Json.JsonConvert.DeserializeObject <AlipayTradeQueryResult>(result);

            CheckSign(result, "alipay_trade_query_response", payResult.sign, config);


            if (payResult.alipay_trade_query_response.code == "10000" && (payResult.alipay_trade_query_response.trade_status == "TRADE_SUCCESS" || payResult.alipay_trade_query_response.trade_status == "TRADE_FINISHED"))
            {
                //明确交易成功了
                PayFactory.OnPaySuccessed(parameter.TradeID, payResult.alipay_trade_query_response.receipt_amount, null, result);
                return(true);
            }

            return(false);
        }
Exemple #8
0
 /// <summary>
 /// 检查订单状态
 /// </summary>
 public override void CheckPayState(PayParameter parameter)
 {
     try
     {
         Config config = new Alipay.Config(PayFactory.GetInterfaceXmlConfig(PayInterfaceType.AlipayScanQRCode, parameter.TradeID));
         IAlipayTradeService serviceClient = config.AppConfig.CreateClientInstance();
         var result = serviceClient.tradeQuery(parameter.TradeID);
         PayFactory.OnLog(parameter.TradeID, result.response.Body);
         //客户没有扫码之前,会返回交易不存在
         if (result.Status == ResultEnum.SUCCESS)
         {
             PayFactory.OnPaySuccessed(parameter.TradeID, result.response.Body);
         }
     }
     catch
     {
     }
 }
        public string BeginPay(PayParameter parameter)
        {
            if (string.IsNullOrEmpty(parameter.Description))
            {
                throw new Exception("PayParameter.Description can not be empty");
            }
            var config = new Config(PayFactory.GetInterfaceXmlConfig(PayInterfaceType.WeiXinTransfers, parameter.TradeID));
            SortedDictionary <string, string> postDict = new SortedDictionary <string, string>();

            postDict["mch_appid"]        = config.AppID;
            postDict["mchid"]            = config.MchID;
            postDict["partner_trade_no"] = parameter.TradeID;
            postDict["nonce_str"]        = Guid.NewGuid().ToString().Replace("-", "");//随机字符串
            postDict["openid"]           = parameter.AuthCode;
            postDict["check_name"]       = "NO_CHECK";
            postDict["amount"]           = ((int)(parameter.Amount * 100)).ToString();//单位:分
            postDict["desc"]             = parameter.Description;
            postDict["spbill_create_ip"] = "8.8.8.8";
            postDict["sign"]             = Helper.GetMd5Hash(postDict, config.Key);

            var xml = WeiXinScanQRCode.ToXml(postDict);

            var result = Helper.PostXml(ServerUrl, xml, parameter.RequestTimeout, config.SSLCERT_PATH, config.SSLCERT_PASSWORD);

            PayFactory.OnLog(parameter.TradeID, LogEventType.ReceivePayResult, result);

            XDocument xmldoc = XDocument.Parse(result);

            //这里不用验证sign

            if (xmldoc.Root.XPathSelectElement("return_msg").Value != "OK" && xmldoc.Root.XPathSelectElement("err_code_des") != null)
            {
                throw new PayServerReportException(xmldoc.Root.XPathSelectElement("err_code_des").Value);
            }

            var return_code = xmldoc.Root.XPathSelectElement("return_code").Value;

            if (return_code == "SUCCESS" && xmldoc.Root.XPathSelectElement("result_code").Value == "SUCCESS")
            {
                PayFactory.OnPaySuccessed(parameter.TradeID, null, null, result);
            }
            return(null);
        }
        public override string BeginPay(PayParameter parameter)
        {
            bool enableNotify = false;

            var config = new Config(PayFactory.GetInterfaceXmlConfig(PayInterfaceType.WeiXinScanQRCode, parameter.TradeID));
            SortedDictionary <string, string> postDict = new SortedDictionary <string, string>();

            postDict["appid"]            = config.AppID;
            postDict["mch_id"]           = config.MchID;
            postDict["nonce_str"]        = Guid.NewGuid().ToString().Replace("-", ""); //随机字符串
            postDict["body"]             = parameter.Description;                      //交易描述
            postDict["out_trade_no"]     = parameter.TradeID;
            postDict["total_fee"]        = ((int)(parameter.Amount * 100)).ToString(); //单位:分
            postDict["spbill_create_ip"] = "8.8.8.8";                                  //终端ip
            if (string.IsNullOrEmpty(parameter.NotifyDomain))
            {
                postDict["notify_url"] = "http://paysdk.weixin.qq.com/example/ResultNotifyPage.aspx";
            }
            else
            {
                enableNotify           = true;
                postDict["notify_url"] = $"{parameter.NotifyDomain}/{WeiXinNotify_RequestHandler.NotifyPageName}";
            }

            postDict["trade_type"] = "NATIVE";
            postDict["sign_type"]  = "MD5";
            postDict["time_start"] = DateTime.Now.ToString("yyyyMMddHHmmss");//交易起始时间
            if (parameter.ExpireTime != null)
            {
                postDict["time_expire"] = parameter.ExpireTime.Value.ToString("yyyyMMddHHmmss");//交易结束时间
            }
            else
            {
                //默认十分钟
                postDict["time_expire"] = DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss");//交易结束时间
            }

            postDict["sign"] = Helper.GetMd5Hash(postDict, config.Key);

            var xml = ToXml(postDict);

            var result = Helper.PostXml(ServerUrl, xml, parameter.RequestTimeout);

            PayFactory.OnLog(parameter.TradeID, LogEventType.ReceivePayResult, result);

            XDocument xmldoc = XDocument.Parse(result);

            CheckSign(xmldoc, config);

            var return_code = xmldoc.Root.XPathSelectElement("return_code").Value;
            var return_msg  = xmldoc.Root.XPathSelectElement("return_msg").Value;

            if (return_code == "FAIL")
            {
                throw new Exception(return_msg);
            }
            else if (return_code == "SUCCESS" && return_msg == "OK")
            {
                if (enableNotify == false)
                {
                    new Thread(() => {
                        CheckPayStateInLoop(parameter);
                    }).Start();
                }
                return(xmldoc.Root.XPathSelectElement("code_url").Value);
            }
            return(null);
        }
        public TaskStatus Handle(IHttpProxy httpProxy)
        {
            using (CLog log = new CLog("Alipay Notify", false))
            {
                var data = GetRequestData(httpProxy.Form);

                var dataJson = Newtonsoft.Json.JsonConvert.SerializeObject(data);
                log.Log(dataJson);

                if (data.Count > 0)
                {
                    string out_trade_no = data["out_trade_no"];
                    string sign         = httpProxy.Form["sign"];
                    //string sign_type = form["sign_type"];


                    PayFactory.OnLog(out_trade_no, LogEventType.ReceiveNotify, dataJson);

                    var config = new Config(PayFactory.GetInterfaceXmlConfig(PayInterfaceType.AlipayScanQRCode, out_trade_no));

                    var signStr = Helper.GetUrlString(data, false);

                    System.Security.Cryptography.RSA rsacore = Way.Lib.RSA.CreateRsaFromPublicKey(config.alipayPublicKey);

                    var isPass = rsacore.VerifyData(Encoding.GetEncoding("utf-8").GetBytes(signStr), Convert.FromBase64String(sign), HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);


                    if (isPass == false)
                    {
                        log.Log("sign:{0}", sign);
                        log.Log("签名不一致");
                        httpProxy.ResponseWrite("fail");
                        return(TaskStatus.Completed);
                    }

                    //支付宝交易号
                    string trade_no = data["trade_no"];

                    //交易状态
                    //在支付宝的业务通知中,只有交易通知状态为TRADE_SUCCESS或TRADE_FINISHED时,才是买家付款成功。
                    string trade_status = data["trade_status"];

                    double?receipt_amount = null;
                    try
                    {
                        receipt_amount = Convert.ToDouble(data["receipt_amount"]);
                    }
                    catch
                    {
                    }
                    log.Log(trade_status);

                    if (trade_status == "TRADE_SUCCESS")
                    {
                        log.Log("excute OnPaySuccessed");
                        PayFactory.OnPaySuccessed(out_trade_no, receipt_amount, null, dataJson);
                    }

                    httpProxy.ResponseWrite("success");
                }
                else
                {
                    httpProxy.ResponseWrite("无通知参数");
                }
            }

            return(TaskStatus.Completed);
        }
        private void handleNotify()
        {
            using (CLog log = new CLog("alipay scan handleNotify "))
            {
                log.Log(Request.Form.ToJson());

                SortedDictionary <string, string> sPara = GetRequestPost();

                if (sPara.Count > 0)//判断是否有带返回参数
                {
                    //商户订单号
                    string out_trade_no = Request.Form["out_trade_no"];
                    var    config       = new Config(PayFactory.GetInterfaceXmlConfig(PayInterfaceType.AlipayScanQRCode, out_trade_no));
                    Notify aliNotify    = new Notify(config.AppConfig.charset, config.AppConfig.sign_type, config.AppConfig.pid,
                                                     config.AppConfig.mapiUrl, config.AppConfig.alipay_public_key);

                    ////对异步通知进行延签
                    bool verifyResult = aliNotify.Verify(sPara, Request.Form["notify_id"], Request.Form["sign"]);


                    log.Log("verifyResult:{0}", verifyResult);
                    if (verifyResult && CheckParams()) //验签成功 && 关键业务参数校验成功
                    {
                        /////////////////////////////////////////////////////////////////////////////////////////////////////////////
                        //请在这里加上商户的业务逻辑程序代码


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



                        //支付宝交易号
                        string trade_no = Request.Form["trade_no"];

                        //交易状态
                        //在支付宝的业务通知中,只有交易通知状态为TRADE_SUCCESS或TRADE_FINISHED时,才是买家付款成功。
                        string trade_status = Request.Form["trade_status"];

                        log.Log(trade_status);
                        PayFactory.OnLog(out_trade_no, Request.Form.ToJson());

                        if (trade_status == "TRADE_SUCCESS")
                        {
                            PayFactory.OnPaySuccessed(out_trade_no, Request.Form.ToJson());
                        }

                        //判断是否在商户网站中已经做过了这次通知返回的处理
                        //如果没有做过处理,那么执行商户的业务程序
                        //如果有做过处理,那么不执行商户的业务程序

                        Response.Write("success");  //请不要修改或删除

                        //——请根据您的业务逻辑来编写程序(以上代码仅作参考)——

                        /////////////////////////////////////////////////////////////////////////////////////////////////////////////
                    }
                    else//验证失败
                    {
                        log.Log("fail");
                        Response.Write("fail");
                    }
                }
                else
                {
                    log.Log("无通知参数");
                    Response.Write("无通知参数");
                }
            }
        }
        public override string BeginPay(PayParameter parameter)
        {
            if (string.IsNullOrEmpty(parameter.ReturnUrl))
            {
                throw new Exception("ReturnUrl can not be empty");
            }

            var attrs = this.GetType().GetCustomAttributes(typeof(PayInterfaceAttribute), false);
            //获取当前接口类型
            var myInterfaceType = ((PayInterfaceAttribute)attrs[0]).InterfaceType;
            var config          = new Config(PayFactory.GetInterfaceXmlConfig(myInterfaceType, parameter.TradeID));

            Dictionary <string, object> postDict = new Dictionary <string, object>();

            postDict["merchantCode"] = config.merchantCode;
            postDict["operatorCode"] = config.operatorCode;
            postDict["businessCode"] = this.BusinessCode;


            var detail = new Dictionary <string, string>
            {
                { "amount", ((int)(parameter.Amount * 100)).ToString() },
                { "businessCode", this.BusinessCode },
                { "merchantGenCode", parameter.TradeID },
                { "operatorCode", config.operatorCode },
                { "purpose", parameter.Description },
                { "openId", parameter.AuthCode },
            };

            if (!string.IsNullOrEmpty(parameter.ReturnUrl))
            {
                PaysoonReturn_RequestHandler.ReturnUrlDict[parameter.TradeID] = parameter.ReturnUrl;
                detail["frontCallback"] = $"{parameter.NotifyDomain}/{PaysoonReturn_RequestHandler.ReturnPageName}";
            }
            if (SupportNotify)
            {
                if (string.IsNullOrEmpty(parameter.NotifyDomain) == false)
                {
                    detail["callBackUrl"] = $"{parameter.NotifyDomain}/{Paysoon_RequestHandler.NotifyPageName}";
                }
                else
                {
                    throw new Exception("This interface just run at website");
                }
            }

            var signContent = Newtonsoft.Json.JsonConvert.SerializeObject(new object[] { detail });

            var rsa = Way.Lib.RSA.CreateRsaFromPublicKey(config.platformPublicKey);

            rsa.KeySize = 1024;
            // 把密文加入提交的参数列表中

            postDict["detail"] = Way.Lib.RSA.EncryptToBase64(rsa, Encoding.UTF8.GetBytes(signContent), RSAEncryptionPadding.Pkcs1);


            string json     = Newtonsoft.Json.JsonConvert.SerializeObject(postDict);
            string queryStr = $"request={WebUtility.UrlEncode(json)}";
            var    result   = Helper.PostQueryString(ServerUrl, queryStr, parameter.RequestTimeout);

            PayFactory.OnLog(parameter.TradeID, LogEventType.ReceivePayResult, result);

            var resultDict = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(result);

            return(OnBeginPayPostGetResult(result, config, resultDict, parameter));
        }
Exemple #14
0
        /// <summary>
        /// 直接付款,适合条码支付
        /// </summary>
        /// <param name="parameter"></param>
        public virtual string StartPay(PayParameter parameter)
        {
            if (parameter.AuthCode.IsNullOrEmpty())
            {
                throw new Exception("条码为空");
            }
            if (parameter.TradeID.IsNullOrEmpty())
            {
                throw new Exception("交易编号为空");
            }


            try
            {
                Config config = new Config(PayFactory.GetInterfaceXmlConfig(PayInterfaceType.AlipayBarcode, parameter.TradeID));


                //创建提交的内容
                AlipayTradePayContentBuilder builder = BuildPayContent(config, parameter);
                var client = config.AppConfig.CreateAopClient();
                AlipayTradePayRequest payRequest = new AlipayTradePayRequest();
                payRequest.BizContent = builder.BuildJson();

                AlipayTradePayResponse payResponse = client.Execute(payRequest);

                PayFactory.OnLog(parameter.TradeID, payResponse.Body);

                string[] errorCodes = new string[] { "20000", "20001", "40001", "40002", "40003", "40004", "40006" };//明确一定是错误的代码

                if (errorCodes.Contains(payResponse.Code))
                {
                    PayFactory.OnPayFailed(parameter.TradeID, payResponse.SubMsg, payResponse.Body);
                }
                else if (payResponse.Code == ResultCode.SUCCESS)
                {
                    PayFactory.OnPaySuccessed(parameter.TradeID, payResponse.Body);
                }
                else
                {
                    //到这里,不能确定支付结果,循环30秒确定
                    int checkTimes = parameter.Timeout / 2;
                    Thread.Sleep(1000);
                    for (int i = 0; i < checkTimes; i++)
                    {
                        if (checkPayStateByConfig(parameter, config))
                        {
                            break;
                        }
                        if (i + 1 == checkTimes)
                        {
                            break;
                        }
                        Thread.Sleep(2000);
                    }
                }
            }
            catch (Exception ex)
            {
            }

            return(null);
        }
        private void handleNotify()
        {
            using (CLog log = new CLog("alipay handleNotify "))
            {
                log.Log(Request.Form.ToJson());
                SortedDictionary <string, string> sPara = GetRequestPost();

                if (sPara.Count > 0)//判断是否有带返回参数
                {
                    string            out_trade_no = Request.Form["out_trade_no"];
                    var               config       = new Config(PayFactory.GetInterfaceXmlConfig(PayInterfaceType.AlipayWebPay, out_trade_no));
                    Com.Alipay.Notify aliNotify    = new Com.Alipay.Notify(config);
                    bool              verifyResult = aliNotify.Verify(sPara, Request.Form["notify_id"], Request.Form["sign"]);

                    log.Log("verifyResult:{0}", verifyResult);
                    if (verifyResult)//验证成功
                    {
                        /////////////////////////////////////////////////////////////////////////////////////////////////////////////
                        //请在这里加上商户的业务逻辑程序代码


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

                        //商户订单号



                        //支付宝交易号

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

                        //交易状态
                        string trade_status = Request.Form["trade_status"];

                        log.Log(Request.Form["trade_status"]);
                        PayFactory.OnLog(out_trade_no, Request.Form.ToJson());

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

                            //注意:
                            //退款日期超过可退款期限后(如三个月可退款),支付宝系统发送该交易状态通知
                        }
                        else if (Request.Form["trade_status"] == "TRADE_SUCCESS")
                        {
                            //判断该笔订单是否在商户网站中已经做过处理
                            //如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序
                            //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
                            //如果有做过处理,不执行商户的业务程序

                            //注意:
                            //付款完成后,支付宝系统发送该交易状态通知

                            log.Log("OnPaySuccessed");
                            PayFactory.OnPaySuccessed(out_trade_no, Request.Form.ToJson());
                        }
                        else
                        {
                        }

                        //——请根据您的业务逻辑来编写程序(以上代码仅作参考)——

                        Response.Write("success");  //请不要修改或删除

                        /////////////////////////////////////////////////////////////////////////////////////////////////////////////
                    }
                    else//验证失败
                    {
                        log.Log("fail");
                        Response.Write("fail");
                    }
                }
                else
                {
                    log.Log("无通知参数");
                    Response.Write("无通知参数");
                }
            }
        }
        public override string BeginPay(PayParameter parameter)
        {
            var attrs = this.GetType().GetCustomAttributes(typeof(PayInterfaceAttribute), false);
            //获取当前接口类型
            var myInterfaceType = ((PayInterfaceAttribute)attrs[0]).InterfaceType;
            var config          = new Config(PayFactory.GetInterfaceXmlConfig(myInterfaceType, parameter.TradeID));

            Dictionary <string, object> postDict = new Dictionary <string, object>();

            postDict["merchantCode"] = config.merchantCode;
            postDict["operatorCode"] = config.operatorCode;
            postDict["businessCode"] = this.BusinessCode;


            var detail = new SortedDictionary <string, object>
            {
                { "amount", ((int)(parameter.Amount * 100)).ToString() },
                { "businessCode", this.BusinessCode },
                { "merchantGenCode", parameter.TradeID },
                { "operatorCode", config.operatorCode },
                { "purpose", parameter.Description },
            };

            if (!string.IsNullOrEmpty(parameter.AuthCode))
            {
                detail["authCode"] = parameter.AuthCode;
            }
            if (parameter.GoodsDetails.Count > 0)
            {
                var goodsDetails = new List <object>();
                foreach (var gooditem in parameter.GoodsDetails)
                {
                    goodsDetails.Add(new
                    {
                        productCode   = gooditem.GoodsId,
                        productName   = gooditem.GoodsName,
                        productNumber = gooditem.Quantity.ToString(),
                        productPrice  = ((int)(gooditem.Price * 100))
                    });
                }
                detail["requestProductList"] = goodsDetails;
            }

            if (SupportNotify)
            {
                if (string.IsNullOrEmpty(parameter.NotifyDomain) == false)
                {
                    detail["callBackUrl"] = $"{parameter.NotifyDomain}/{Paysoon_RequestHandler.NotifyPageName}";
                }
            }

            var signContent = Newtonsoft.Json.JsonConvert.SerializeObject(new object[] { detail });

            var rsa = Way.Lib.RSA.CreateRsaFromPublicKey(config.platformPublicKey);

            rsa.KeySize = 1024;
            // 把密文加入提交的参数列表中

            postDict["detail"] = Way.Lib.RSA.EncryptToBase64(rsa, Encoding.UTF8.GetBytes(signContent), RSAEncryptionPadding.Pkcs1);


            string json     = Newtonsoft.Json.JsonConvert.SerializeObject(postDict);
            string queryStr = $"request={WebUtility.UrlEncode(json)}";
            var    result   = Helper.PostQueryString(ServerUrl, queryStr, parameter.RequestTimeout);

            PayFactory.OnLog(parameter.TradeID, LogEventType.ReceivePayResult, result);

            var resultDict = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(result);

            return(OnBeginPayPostGetResult(result, config, resultDict, parameter));
        }
        public override string BeginPay(PayParameter parameter)
        {
            var enableNotify = false;
            var config       = new Config(PayFactory.GetInterfaceXmlConfig(PayInterfaceType.AlipayScanQRCode, parameter.TradeID));
            SortedDictionary <string, string> postDict = new SortedDictionary <string, string>();

            postDict["app_id"]    = config.appid;
            postDict["method"]    = "alipay.trade.precreate";
            postDict["charset"]   = "utf-8";
            postDict["sign_type"] = "RSA";
            postDict["timestamp"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            postDict["version"]   = "1.0";
            if (string.IsNullOrEmpty(parameter.NotifyDomain) == false)
            {
                enableNotify           = true;
                postDict["notify_url"] = $"{parameter.NotifyDomain}/{AlipayNotify_RequestHandler.NotifyPageName}";
            }

            var bizParameters = new SortedDictionary <string, object>
            {
                { "out_trade_no", parameter.TradeID },
                { "subject", parameter.TradeName },
                { "body", parameter.Description },
                { "total_amount", parameter.Amount.ToString("0.00") },
                { "undiscountable_amount", "0" },
                { "timeout_express", Math.Max(1, parameter.Timeout / 60) + "m" },
                //{"seller_id", config.pid}
            };

            if (parameter.GoodsDetails.Count > 0)
            {
                var goodsDetails = new List <object>();
                foreach (var gooditem in parameter.GoodsDetails)
                {
                    goodsDetails.Add(new
                    {
                        goods_id   = gooditem.GoodsId,
                        goods_name = gooditem.GoodsName,
                        quantity   = gooditem.Quantity,
                        price      = gooditem.Price
                    });
                }
                bizParameters["goods_detail"] = goodsDetails;
            }
            if (!string.IsNullOrEmpty(parameter.StoreId))
            {
                bizParameters["store_id"] = parameter.StoreId;
            }
            postDict["biz_content"] = Newtonsoft.Json.JsonConvert.SerializeObject(bizParameters);

            //获取签名的内容
            var signContent = Helper.GetUrlString(postDict);

            var rsa = Way.Lib.RSA.CreateRsaFromPrivateKey(config.merchantPrivateKey, Way.Lib.RSAKeyType.PKCS1);

            rsa.KeySize = 1024;

            var signatureBytes = rsa.SignData(Encoding.UTF8.GetBytes(signContent), HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);

            // 把密文加入提交的参数列表中
            postDict["sign"] = Convert.ToBase64String(signatureBytes);

            var result = Helper.PostQueryString(ServerUrl, Helper.BuildQuery(postDict), parameter.RequestTimeout);

            PayFactory.OnLog(parameter.TradeID, LogEventType.ReceivePayResult, result);

            // 把json结果转为对象
            var payResult = Newtonsoft.Json.JsonConvert.DeserializeObject <AlipayTradePrecreateResult>(result);

            AlipayBarcode.CheckSign(result, "alipay_trade_precreate_response", payResult.sign, config);


            if (payResult.alipay_trade_precreate_response.code == "10000")
            {
                if (enableNotify == false)
                {
                    new Thread(() =>
                    {
                        CheckPayStateInLoop(parameter);
                    }).Start();
                }
                return(payResult.alipay_trade_precreate_response.qr_code);
            }
            else
            {
                throw new Exception(payResult.alipay_trade_precreate_response.sub_msg);
            }
        }
        public TaskStatus Handle(IHttpProxy httpHandler)
        {
            try
            {
                var xml = httpHandler.ReadRequestBody();
                using (CLog log = new CLog("WeiXinNotify Notify", false))
                {
                    log.Log("xml:{0}", xml);

                    XDocument xmldoc = XDocument.Parse(xml);
                    SortedDictionary <string, string> xmlDict = new SortedDictionary <string, string>();
                    var nodes = xmldoc.Root.Elements();
                    foreach (var element in nodes)
                    {
                        if (element.Name.LocalName != "sign")
                        {
                            xmlDict[element.Name.LocalName] = element.Value;
                        }
                    }

                    var return_code  = xmlDict["return_code"];
                    var result_code  = xmlDict["result_code"];
                    var out_trade_no = xmlDict["out_trade_no"];

                    PayFactory.OnLog(out_trade_no, LogEventType.ReceiveNotify, xml);

                    var config = new Config(PayFactory.GetInterfaceXmlConfig(PayInterfaceType.WeiXinScanQRCode, out_trade_no));

                    log.Log("签名校验");
                    var sign = xmldoc.Root.XPathSelectElement("sign").Value;

                    var computeSign = Helper.GetMd5Hash(xmlDict, config.Key);

                    if (sign != computeSign)
                    {
                        log.Log("正确签名:{0}", computeSign);
                        log.Log("签名校验不通过");
                        throw new Exception("签名校验不通过");
                    }

                    if (result_code == "SUCCESS" && return_code == "SUCCESS")
                    {
                        log.Log("excute OnPaySuccessed");
                        PayFactory.OnPaySuccessed(out_trade_no, null, null, xml);

                        WxPayData data = new WxPayData();
                        data.SetValue("return_code", "SUCCESS");
                        data.SetValue("return_msg", "OK");
                        data.SetValue("appid", config.AppID);
                        data.SetValue("mch_id", config.MchID);
                        data.SetValue("result_code", "SUCCESS");
                        data.SetValue("err_code_des", "OK");
                        data.SetValue("sign", data.MakeSign(config));

                        var writebackXml = data.ToXml();
                        log.Log("write to weixin:{0}", writebackXml);

                        httpHandler.ResponseWrite(writebackXml);
                    }
                }
            }
            catch (Exception ex)
            {
                using (CLog log = new CLog("WeiXin Notify error "))
                {
                    log.Log(ex.ToString());

                    WxPayData res = new WxPayData();
                    res.SetValue("return_code", "FAIL");
                    res.SetValue("return_msg", ex.Message);

                    var writebackXml = res.ToXml();
                    log.Log("write to weixin:{0}", writebackXml);

                    httpHandler.ResponseWrite(writebackXml);
                }
            }
            return(TaskStatus.Completed);
        }
Exemple #19
0
        public override string BeginPay(PayParameter parameter)
        {
            bool enableNotify = false;
            var  config       = PayFactory.GetConfig <Config>(this.GetType(), parameter.TradeID);

            var head = new Dictionary <string, object>();

            head["service"] = "front.jsapi";

            var body = new Dictionary <string, object>();

            body["merchant_no"]      = config.merchant_id;
            body["channel_type"]     = "WX";
            body["out_trade_no"]     = parameter.TradeID;
            body["total_amount"]     = parameter.Amount.ToString();
            body["subject"]          = parameter.TradeName;
            body["spbill_create_ip"] = "8.8.8.8";
            body["open_id"]          = parameter.AuthCode;
            body["sub_appid"]        = config.weixin_appid;
            if (!string.IsNullOrEmpty(parameter.NotifyDomain))
            {
                enableNotify       = true;
                body["notify_url"] = $"{parameter.NotifyDomain}/{PayResult_RequestHandler.NotifyPageName}";
            }


            var strResult = LianTuo_Helper.PostJsonReturnString(config, URL, head, body, parameter.RequestTimeout);

            PayFactory.OnLog(parameter.TradeID, LogEventType.ReceivePayResult, strResult);

            var responseObj = Newtonsoft.Json.JsonConvert.DeserializeObject <ResponseObject>(strResult);

            string serverSign = responseObj.head["sign"].ToString();

            if (LianTuo_Helper.Sign(config.key, responseObj.head, responseObj.body) != serverSign)
            {
                throw new Exception("服务器返回信息签名检验失败");
            }

            if ((string)responseObj.body["is_success"] == "S")
            {
                if (enableNotify == false)
                {
                    new Thread(() =>
                    {
                        CheckPayStateInLoop(parameter);
                    }).Start();
                }
                //pay_info参数是微信jsapi发起的参数
                var jsonWeiXinBody = Newtonsoft.Json.JsonConvert.DeserializeObject <string>(responseObj.body["pay_info"].ToString());
                Dictionary <string, string> returnDict = Newtonsoft.Json.JsonConvert.DeserializeObject <Dictionary <string, string> >(jsonWeiXinBody);

                returnDict["ReturnUrl"] = parameter.ReturnUrl;
                returnDict["TradeID"]   = parameter.TradeID;
                var jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(returnDict);


                //先把jsonStr保存成一个临时文件
                string tranid   = Guid.NewGuid().ToString("N");
                string tempFile = $"{Helper.GetSaveFilePath()}\\{tranid}.txt";
                System.IO.File.WriteAllText(tempFile, jsonStr, Encoding.UTF8);

                return($"{parameter.NotifyDomain}/{Weixin.WeiXinPayRedirect_RequestHandler.NotifyPageName}?tranId={tranid}");
            }
            else if ((string)responseObj.body["is_success"] == "F")
            {
                throw new Exception((string)responseObj.body["message"]);
            }
            return(null);
        }
Exemple #20
0
        public virtual string StartPay(PayParameter parameter)
        {
            try
            {
                WxPayConfig config = new WxPayAPI.WxPayConfig(PayFactory.GetInterfaceXmlConfig(PayInterfaceType.WeiXinBarcode, parameter.TradeID));
                WxPayData   data   = new WxPayData();
                data.SetValue("auth_code", parameter.AuthCode);                                                   //授权码
                data.SetValue("body", parameter.TradeName == null ? parameter.Description : parameter.TradeName); //商品描述
                data.SetValue("total_fee", Convert.ToInt32(parameter.Amount * 100));                              //总金额,以分为单位
                data.SetValue("out_trade_no", parameter.TradeID);                                                 //产生随机的商户订单号

                WxPayData result = WxPayApi.Micropay(data, config, 20);                                           //提交被扫支付,接收返回结果
                string    xml    = result.ToXml();
                PayFactory.OnLog(parameter.TradeID, xml);
                string returnMsg = result.IsSet("return_msg") ? result.GetValue("return_msg").ToSafeString() : result.GetValue("err_code_des").ToSafeString();
                //如果提交被扫支付接口调用失败,则抛异常
                if (!result.IsSet("return_code") || result.GetValue("return_code").ToString() == "FAIL")
                {
                    //触发回调函数
                    PayFactory.OnPayFailed(parameter.TradeID, returnMsg, xml);
                    return(null);
                }

                //签名验证
                result.CheckSign(config);


                //刷卡支付直接成功
                if (result.GetValue("return_code").ToString() == "SUCCESS" &&
                    result.GetValue("result_code").ToString() == "SUCCESS")
                {
                    //触发回调函数
                    PayFactory.OnPaySuccessed(parameter.TradeID, result.ToXml());
                    return(null);
                }

                //1)业务结果明确失败
                if (result.GetValue("err_code").ToString() != "USERPAYING" &&
                    result.GetValue("err_code").ToString() != "SYSTEMERROR")
                {
                    //触发回调函数
                    PayFactory.OnPayFailed(parameter.TradeID, result.GetValue("err_code_des").ToSafeString(), xml);
                    return(null);
                }

                //到这里,不能确定支付结果,循环30秒确定
                int checkTimes = parameter.Timeout / 2;
                Thread.Sleep(1000);
                for (int i = 0; i < checkTimes; i++)
                {
                    if (checkPayStateByConfig(parameter, config))
                    {
                        break;
                    }
                    if (i + 1 == checkTimes)
                    {
                        break;
                    }
                    Thread.Sleep(2000);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(null);
        }
Exemple #21
0
        public override string BeginPay(PayParameter parameter)
        {
            if (string.IsNullOrEmpty(parameter.AuthCode))
            {
                throw new Exception("PayParameter.AuthCode(wechat openid)can not be empty");
            }
            if (string.IsNullOrEmpty(parameter.ReturnUrl))
            {
                throw new Exception("ReturnUrl can not be empty");
            }

            bool enableNotify = false;

            var config = new Config(PayFactory.GetInterfaceXmlConfig(PayInterfaceType.WeiXinJSApi, parameter.TradeID));
            SortedDictionary <string, string> postDict = new SortedDictionary <string, string>();

            postDict["appid"]            = config.AppID;
            postDict["mch_id"]           = config.MchID;
            postDict["nonce_str"]        = Guid.NewGuid().ToString().Replace("-", ""); //随机字符串
            postDict["sign_type"]        = "MD5";
            postDict["body"]             = parameter.Description;                      //商品描述
            postDict["out_trade_no"]     = parameter.TradeID;
            postDict["openid"]           = parameter.AuthCode;
            postDict["total_fee"]        = ((int)(parameter.Amount * 100)).ToString(); //单位:分
            postDict["spbill_create_ip"] = "8.8.8.8";                                  //终端ip
            if (string.IsNullOrEmpty(parameter.NotifyDomain))
            {
                postDict["notify_url"] = "http://paysdk.weixin.qq.com/example/ResultNotifyPage.aspx";
            }
            else
            {
                enableNotify           = true;
                postDict["notify_url"] = $"{parameter.NotifyDomain}/{WeiXinNotify_RequestHandler.NotifyPageName}";
            }

            postDict["time_start"] = DateTime.Now.ToString("yyyyMMddHHmmss");//交易起始时间
            if (parameter.ExpireTime != null)
            {
                postDict["time_expire"] = parameter.ExpireTime.Value.ToString("yyyyMMddHHmmss");//交易结束时间
            }
            else
            {
                //默认十分钟
                postDict["time_expire"] = DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss");//交易结束时间
            }

            postDict["trade_type"] = "JSAPI";

            postDict["sign"] = Helper.GetMd5Hash(postDict, config.Key);

            var xml = ToXml(postDict);

            var result = Helper.PostXml(ServerUrl, xml, parameter.RequestTimeout);

            PayFactory.OnLog(parameter.TradeID, LogEventType.ReceivePayResult, result);

            XDocument xmldoc = XDocument.Parse(result);

            var return_code = xmldoc.Root.XPathSelectElement("return_code").Value;
            var return_msg  = xmldoc.Root.XPathSelectElement("return_msg").Value;

            if (return_code == "FAIL")
            {
                throw new PayServerReportException(return_msg);
            }
            else if (return_code == "SUCCESS" && return_msg == "OK")
            {
                WeiXinScanQRCode.CheckSign(xmldoc, config);

                if (enableNotify == false)
                {
                    new Thread(() => {
                        CheckPayStateInLoop(parameter);
                    }).Start();
                }

                var prepayid = xmldoc.Root.XPathSelectElement("prepay_id").Value;
                SortedDictionary <string, string> returnDict = new SortedDictionary <string, string>();
                returnDict["appId"]     = config.AppID;
                returnDict["timeStamp"] = GenerateTimeStamp();
                returnDict["nonceStr"]  = Guid.NewGuid().ToString("N");
                returnDict["package"]   = $"prepay_id={prepayid}";
                returnDict["signType"]  = "MD5";
                returnDict["paySign"]   = Helper.GetMd5Hash(returnDict, config.Key);

                returnDict["ReturnUrl"] = parameter.ReturnUrl;
                returnDict["TradeID"]   = parameter.TradeID;
                var jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(returnDict);


                //先把jsonStr保存成一个临时文件
                string tranid   = Guid.NewGuid().ToString("N");
                string tempFile = $"{Helper.GetSaveFilePath()}\\{tranid}.txt";
                System.IO.File.WriteAllText(tempFile, jsonStr, Encoding.UTF8);

                return($"{parameter.NotifyDomain}/{WeiXinPayRedirect_RequestHandler.NotifyPageName}?tranId={tranid}");
            }
            return(null);
        }
Exemple #22
0
        /// <summary>
        /// 检查订单状态
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="config"></param>
        /// <returns>只要有结果,无论成功或者失败,返回true,不确定支付结果返回false</returns>
        bool checkPayStateByConfig(PayParameter parameter, WxPayConfig config)
        {
            try
            {
                WxPayData queryOrderInput = new WxPayData();
                queryOrderInput.SetValue("out_trade_no", parameter.TradeID);
                WxPayData result = WxPayApi.OrderQuery(queryOrderInput, config);
                string    xml    = result.ToXml();

                PayFactory.OnLog(parameter.TradeID, xml);
                if (result.GetValue("return_code").ToString() == "SUCCESS" &&
                    result.GetValue("result_code").ToString() == "SUCCESS")
                {
                    //支付成功
                    if (result.GetValue("trade_state").ToString() == "SUCCESS")
                    {
                        //触发回调函数
                        PayFactory.OnPaySuccessed(parameter.TradeID, result.ToXml());
                        return(true);
                    }
                    //用户支付中,需要继续查询
                    else if (result.GetValue("trade_state").ToString() == "USERPAYING")
                    {
                        return(false);
                    }
                    else if (result.GetValue("trade_state").ToString() == "NOTPAY")
                    {
                        //触发回调函数
                        PayFactory.OnPayFailed(parameter.TradeID, "放弃支付", xml);
                        return(true);
                    }
                }

                string returnMsg = result.GetValue("err_code_des").ToSafeString();
                if (string.IsNullOrEmpty(returnMsg))
                {
                    returnMsg = result.GetValue("return_msg").ToSafeString();
                }

                //如果返回错误码为“此交易订单号不存在”,直接失败
                if (result.GetValue("err_code").ToString() == "ORDERNOTEXIST")
                {
                    //触发回调函数
                    PayFactory.OnPayFailed(parameter.TradeID, returnMsg, xml);
                    return(true);
                }
                else if (result.GetValue("err_code").ToString() == "SYSTEMERROR")
                {
                    //如果是系统错误,则后续继续
                    return(false);
                }
                else if (result.GetValue("return_code").ToString() == "FAIL" ||
                         result.GetValue("result_code").ToString() == "FAIL")
                {
                    //FAIL
                    //触发回调函数
                    PayFactory.OnPayFailed(parameter.TradeID, returnMsg, xml);
                    return(true);
                }
            }
            catch
            {
            }
            return(false);
        }
Exemple #23
0
        public override string BeginPay(PayParameter parameter)
        {
            if (string.IsNullOrEmpty(parameter.AuthCode))
            {
                throw new Exception("请把PayParameter.AuthCode设置为客户端ip");
            }
            var config = new Config(PayFactory.GetInterfaceXmlConfig(PayInterfaceType.WeiXinH5, parameter.TradeID));
            SortedDictionary <string, string> postDict = new SortedDictionary <string, string>();

            postDict["appid"]            = config.AppID;
            postDict["mch_id"]           = config.MchID;
            postDict["nonce_str"]        = Guid.NewGuid().ToString().Replace("-", ""); //随机字符串
            postDict["body"]             = parameter.Description;                      //交易描述
            postDict["out_trade_no"]     = parameter.TradeID;
            postDict["total_fee"]        = ((int)(parameter.Amount * 100)).ToString(); //单位:分
            postDict["spbill_create_ip"] = parameter.AuthCode;                         //终端ip
            if (string.IsNullOrEmpty(parameter.NotifyDomain))
            {
                postDict["notify_url"] = "http://paysdk.weixin.qq.com/example/ResultNotifyPage.aspx";
            }
            else
            {
                postDict["notify_url"] = $"{parameter.NotifyDomain}/{WeiXinNotify_RequestHandler.NotifyPageName}";
            }

            postDict["trade_type"] = "MWEB";
            postDict["sign_type"]  = "MD5";
            postDict["time_start"] = DateTime.Now.ToString("yyyyMMddHHmmss");//交易起始时间
            if (parameter.ExpireTime != null)
            {
                postDict["time_expire"] = parameter.ExpireTime.Value.ToString("yyyyMMddHHmmss");//交易结束时间
            }
            else
            {
                //默认十分钟
                postDict["time_expire"] = DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss");//交易结束时间
            }
            postDict["scene_info"] = Newtonsoft.Json.JsonConvert.SerializeObject(new { h5_info = new { type = "Wap", wap_url = $"{PayFactory.CurrentDomainUrl}/", wap_name = "H5Pay" } });
            postDict["sign"]       = Helper.GetMd5Hash(postDict, config.Key);

            var xml = ToXml(postDict);

            var result = Helper.PostXml(ServerUrl, xml, parameter.RequestTimeout);

            PayFactory.OnLog(parameter.TradeID, LogEventType.ReceivePayResult, result);

            XDocument xmldoc = XDocument.Parse(result);

            CheckSign(xmldoc, config);

            var return_code = xmldoc.Root.XPathSelectElement("return_code").Value;
            var return_msg  = xmldoc.Root.XPathSelectElement("return_msg").Value;

            if (return_code == "FAIL")
            {
                throw new Exception(return_msg);
            }
            else if (return_code == "SUCCESS" && return_msg == "OK")
            {
                return(xmldoc.Root.XPathSelectElement("mweb_url").Value);
            }
            return(null);
        }