Ejemplo n.º 1
0
 private static XmlDocument SendGoodsRequest(string url)
 {
     try
     {
         HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
         request.Timeout = 0x1388;
         HttpWebResponse response = (HttpWebResponse)request.GetResponse();
         StringBuilder   builder  = new StringBuilder();
         using (Stream stream = response.GetResponseStream())
         {
             using (StreamReader reader = new StreamReader(stream, Encoding.Default))
             {
                 while (-1 != reader.Peek())
                 {
                     builder.Append(reader.ReadLine());
                 }
             }
         }
         XmlDocument document = new XmlDocument();
         document.LoadXml(builder.ToString());
         return(document);
     }
     catch (Exception exception)
     {
         PayLog.AppendLog(null, "", url, exception.Message, LogType.Alipay_Assure);
         return(null);
     }
 }
Ejemplo n.º 2
0
        public string GetSignInfo(string subject, string body, string notifyUrl, PayLog payLog, Payment payment, Dictionary <string, string> param = null)
        {
            var config = _configService.Get <WeiXinConfig>();

            WxPayData data = new WxPayData();

            data.SetValue("body", body);
            data.SetValue("out_trade_no", payLog.TransactionNo);
            data.SetValue("total_fee", Convert.ToInt32(payLog.OrderAmount * 100));
            data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));
            data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss"));
            data.SetValue("goods_tag", body);
            data.SetValue("trade_type", "APP");
            data.SetValue("nonce_str", WxPayApi.GenerateNonceStr());
            data.SetValue("notify_url", notifyUrl);

            WeiXinPayConfig weiXinPayConfig = new WeiXinPayConfig()
            {
                APPID = config.AppId, MCHID = config.MchId, KEY = config.Key
            };
            WxPayData result = WxPayApi.UnifiedOrder(data, 6, weiXinPayConfig);

            WxPayData reSignWxPayData = new WxPayData();

            reSignWxPayData.SetValue("appid", result.GetValue("appid"));
            reSignWxPayData.SetValue("partnerid", result.GetValue("mch_id"));
            reSignWxPayData.SetValue("prepayid", result.GetValue("prepay_id"));
            reSignWxPayData.SetValue("noncestr", result.GetValue("nonce_str"));
            reSignWxPayData.SetValue("timestamp", WxPayApi.GenerateTimeStamp());
            reSignWxPayData.SetValue("package", "Sign=WXPay");
            reSignWxPayData.SetValue("sign", reSignWxPayData.MakeSign(weiXinPayConfig.KEY));
            return(reSignWxPayData.ToJson());
        }
Ejemplo n.º 3
0
        public void VerifyReturn(int timeout, string configXml)
        {
            XmlDocument document = new XmlDocument();

            document.LoadXml(configXml);
            Dictionary <string, string> dict = new Dictionary <string, string>();

            foreach (string str in this.parameters.AllKeys)
            {
                if (((str != "sign") && (str != "sign_type")) && (str.ToLower() != "higw"))
                {
                    dict.Add(str, this.parameters[str]);
                }
            }
            string prestr = BuildQuery(dict, false) + document.FirstChild.SelectSingleNode("Key").InnerText;
            string sign   = Function.Sign(prestr, "MD5", "utf-8");
            string str4   = (this.parameters["sign"] == null) ? "" : this.parameters["sign"].ToLower();

            if (sign != str4)
            {
                PayLog.writeLog_Collection(this.parameters, sign, "", "验签失败Return---" + document.FirstChild.SelectSingleNode("Key").InnerText + "---" + prestr, LogType.WS_WapPay);
                this.OnNotifyVerifyFaild();
            }
            else if (this.trade_status.ToLower() != "success")
            {
                PayLog.writeLog_Collection(this.parameters, sign, "", "通知结果不为成功---" + prestr, LogType.WS_WapPay);
                this.OnNotifyVerifyFaild();
            }
            else
            {
                this.OnFinished(false);
            }
        }
Ejemplo n.º 4
0
        public string GetSignInfo(string subject, string body, string notifyUrl, PayLog payLog, Payment payment, Dictionary <string, string> param = null)
        {
            if (body.Length > 512)
            {
                body = body.Substring(0, 500) + "...";
            }

            var alipayConfig = _configService.Get <AlipayConfig>();

            var config = new AlipayConfig2
            {
                Partner  = alipayConfig.Partner,
                SellerId = alipayConfig.SellerId,
                Md5Key   = alipayConfig.MD5Key,
                SignType = SignType.MD5
            };

            var paras = new SortedDictionary <string, string>();

            paras.Add("partner", config.Partner);
            paras.Add("seller_id", config.SellerId);
            paras.Add("out_trade_no", payLog.TransactionNo);
            paras.Add("subject", subject);
            paras.Add("body", body);
            paras.Add("total_fee", payLog.OrderAmount.ToString());
            paras.Add("notify_url", notifyUrl);
            paras.Add("service", "mobile.securitypay.pay");
            paras.Add("payment_type", "1");
            paras.Add("_input_charset", "utf-8");
            paras.Add("it_b_pay", "30m");

            var sPara = new Submit(config).BuildRequestPara(paras);

            return(Core.CreateLinkStringUrlencode(sPara, Encoding.UTF8));
        }
        public override void SendRequest()
        {
            Dictionary <string, string> data = new Dictionary <string, string>();

            BUConfig.MerId         = SDKConfig.MerId = this.Vmid;
            SDKConfig.SignCertPwd  = this.Key;
            SDKConfig.signCertPath = Path.Combine(SDKConfig.validateCertDir, this.SignCertFileName);
            BUConfig.CertId        = CertUtil.GetSignCertId();
            data.Add("version", BUConfig.Version);
            data.Add("encoding", BUConfig.Encoding);
            data.Add("certId", BUConfig.CertId);
            data.Add("signMethod", BUConfig.SignMethod);
            data.Add("txnType", BUConfig.TxnType);
            data.Add("txnSubType", BUConfig.TxnSubType);
            data.Add("bizType", BUConfig.BizType);
            data.Add("channelType", BUConfig.ChannelType);
            data.Add("frontUrl", BUConfig.FrontUrl);
            data.Add("backUrl", BUConfig.BackUrl);
            data.Add("accessType", BUConfig.AccessType);
            data.Add("merId", BUConfig.MerId);
            data.Add("orderId", BUConfig.OrderId);
            data.Add("txnTime", BUConfig.TxnTime);
            data.Add("txnAmt", BUConfig.TxnAmt);
            data.Add("currencyCode", BUConfig.CurrencyCode);
            data.Add("userMac", "userMac");
            SDKUtil.Sign(data, Encoding.UTF8);
            string msg = SDKUtil.CreateAutoSubmitForm("https://gateway.95516.com/gateway/api/frontTransReq.do", data, Encoding.UTF8);

            PayLog.writeLog(data, "", "", msg, LogType.BankUnion_GateWay);
            this.SubmitPaymentForm(msg);
        }
Ejemplo n.º 6
0
        public override void VerifyNotify(int timeout, string configXml)
        {
            string str   = this._parameters["Name"];
            string str2  = this._parameters["Version"];
            string str3  = this._parameters["Charset"];
            string str4  = this._parameters["TraceNo"];
            string str5  = this._parameters["MsgSender"];
            string str6  = this._parameters["SendTime"];
            string str7  = this._parameters["InstCode"];
            string str8  = this._parameters["OrderNo"];
            string str9  = this._parameters["OrderAmount"];
            string str10 = this._parameters["TransNo"];
            string str11 = this._parameters["TransAmount"];
            string str12 = this._parameters["TransStatus"];
            string str13 = this._parameters["TransType"];
            string str14 = this._parameters["TransTime"];
            string str15 = this._parameters["MerchantNo"];
            string str16 = this._parameters["PaymentNo"];
            string str17 = this._parameters["ErrorCode"];
            string str18 = this._parameters["ErrorMsg"];
            string str19 = this._parameters["PayableFee"];
            string str20 = this._parameters["ReceivableFee"];
            string str21 = this._parameters["PayChannel"];
            string str22 = this._parameters["Ext1"];
            string str23 = this._parameters["BankSerialNo"];
            string str24 = this._parameters["SignType"];
            string str25 = this._parameters["SignMsg"];

            try
            {
                IDictionary <string, string> param = new Dictionary <string, string>();
                foreach (string str26 in this._parameters.AllKeys)
                {
                    param.Add(str26, this._parameters[str26]);
                }
                string      msg      = "";
                XmlDocument document = new XmlDocument();
                document.LoadXml(configXml);
                string innerText = document.FirstChild.SelectSingleNode("Key").InnerText;
                string str30     = str + str2 + str3 + str4 + str5 + str6 + str7 + str8 + str9 + str10 + str11 + str12 + str13 + str14 + str15 + str17 + str18 + str22 + str24;
                msg = str30;
                string sign  = FormsAuthentication.HashPasswordForStoringInConfigFile(str30 + innerText, "MD5");
                string str32 = msg;
                msg = str32 + "|status:" + str12 + "|sign:" + sign + "|mac:" + str25;
                if ((str12 != "01") || (str25 != sign))
                {
                    PayLog.AppendLog(param, sign, "", msg, LogType.ShengPay);
                    this.OnNotifyVerifyFaild();
                }
                else
                {
                    this.OnFinished(false);
                }
            }
            catch (Exception exception)
            {
                this.writeXML(configXml, exception.Message + exception.StackTrace);
            }
        }
Ejemplo n.º 7
0
    protected void BtnAlipay_Click(object sender, EventArgs e)
    {
        ////////////////////////////////////////////请求参数////////////////////////////////////////////


        //商户订单号,商户网站订单系统中唯一订单号,必填
        string out_trade_no = WIDout_trade_no.Text.Trim();

        //订单名称,必填
        string subject = WIDsubject.Text.Trim();

        //付款金额,必填
        string total_fee = WIDtotal_fee.Text.Trim();

        //收银台页面上,商品展示的超链接,必填
        string show_url = WIDshow_url.Text.Trim();

        //商品描述,可空
        string body = WIDbody.Text.Trim();

        PayLog.PayLogWrite(Guid.NewGuid().ToString(), "0", out_trade_no, "paysend", "zfb", decimal.Parse(total_fee), DateTime.Now, "", subject, DateTime.Now);


        ////////////////////////////////////////////////////////////////////////////////////////////////

        //把请求参数打包成数组
        SortedDictionary <string, string> sParaTemp = new SortedDictionary <string, string>();

        sParaTemp.Add("partner", Config.partner);
        sParaTemp.Add("seller_id", Config.seller_id);
        sParaTemp.Add("_input_charset", Config.input_charset.ToLower());
        sParaTemp.Add("service", Config.service);
        sParaTemp.Add("payment_type", Config.payment_type);
        sParaTemp.Add("notify_url", Config.notify_url);
        sParaTemp.Add("return_url", Config.return_url);
        sParaTemp.Add("out_trade_no", out_trade_no);
        sParaTemp.Add("subject", subject);
        sParaTemp.Add("total_fee", total_fee);
        sParaTemp.Add("show_url", show_url);
        //sParaTemp.Add("app_pay","Y");//启用此参数可唤起钱包APP支付。
        sParaTemp.Add("body", body);
        //其他业务参数根据在线开发文档,添加参数.文档地址:https://doc.open.alipay.com/doc2/detail.htm?spm=a219a.7629140.0.0.2Z6TSk&treeId=60&articleId=103693&docType=1
        //如sParaTemp.Add("参数名","参数值");

        //建立请求
        string sHtmlText = Submit.BuildRequest(sParaTemp, "get", "确认");

        Response.Write(sHtmlText);
    }
Ejemplo n.º 8
0
        /// <summary>
        /// 发送获取code请求
        /// 微信支付入口
        /// </summary>
        /// <returns></returns>
        public ActionResult GetWXCode(string id)
        {
            Session["orderid"] = id;
            var myurl = Request.Url.Scheme + "://" + Request.Url.Host + "/tenpay/ResponseParam";//获取code的地址
            var appid = WxPayConfig.APPID;
            var url   = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect", appid, myurl);

            #region 日志
            PayLog model = new PayLog();
            model.ID      = FCake.Core.Common.DataHelper.GetSystemID();
            model.LogTime = DateTime.Now;
            model.Message = "取code的url:" + url;
            log.Add(model);
            #endregion
            return(Redirect(url));
        }
        public override void VerifyNotify(int timeout, string configXml)
        {
            bool        flag;
            XmlDocument document = new XmlDocument();

            document.LoadXml(configXml);
            try
            {
                flag = bool.Parse(this.GetResponse(this.CreateUrl(document.FirstChild), timeout));
            }
            catch (Exception exception)
            {
                PayLog.writeLog_Collection(this.parameters, this.GetResponse(this.CreateUrl(document.FirstChild), timeout) + "-" + this.CreateUrl(document.FirstChild), HttpContext.Current.Request.Url.ToString(), exception.Message, LogType.Alipay_Direct);
                flag = false;
            }
            this.parameters.Remove("HIGW");
            string[] strArray2 = Globals.BubbleSort(this.parameters.AllKeys);
            string   s         = "";

            for (int i = 0; i < strArray2.Length; i++)
            {
                if ((!string.IsNullOrEmpty(this.parameters[strArray2[i]]) && (strArray2[i] != "sign")) && (strArray2[i] != "sign_type"))
                {
                    if (i == (strArray2.Length - 1))
                    {
                        s = s + strArray2[i] + "=" + this.parameters[strArray2[i]];
                    }
                    else
                    {
                        s = s + strArray2[i] + "=" + this.parameters[strArray2[i]] + "&";
                    }
                }
            }
            s    = s + document.FirstChild.SelectSingleNode("Key").InnerText;
            flag = flag && this.parameters["sign"].Equals(Globals.GetMD5(s, "utf-8"));
            string str2 = this.parameters["trade_status"];

            if (flag && ((str2 == "TRADE_SUCCESS") || (str2 == "TRADE_FINISHED")))
            {
                this.OnFinished(false);
            }
            else
            {
                PayLog.AppendLog_Collection(this.parameters, this.parameters["sign"], Globals.GetMD5(s, "utf-8"), "签名验证失败", LogType.Alipay_Direct);
                this.OnNotifyVerifyFaild();
            }
        }
Ejemplo n.º 10
0
        private void SavePayLog(ViewModel.PaymentViewModel model)
        {
            var paylog = new PayLog();

            paylog.OrderId = model.OrderModel.OrderId;
            //paylog.TransactionId = model.OrderModel.TradeNo;
            paylog.UserId     = model.OrderModel.UserId;
            paylog.PayWay     = (int)PayWay.UnionPay;
            paylog.PayMoney   = model.OrderModel.Total;
            paylog.PayUrl     = "";
            paylog.BackUrl    = model.BackCallbackUrl;
            paylog.PayResult  = "前往支付";
            paylog.CreateTime = DateTime.Now;

            _uow.PayLogService.Add(paylog);
            _uow.Commit();
        }
Ejemplo n.º 11
0
        public override void VerifyNotify(int timeout, string configXml)
        {
            XmlDocument document = new XmlDocument();

            document.LoadXml(configXml);
            string innerText = document.FirstChild.SelectSingleNode("AppSecret").InnerText;

            if (this.GetMD5String(this.CoverDictionaryToString(this.nofifyData) + "&key=" + innerText).ToUpper().Equals(this.sign))
            {
                this.OnFinished(false);
            }
            else
            {
                PayLog.AppendLog(null, configXml, "4", string.Concat(new object[] { "sign:", this.sign, "-", this.sign.Length }), LogType.WXQRCode);
                this.OnNotifyVerifyFaild();
            }
        }
Ejemplo n.º 12
0
        public void AddPayLog(bool isNotify)
        {
            PayLog log = new PayLog();

            log.ID      = DataHelper.GetSystemID();
            log.OrderNo = Request.QueryString["out_trade_no"];
            if (isNotify)
            {
                log.Message = Request.Form.ToString();
            }
            else
            {
                log.Message = Request.Url.ToString();;
            }
            log.LogTime = DateTime.Now;
            PayLogService ps = new PayLogService();

            ps.Add(log);
        }
Ejemplo n.º 13
0
 /// <summary>
 /// 接收code参数
 /// </summary>
 /// <returns></returns>
 public ActionResult ResponseParam()
 {
     try
     {
         var code = Request["code"];
         if (code != null)
         {
             Session["code"] = code;
         }
         return(Redirect("/Tenpay/WXPay/" + Session["orderid"]));
     }
     catch (Exception e)
     {
         PayLog model = new PayLog();
         model.ID      = FCake.Core.Common.DataHelper.GetSystemID();
         model.LogTime = DateTime.Now;
         model.Message = "error:" + e.Message;
         log.Add(model);
         return(Redirect("/"));
     }
 }
Ejemplo n.º 14
0
 public override void VerifyNotify(int timeout, string configXml)
 {
     try
     {
         string str  = this.parameters["v_oid"];
         string str2 = this.parameters["v_pstatus"];
         string str3 = this.parameters["v_pstring"];
         string str4 = this.parameters["v_pmode"];
         string str5 = this.parameters["v_md5str"];
         string str6 = this.parameters["v_amount"];
         string str7 = this.parameters["v_moneytype"];
         string str8 = this.parameters["remark1"];
         if (((((str == null) || (str2 == null)) || ((str3 == null) || (str4 == null))) || (((str5 == null) || (str6 == null)) || (str8 == null))) || (str7 == null))
         {
             PayLog.AppendLog_Collection(this.parameters, "", "1", configXml, LogType.ChinaBank);
             this.OnNotifyVerifyFaild();
             return;
         }
         if (!str2.Equals("20"))
         {
             PayLog.AppendLog_Collection(this.parameters, "", "2", configXml, LogType.ChinaBank);
             this.OnNotifyVerifyFaild();
             return;
         }
         XmlDocument document = new XmlDocument();
         document.LoadXml(configXml);
         string str9 = FormsAuthentication.HashPasswordForStoringInConfigFile(str + str2 + str6 + str7 + document.FirstChild.SelectSingleNode("Key").InnerText, "MD5").ToUpper(CultureInfo.InvariantCulture);
         if (!str5.Equals(str9))
         {
             PayLog.AppendLog_Collection(this.parameters, str9, "3", configXml, LogType.ChinaBank);
             this.OnNotifyVerifyFaild();
             return;
         }
     }
     catch (Exception exception)
     {
         PayLog.AppendLog_Collection(this.parameters, "", "3", configXml + "---" + exception.Message, LogType.ChinaBank);
     }
     this.OnFinished(false);
 }
Ejemplo n.º 15
0
 public override void VerifyNotify(int timeout, string configXml)
 {
     if (!this.IsNotify)
     {
         this.VerifyReturn(timeout, configXml);
     }
     else
     {
         XmlDocument document = new XmlDocument();
         document.LoadXml(configXml);
         this.parameters.Remove("HIGW");
         string[] allKeys = this.parameters.AllKeys;
         Dictionary <string, string> dictionary = new Dictionary <string, string>();
         foreach (string str in this.parameters.AllKeys)
         {
             if ((str != "sign") && (str != "sign_type"))
             {
                 dictionary.Add(str, this.parameters[str]);
             }
         }
         string prestr = "service=" + this.parameters["service"] + "&v=" + this.parameters["v"] + "&sec_id=" + this.parameters["sec_id"] + "&notify_data=" + this.parameters["notify_data"] + document.FirstChild.SelectSingleNode("Key").InnerText.Trim();
         string sign   = Function.Sign(prestr, "MD5", "utf-8");
         string str4   = (this.parameters["sign"] == null) ? "" : this.parameters["sign"].ToLower();
         if (!(str4 == sign))
         {
             PayLog.writeLog_Collection(this.parameters, sign, "", "验签失败Return---" + document.FirstChild.SelectSingleNode("Key").InnerText + "---" + prestr, LogType.WS_WapPay);
             this.OnNotifyVerifyFaild();
         }
         else if (this.trade_status.ToLower() != "trade_success")
         {
             PayLog.writeLog_Collection(this.parameters, sign, "", "通知结果不为成功---" + prestr, LogType.WS_WapPay);
             this.OnNotifyVerifyFaild();
         }
         else
         {
             this.OnFinished(false);
         }
     }
 }
Ejemplo n.º 16
0
        public virtual async Task UpdateApprovalAsync(ApprovalEditDto input)
        {
            //TODO:更新前的逻辑判断,是否允许更新

            var entity = await _approvalRepository.GetAsync(input.Id.Value);

            if (entity == null)
            {
                return;
            }
            Approval _approval = input.MapTo(entity);

            _approval.IsPay  = true;
            _approval.IsShow = true;
            await _approvalRepository.UpdateAsync(entity);

            PayLog _payLog = new PayLog();

            _payLog.CompanyID = _approval.CompanyID;
            _payLog.CoopTime  = Convert.ToInt32(_approval.CoopTime);
            _payLog.PayAmount = Convert.ToInt32(_approval.PayAmount);
            _payLog.PayTime   = Convert.ToDateTime(_approval.PayTime);
            await _paylogRepository.InsertAsync(_payLog);
        }
Ejemplo n.º 17
0
        public string SyncReturn(HttpRequestBase request)
        {
            var payment = _paymentService.LoadPayment(PaymentType.WeiXin.ToString());
            var config  = _configService.Get <WeiXinConfig>();

            WxPayData notifyData = GetNotifyData(request, config.Key);

            //检查支付结果中transaction_id是否存在
            if (!notifyData.IsSet("transaction_id"))
            {
                //若transaction_id不存在,则立即返回结果给微信支付后台
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", "支付结果中微信订单号不存在");
                Log.Error(this.GetType().ToString(), "The Pay result is error : " + res.ToXml());
                return("支付结果中微信订单号不存在");
            }

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

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

            //查询订单,判断订单真实性
            if (!QueryOrder(transaction_id))
            {
                //若订单查询失败,则立即返回结果给微信支付后台
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", "订单查询失败");
                Log.Error(this.GetType().ToString(), "Order query failure : " + res.ToXml());
                return("订单查询失败");
            }
            //查询订单成功
            else
            {
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "SUCCESS");
                res.SetValue("return_msg", "OK");
                Log.Info(this.GetType().ToString(), "order query success : " + res.ToXml());

                PayLog payLog = _currencyService.GetSingleByConditon <PayLog>(o => o.TransactionNo == out_trade_no);
                if (payLog != null)
                {
                    using (TransactionScope scope = new TransactionScope())
                    {
                        payLog.PayTime   = DateTime.Now;
                        payLog.LogStatus = LogStatus.Paid;
                        _currencyService.Update(payLog);
                        Order order = _currencyService.GetSingleByConditon <Order>(o => o.Id == payLog.OrderId);
                        order.PayStatus   = PayStatus.Paid;
                        order.PayTime     = DateTime.Now;
                        order.PaymentId   = payment.Id;
                        order.PaymentName = payment.Name;
                        order.OrderStatus = OrderStatus.WaitingForDelivery;
                        _orderService.ChangeOrderStatus(order.Id, order.OrderStatus, order.PayStatus);
                        _currencyService.Update(order);

                        var orderAction = new OrderAction
                        {
                            Id             = KeyGenerator.GetGuidKey(),
                            OrderId        = order.Id,
                            Memo           = "微信支付",
                            CreateTime     = DateTime.Now,
                            OrderStatus    = order.OrderStatus,
                            PayStatus      = order.PayStatus,
                            ShippingStatus = order.ShippingStatus,
                            EvaluateStatus = order.EvaluateStatus,
                            UserId         = order.MemberId,
                            UserName       = order.MemberName
                        };
                        _currencyService.Create(orderAction);
                        //提交
                        scope.Complete();
                    }
                }

                return("OK");
            }
        }
Ejemplo n.º 18
0
        public string H5Pay(string subject, string body, string notifyUrl, string returnUrl, PayLog payLog, Payment payment,
                            Dictionary <string, string> param = null)
        {
            var config = _configService.Get <WeiXinConfig>();

            WxPayData data = new WxPayData();

            data.SetValue("body", body);
            data.SetValue("out_trade_no", payLog.TransactionNo);
            data.SetValue("total_fee", Convert.ToInt32(payLog.OrderAmount * 100));
            data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));
            data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss"));
            data.SetValue("goods_tag", body);
            data.SetValue("trade_type", "WAP");
            data.SetValue("nonce_str", WxPayApi.GenerateNonceStr());
            data.SetValue("notify_url", notifyUrl);

            WeiXinPayConfig weiXinPayConfig = new WeiXinPayConfig()
            {
                APPID = config.AppId, MCHID = config.MchId, KEY = config.Key
            };
            WxPayData result = WxPayApi.UnifiedOrder(data, 6, weiXinPayConfig);

            if (result.GetValue("return_code").ToString().Equals("fail", StringComparison.OrdinalIgnoreCase))
            {
                return(result.GetValue("return_msg").ToString());
            }

            WxPayData reSignWxPayData = new WxPayData();

            reSignWxPayData.SetValue("appid", result.GetValue("appid"));
            reSignWxPayData.SetValue("partnerid", result.GetValue("mch_id"));
            reSignWxPayData.SetValue("prepayid", result.GetValue("prepay_id"));
            reSignWxPayData.SetValue("noncestr", result.GetValue("nonce_str"));
            reSignWxPayData.SetValue("timestamp", WxPayApi.GenerateTimeStamp());
            reSignWxPayData.SetValue("package", "WAP");
            reSignWxPayData.SetValue("sign", reSignWxPayData.MakeSign(weiXinPayConfig.KEY));

            var deepLink = $"weixin://wap/pay?{HttpUtility.UrlEncode(reSignWxPayData.ToUrl())}";

            return($"<script>location.href='{deepLink}';</script>");
        }
Ejemplo n.º 19
0
        public string WebPay(string subject, string body, string notifyUrl, string returnUrl, PayLog payLog, Payment payment,
                             Dictionary <string, string> param = null)
        {
            //统一下单
            var config = _configService.Get <WeiXinConfig>();

            WxRequestHandler packageReqHandler = new WxRequestHandler(null);
            var nonceStr = TenPayV3Util.GetNoncestr();
            //商品Id,用户自行定义
            string productId = DateTime.Now.ToString("yyyyMMddHHmmss");

            //创建请求统一订单接口参数
            packageReqHandler.SetParameter("appid", config.AppId);
            packageReqHandler.SetParameter("mch_id", config.MchId);
            packageReqHandler.SetParameter("nonce_str", nonceStr);
            packageReqHandler.SetParameter("body", body);
            packageReqHandler.SetParameter("out_trade_no", payLog.TransactionNo);
            packageReqHandler.SetParameter("total_fee", Convert.ToInt32(payLog.OrderAmount * 100).ToString());
            packageReqHandler.SetParameter("spbill_create_ip", "127.0.0.1");
            packageReqHandler.SetParameter("notify_url", notifyUrl);
            packageReqHandler.SetParameter("trade_type", TenPayV3Type.NATIVE.ToString());
            packageReqHandler.SetParameter("product_id", productId);
            string sign = packageReqHandler.CreateMd5Sign("key", config.Key);

            packageReqHandler.SetParameter("sign", sign);
            string data = packageReqHandler.ParseXML();

            //调用统一订单接口
#pragma warning disable 618
            var result = TenPayV3.Unifiedorder(data);
#pragma warning restore 618
            var    unifiedorderRes = XDocument.Parse(result);
            string codeUrl         = unifiedorderRes.Element("xml")?.Element("code_url")?.Value;
            return(codeUrl);
        }
Ejemplo n.º 20
0
    protected void Page_Load(object sender, EventArgs e)
    {
        SortedDictionary <string, string> sPara = GetRequestPost();

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

            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"];


                string remarks = "【支付宝服务器异步通知】[return_url.aspx]支付宝返回值(out_trade_no=" + Request.Form["out_trade_no"] + ",trade_no=" + Request.Form["trade_no"] + ",trade_status=" + Request.Form["trade_status"] + ")";

                StarTech.DBUtility.AdoHelper adoHelper = StarTech.DBUtility.AdoHelper.CreateHelper("DB_Instance");

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

                    //注意:
                    //退款日期超过可退款期限后(如三个月可退款),支付宝系统发送该交易状态通知
                    object objMoney = adoHelper.ExecuteSqlScalar(" select top 1 paymoney from T_Order_PayLog where payStatu='paysend' and orderId='" + out_trade_no + "' order by payTime desc");
                    if (objMoney != null)
                    {
                        adoHelper.ExecuteSqlNonQuery("update T_Order_Info set isPay=1 , payTime=getdate() where isPay=0 and orderId='" + out_trade_no + "'");

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

                    //注意:
                    //付款完成后,支付宝系统发送该交易状态通知
                    object objMoney = adoHelper.ExecuteSqlScalar(" select top 1 paymoney from T_Order_PayLog where payStatu='paysend' and orderId='" + out_trade_no + "' order by payTime desc");
                    if (objMoney != null)
                    {
                        adoHelper.ExecuteSqlNonQuery("update T_Order_Info set isPay=1 , payTime=getdate() where isPay=0 and orderId='" + out_trade_no + "'");
                        adoHelper.ExecuteSqlNonQuery("update T_Goods_Info set JobStatus='进行中' where goodsId=(select goodsId from T_Order_InfoDetail where orderId='" + out_trade_no + "')");
                        PayLog.PayLogWrite(Guid.NewGuid().ToString(), "0", out_trade_no, "pay", "zfb", decimal.Parse(objMoney.ToString()), DateTime.Now, trade_no, remarks, DateTime.Now);
                    }
                }
                else
                {
                    PayLog.PayLogWrite(Guid.NewGuid().ToString(), "0", out_trade_no, "other", "zfb", 0, DateTime.Now, trade_no, remarks, DateTime.Now);
                }

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

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

                /////////////////////////////////////////////////////////////////////////////////////////////////////////////
            }
            else//验证失败
            {
                Response.Write("fail");
            }
        }
        else
        {
            Response.Write("无通知参数");
        }
    }
Ejemplo n.º 21
0
        public ApiResult GetWxPayJsApiParam([FromBody] PayViewModel payModel)
        {
            var orderId = payModel.OrderId;

            if (orderId.Equals(Guid.Empty))
            {
                throw new WebApiInnerException("0001", "订单Id不合法");
            }
            var order = _currencyService.GetSingleById <Order>(orderId);

            if (order == null)
            {
                throw new WebApiInnerException("0002", "订单数据不存在");
            }
            if (order.PayStatus != PayStatus.Unpaid)
            {
                throw new WebApiInnerException("0003", "订单状态不合理,无法支付");
            }
            var payment = _paymentService.LoadPayment(PaymentType.WeiXin.ToString());

            if (payment == null || !payment.Enabled)
            {
                throw new WebApiInnerException("0004", "支付方式不合法或已停用");
            }
            var paymentDispatcher = HostConstObject.Container.ResolveNamed <IPaymentDispatcher>(payment.Code.ToLower());

            if (paymentDispatcher == null)
            {
                throw new WebApiInnerException("0005", "支付方式不合法");
            }

            var oath = _currencyService.GetSingleByConditon <UserOAuth>(ua => ua.MemberId == order.MemberId && ua.OAuthType == OAuthType.WeiXin);

            if (oath == null)
            {
                throw new WebApiInnerException("0008", "未绑定微信号,无法支付");
            }

            var result = new ApiResult();

            try
            {
                var routeParas = new RouteValueDictionary {
                    { "area", PaymentProcessModule.Area },
                    { "controller", "Receive" },
                    { "action", "AsyncReturn" },
                    { "paymentCode", payment.Code }
                };
                var notifyUrl = HostConstObject.HostUrl + _urlHelper.RouteUrl(routeParas);
                if (payModel.UseBalance == 1)
                {
                    //使用余额付款
                    #region
                    using (TransactionScope scope = new TransactionScope())
                    {
                        var cashWallet = _walletService.GetWalletByMemberId(order.MemberId,
                                                                            Wallet.Models.WalletType.Cash);
                        if (cashWallet != null && cashWallet.Available > 0)
                        {
                            if (cashWallet.Available > order.PayFee)
                            {
                                string error;
                                _walletService.Draw(order.MemberId, Wallet.Models.WalletType.Cash, order.PayFee,
                                                    "支付订单" + order.OrderNo, out error);
                                if (string.IsNullOrWhiteSpace(error))
                                {
                                    order.BalancePay  = order.PayFee;
                                    order.OrderStatus = OrderStatus.WaitingForDelivery;
                                    order.PayStatus   = PayStatus.Paid;
                                    order.PayTime     = DateTime.Now;

                                    var balancePayment = _paymentService.LoadPayment(PaymentType.Balance.ToString());
                                    order.PaymentId   = balancePayment.Id;
                                    order.PaymentName = balancePayment.Name;
                                    _orderService.ChangeOrderStatus(order.Id, order.OrderStatus, order.PayStatus);
                                    _currencyService.Update(order);
                                }
                            }
                            else
                            {
                                string error;
                                _walletService.Draw(order.MemberId, Wallet.Models.WalletType.Cash,
                                                    cashWallet.Available,
                                                    "支付订单" + order.OrderNo, out error);
                                if (string.IsNullOrWhiteSpace(error))
                                {
                                    order.UnpayFee   = order.PayFee - cashWallet.Available;
                                    order.BalancePay = cashWallet.Available;
                                    _currencyService.Update(order);
                                }
                            }
                        }
                        scope.Complete();
                    }
                    #endregion
                }
                var payLog = new PayLog
                {
                    Id            = KeyGenerator.GetGuidKey(),
                    TransactionNo = $"{order.OrderNo}{KeyGenerator.GenerateRandom(1000, 1)}",
                    OrderId       = order.Id,
                    OrderNo       = order.OrderNo,
                    OrderAmount   = order.PayFee,//UnpayFee
                    PaymentId     = payment.Id,
                    PaymentName   = payment.Name,
                    CreateTime    = DateTime.Now,
                    LogStatus     = LogStatus.Unpaid
                };
                if (!_currencyService.Create(payLog))
                {
                    throw new WebApiInnerException("0007", "生成支付流水失败");
                }

                string timeStamp = "";
                string nonceStr  = "";
                string paySign   = "";

                var appId = _configService.Get <WeiXinConfig>().AppId;
                var mchId = _configService.Get <WeiXinConfig>().MchId;
                var key   = _configService.Get <WeiXinConfig>().Key;

                //创建支付应答对象
                WxRequestHandler packageReqHandler = new WxRequestHandler(null);
                //初始化
                packageReqHandler.Init();

                timeStamp = TenPayV3Util.GetTimestamp();
                nonceStr  = TenPayV3Util.GetNoncestr();

                //设置package订单参数
                packageReqHandler.SetParameter("appid", appId);                       //公众账号ID
                packageReqHandler.SetParameter("mch_id", mchId);                      //商户号
                packageReqHandler.SetParameter("nonce_str", nonceStr);                //随机字符串
                packageReqHandler.SetParameter("body", order.OrderNo);                //商品信息
                packageReqHandler.SetParameter("out_trade_no", payLog.TransactionNo); //商家订单号
                packageReqHandler.SetParameter("total_fee", Convert.ToInt32(order.PayFee * 100).ToString());
                //商品金额,以分为单位(money * 100).ToString()
                packageReqHandler.SetParameter("spbill_create_ip", "127.0.0.1");             //用户的公网ip,不是商户服务器IP
                packageReqHandler.SetParameter("notify_url", notifyUrl);                     //接收财付通通知的URL
                packageReqHandler.SetParameter("trade_type", TenPayV3Type.JSAPI.ToString()); //交易类型
                packageReqHandler.SetParameter("openid", oath.OAuthId);                      //用户的openId

                string sign = packageReqHandler.CreateMd5Sign("key", key);
                packageReqHandler.SetParameter("sign", sign); //签名

                string data        = packageReqHandler.ParseXML();
                var    orderResult = TenPayV3.Unifiedorder(data);
                var    res         = XDocument.Parse(orderResult);
                var    prepayXml   = res.Element("xml").Element("prepay_id");
                if (prepayXml == null)
                {
                    Logger.Error("生成微信预付单失败:" + res.ToString());
                    throw new WebApiInnerException("0009", "生成微信预付单失败");
                    //res.Element("xml").Element("return_msg").Value;
                }
                string prepayId = prepayXml.Value;
                //设置支付参数
                WxRequestHandler paySignReqHandler = new WxRequestHandler(null);
                paySignReqHandler.SetParameter("appId", appId);
                paySignReqHandler.SetParameter("timeStamp", timeStamp);
                paySignReqHandler.SetParameter("nonceStr", nonceStr);
                paySignReqHandler.SetParameter("package", $"prepay_id={prepayId}");
                paySignReqHandler.SetParameter("signType", "MD5");
                paySign = paySignReqHandler.CreateMd5Sign("key", key);

                result.SetData(new { appId, timeStamp, nonceStr, package = $"prepay_id={prepayId}", paySign, signType = "MD5", orderid = order.Id, orderType = order.ModuleKey, orderStatus = order.OrderStatus, payStatus = order.PayStatus });
            }
            catch (Exception ex)
            {
                Logger.Error(ex, "获取订单支付签名数据失败");
                throw new WebApiInnerException("0006", "生成签名数据出现异常");
            }
            return(result);
        }
        public void FastNotice()
        {
            string Resp    = Request.Form["resp"];
            string Sign    = Request.Form["sign"];
            string SignStr = Resp;

            Resp = LokFuEncode.Base64Decode(Resp, "utf-8");
            JObject json = new JObject();

            try
            {
                json = (JObject)JsonConvert.DeserializeObject(Resp);
            }
            catch (Exception Ex)
            {
                Response.Write(Ex.ToString());
                return;
            }
            if (json == null)
            {
                Response.Write("Json Null");
                return;
            }
            string resultcode = json["resultcode"].ToString(); //交易结果码
            string resultmsg  = json["resultmsg"].ToString();  //交易结果信息
            string queryid    = json["queryid"].ToString();    //交易流水号
            string txnamt     = json["txnamt"].ToString();     //交易金额\
            string merid      = json["merid"].ToString();      //交易金额
            string orderid    = json["orderid"].ToString();    //交易金额

            FastOrder FastOrder = Entity.FastOrder.FirstOrDefault(n => n.TNum == orderid);

            if (FastOrder == null)
            {
                Response.Write("E1");
                return;
            }
            if (FastOrder.State != 1)
            {
                Response.Write("E2");
                return;
            }
            if (FastOrder.PayState == 1)
            {
                if (resultcode == "0000")
                {
                    FastOrder.UserState = 1;
                    FastOrder.UserTime  = DateTime.Now;
                }
                if (resultcode == "1002")
                {
                    FastOrder.UserState = 3;
                    FastOrder.UserTime  = DateTime.Now;
                }
                if (resultcode == "1003")
                {
                    FastOrder.UserState = 2;
                    FastOrder.UserTime  = DateTime.Now;
                }
                Entity.SaveChanges();
                Response.Write("0000");
                return;
            }
            FastUserPay FastUserPay = Entity.FastUserPay.FirstOrDefault(o => o.UId == FastOrder.UId && o.PayWay == FastOrder.PayWay);
            string      MerId       = FastUserPay.MerId;
            string      MerKey      = FastUserPay.MerKey;

            if (MerId.IsNullOrEmpty() || MerKey.IsNullOrEmpty())
            {
                Response.Write("E53");
                return;
            }
            string MD5Str = SignStr + MerKey;
            string sign   = MD5Str.GetMD5();
            //================================================
            //这里记录日志
            PayLog PayLog = new PayLog();

            PayLog.PId     = (int)FastOrder.PayWay;
            PayLog.OId     = FastOrder.TNum;
            PayLog.TId     = FastOrder.Trade;
            PayLog.Amount  = decimal.Parse(txnamt) / 100;
            PayLog.Way     = "POST";
            PayLog.AddTime = DateTime.Now;
            PayLog.Data    = Request.Form.ToString();
            PayLog.State   = 1;
            Entity.PayLog.AddObject(PayLog);
            Entity.SaveChanges();
            //================================================
            if (Sign != sign)
            {
                Response.Write("E4");
                return;
            }
            if (MerId != merid)
            {
                Response.Write("E5");
                return;
            }
            //0000 交易成功【已支付,结算到子商户结算卡】
            //1001 未支付
            //1002 交易处理中【已支付,未结算到结算卡】
            //1003交易成功结算失败
            //1004 交易失败
            if (resultcode != "0000" && resultcode != "1002" && resultcode != "1003")
            {
                Response.Write("E6");
                return;
            }
            int factmoney = int.Parse(txnamt);

            if (((int)(FastOrder.Amoney * 100)) != factmoney)
            {
                Response.Write("E7");
                return;
            }
            FastOrder.Trade = queryid;
            Entity.SaveChanges();
            FastOrder = FastOrder.PaySuccess(Entity);
            if (FastOrder.PayState == 1)
            {
                if (resultcode == "0000")
                {
                    FastOrder.UserState = 1;
                    FastOrder.UserTime  = DateTime.Now;
                }
                if (resultcode == "1002")
                {
                    FastOrder.UserState = 3;
                    FastOrder.UserTime  = DateTime.Now;
                }
                if (resultcode == "1003")
                {
                    FastOrder.UserState = 2;
                    FastOrder.UserTime  = DateTime.Now;
                }
                Entity.SaveChanges();
            }
            Response.Write("0000");
        }
        public ActionResult FastResult()
        {
            string Resp    = Request.QueryString["resp"];
            string Sign    = Request.QueryString["sign"];
            string SignStr = Resp;

            Resp = LokFuEncode.Base64Decode(Resp, "utf-8");
            JObject json = new JObject();

            try
            {
                json = (JObject)JsonConvert.DeserializeObject(Resp);
            }
            catch (Exception Ex)
            {
                ViewBag.ErrorMsg = Ex.ToString();
                return(View("Error"));
            }
            if (json == null)
            {
                ViewBag.ErrorMsg = "数据处理出错";
                return(View("Error"));
            }

            string resultcode = json["resultcode"].ToString(); //交易结果码
            string resultmsg  = json["resultmsg"].ToString();  //交易结果信息
            string queryid    = json["queryid"].ToString();    //交易流水号
            string txnamt     = json["txnamt"].ToString();     //交易金额
            string merid      = json["merid"].ToString();      //商户号
            string orderid    = json["orderid"].ToString();    //交易单号

            FastOrder FastOrder = Entity.FastOrder.FirstOrDefault(n => n.TNum == orderid);

            if (FastOrder == null)
            {
                ViewBag.ErrorMsg = "交易不存在!";
                return(View("Error"));
            }
            if (FastOrder.State != 1)
            {
                ViewBag.ErrorMsg = "交易异常!";
                return(View("Error"));
            }
            FastUserPay FastUserPay = Entity.FastUserPay.FirstOrDefault(o => o.UId == FastOrder.UId && o.PayWay == FastOrder.PayWay);
            string      MerId       = FastUserPay.MerId;
            string      MerKey      = FastUserPay.MerKey;

            if (MerId.IsNullOrEmpty() || MerKey.IsNullOrEmpty())
            {
                ViewBag.ErrorMsg = "支付通道配置异常!";
                return(View("Error"));
            }
            string MD5Str = SignStr + MerKey;
            string sign   = MD5Str.GetMD5();
            //================================================
            //这里记录日志
            PayLog PayLog = new PayLog();

            PayLog.PId     = (int)FastOrder.PayWay;
            PayLog.OId     = FastOrder.TNum;
            PayLog.TId     = FastOrder.Trade;
            PayLog.Amount  = decimal.Parse(txnamt) / 100;
            PayLog.Way     = "Result";
            PayLog.AddTime = DateTime.Now;
            PayLog.Data    = Request.Form.ToString();
            PayLog.State   = 1;
            Entity.PayLog.AddObject(PayLog);
            Entity.SaveChanges();
            //================================================
            if (Sign != sign)
            {
                ViewBag.ErrorMsg = "签名错误!";
                return(View("Error"));
            }
            if (MerId != merid)
            {
                ViewBag.ErrorMsg = "商户号不一置!";
                return(View("Error"));
            }
            if (resultcode != "0000" && resultcode != "1002" && resultcode != "1003")
            {
                ViewBag.ErrorMsg = "支付失败![" + resultcode + "]" + resultmsg;
                return(View("Error"));
            }
            int factmoney = int.Parse(txnamt);

            if (((int)(FastOrder.Amoney * 100)) != factmoney)
            {
                ViewBag.ErrorMsg = "支付金额与交易金额不符!";
                return(View("Error"));
            }
            FastOrder.Trade = queryid;
            Entity.SaveChanges();
            FastOrder = FastOrder.PaySuccess(Entity);
            if (FastOrder.PayState == 1)
            {
                if (resultcode == "0000")
                {
                    FastOrder.UserState = 1;
                    FastOrder.UserTime  = DateTime.Now;
                }
                if (resultcode == "1002")
                {
                    FastOrder.UserState = 3;
                    FastOrder.UserTime  = DateTime.Now;
                }
                if (resultcode == "1003")
                {
                    FastOrder.UserState = 2;
                    FastOrder.UserTime  = DateTime.Now;
                }
                Entity.SaveChanges();
            }
            ViewBag.FastOrder = FastOrder;
            return(View("FastSuccess"));
        }
Ejemplo n.º 24
0
        public override void SendRequest()
        {
            this.SendTime = this.GetSendTimeSpan(this.MerchantNo);
            StringBuilder builder = new StringBuilder();

            builder.AppendFormat(string.IsNullOrEmpty(this.Name) ? "" : (this.Name + "|"), new object[0]);
            builder.AppendFormat(string.IsNullOrEmpty("V4.1.1.1.1") ? "" : "V4.1.1.1.1|", new object[0]);
            builder.AppendFormat(string.IsNullOrEmpty("UTF-8") ? "" : "UTF-8|", new object[0]);
            builder.AppendFormat(string.IsNullOrEmpty(this.MerchantNo) ? "" : (this.MerchantNo + "|"), new object[0]);
            builder.AppendFormat(string.IsNullOrEmpty(this.SendTime) ? "" : (this.SendTime + "|"), new object[0]);
            builder.AppendFormat(string.IsNullOrEmpty(this._orderNo) ? "" : (this._orderNo + "|"), new object[0]);
            builder.AppendFormat(string.IsNullOrEmpty(this._amount) ? "" : (this._amount + "|"), new object[0]);
            builder.AppendFormat(string.IsNullOrEmpty(this._orderTime) ? "" : (this._orderTime + "|"), new object[0]);
            builder.AppendFormat(string.IsNullOrEmpty("CNY") ? "" : "CNY|", new object[0]);
            builder.AppendFormat(string.IsNullOrEmpty(this._payType) ? "" : (this._payType + "|"), new object[0]);
            builder.AppendFormat(string.IsNullOrEmpty(this._payChannel) ? "" : (this._payChannel + "|"), new object[0]);
            builder.AppendFormat(string.IsNullOrEmpty("") ? "" : "|", new object[0]);
            builder.AppendFormat(string.IsNullOrEmpty(this._backUrl) ? "" : (this._backUrl + "|"), new object[0]);
            builder.AppendFormat(string.IsNullOrEmpty(this._notifyUrl) ? "" : (this._notifyUrl + "|"), new object[0]);
            builder.AppendFormat(string.IsNullOrEmpty(this._productNo) ? "" : (this._productNo + "|"), new object[0]);
            builder.AppendFormat(string.IsNullOrEmpty(this.BuyerContact) ? "" : (this.BuyerContact + "|"), new object[0]);
            builder.AppendFormat(string.IsNullOrEmpty(this.BuyerIP) ? "" : (this.BuyerIP + "|"), new object[0]);
            builder.AppendFormat(string.IsNullOrEmpty(this._remark1) ? "" : (this._remark1 + "|"), new object[0]);
            builder.AppendFormat(string.IsNullOrEmpty("MD5") ? "" : "MD5|", new object[0]);
            string        str      = builder.ToString();
            string        strValue = FormsAuthentication.HashPasswordForStoringInConfigFile(str + this.Key, "MD5");
            StringBuilder builder2 = new StringBuilder();

            builder2.Append(this.CreateField("Name", this.Name));
            builder2.Append(this.CreateField("Version", "V4.1.1.1.1"));
            builder2.Append(this.CreateField("Charset", "UTF-8"));
            builder2.Append(this.CreateField("MsgSender", this.MerchantNo));
            builder2.Append(this.CreateField("SendTime", this.SendTime));
            builder2.Append(this.CreateField("OrderNo", this._orderNo));
            builder2.Append(this.CreateField("OrderAmount", this._amount));
            builder2.Append(this.CreateField("OrderTime", this._orderTime));
            builder2.Append(this.CreateField("Currency", "CNY"));
            builder2.Append(this.CreateField("PayType", this._payType));
            builder2.Append(this.CreateField("PayChannel", this._payChannel));
            builder2.Append(this.CreateField("InstCode", ""));
            builder2.Append(this.CreateField("PageUrl", this._backUrl));
            builder2.Append(this.CreateField("NotifyUrl", this._notifyUrl));
            builder2.Append(this.CreateField("ProductName", this._productNo));
            builder2.Append(this.CreateField("BuyerContact", this.BuyerContact));
            builder2.Append(this.CreateField("BuyerIp", this.BuyerIP));
            builder2.Append(this.CreateField("Ext1", this._remark1));
            builder2.Append(this.CreateField("SignType", "MD5"));
            builder2.Append(this.CreateField("SignMsg", strValue));
            IDictionary <string, string> param = new Dictionary <string, string>();

            param.Add("originStr", str);
            param.Add("Name", this.Name);
            param.Add("Version", "V4.1.1.1.1");
            param.Add("Charset", "UTF-8");
            param.Add("MsgSender", this.MerchantNo);
            param.Add("SendTime", this.SendTime);
            param.Add("OrderNo", this._orderNo);
            param.Add("OrderAmount", this._amount);
            param.Add("OrderTime", this._orderTime);
            param.Add("Currency", "CNY");
            param.Add("PayType", this._payType);
            param.Add("PayChannel", this._payChannel);
            param.Add("InstCode", "");
            param.Add("PageUrl", this._backUrl);
            param.Add("NotifyUrl", this._notifyUrl);
            param.Add("ProductName", this._productNo);
            param.Add("BuyerContact", this.BuyerContact);
            param.Add("BuyerIp", this.BuyerIP);
            param.Add("Ext1", this._remark1);
            param.Add("SignType", "MD5");
            param.Add("SignMsg", strValue);
            PayLog.AppendLog(param, strValue, this._notifyUrl, "支付日志", LogType.ShengpayMobile);
            this.SubmitPaymentForm(this.CreateForm(builder2.ToString(), "https://mas.shengpay.com/web-acquire-channel/cashier.htm"));
        }
Ejemplo n.º 25
0
 public string WebPay(string subject, string body, string notifyUrl, string returnUrl, PayLog payLog, Payment payment,
                      Dictionary <string, string> param = null)
 {
     return(string.Empty);
 }
Ejemplo n.º 26
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public ActionResult Pay(PayViewModel payModel)
        {
            //获取产品信息
            if (payModel.OrderId.Equals(Guid.Empty))
            {
                return(Content("订单Id不合法!"));
            }

            var order = _currencyService.GetSingleById <Order>(payModel.OrderId);

            if (order == null)
            {
                return(Content("订单数据不存在!"));
            }

            if (order.OrderStatus != OrderStatus.PendingPayment && order.PayStatus != PayStatus.Unpaid)
            {
                return(Content("订单状态不合理,无法支付!"));
            }

            var payment = _paymentService.LoadPayment(payModel.PaymentCode);

            if (payment == null || !payment.Enabled)
            {
                return(Content("支付方式不合法或已停用!"));
            }

            var paymentDispatcher = HostConstObject.Container.ResolveNamed <IPaymentDispatcher>(payment.Code.ToLower());

            if (paymentDispatcher == null)
            {
                return(Content("支付方式不合法"));
            }

            var routeParas = new RouteValueDictionary {
                { "area", PaymentProcessModule.Area },
                { "controller", "Receive" },
                { "action", "AsyncReturn" },
                { "paymentCode", payment.Code }
            };
            var notifyUrl = HostConstObject.HostUrl + _urlHelper.RouteUrl(routeParas);

            var routeParas2 = new RouteValueDictionary {
                { "area", PaymentProcessModule.Area },
                { "controller", "Receive" },
                { "action", "SyncReturn" },
                { "paymentCode", payment.Code }
            };
            var returnUrl = HostConstObject.HostUrl + _urlHelper.RouteUrl(routeParas2);

            if (payModel.UseBalance == 1)
            {
                //使用余额付款
                #region

                using (TransactionScope scope = new TransactionScope())
                {
                    var cashWallet = _walletService.GetWalletByMemberId(order.MemberId,
                                                                        Wallet.Models.WalletType.Cash);
                    if (cashWallet != null && cashWallet.Available > 0)
                    {
                        if (cashWallet.Available >= order.PayFee)
                        {
                            string error;
                            if (_walletService.Draw(order.MemberId, Wallet.Models.WalletType.Cash, order.PayFee,
                                                    "支付订单" + order.OrderNo, out error))
                            {
                                order.BalancePay  = order.PayFee;
                                order.OrderStatus = OrderStatus.WaitingForDelivery;
                                order.PayStatus   = PayStatus.Paid;
                                order.PayTime     = DateTime.Now;

                                var balancePayment = _paymentService.LoadPayment(PaymentType.Balance.ToString());
                                order.PaymentId   = balancePayment.Id;
                                order.PaymentName = balancePayment.Name;
                                _orderService.ChangeOrderStatus(order.Id, order.OrderStatus, order.PayStatus);
                                _currencyService.Update(order);

                                scope.Complete();
                            }
                        }
                        else
                        {
                            string error;
                            if (_walletService.Draw(order.MemberId, Wallet.Models.WalletType.Cash,
                                                    cashWallet.Available,
                                                    "支付订单" + order.OrderNo, out error))
                            {
                                order.UnpayFee   = order.PayFee - cashWallet.Available;
                                order.BalancePay = cashWallet.Available;
                                _currencyService.Update(order);

                                scope.Complete();
                            }
                        }
                    }
                }

                #endregion
            }

            if (order.PayStatus == PayStatus.Paid)
            {
                return(Redirect(_publicService.GetReturnUrl(order.Id)));
            }

            var payLog = new PayLog
            {
                Id            = KeyGenerator.GetGuidKey(),
                TransactionNo = $"{order.OrderNo}{KeyGenerator.GenerateRandom(1000, 1)}",
                OrderId       = order.Id,
                OrderNo       = order.OrderNo,
                OrderAmount   = order.UnpayFee,
                PaymentId     = payment.Id,
                PaymentName   = payment.Name,
                CreateTime    = DateTime.Now,
                LogStatus     = LogStatus.Unpaid
            };
            if (!_currencyService.Create(payLog))
            {
                throw new WebApiInnerException("0007", "生成支付流水失败");
            }

            var subject = $"支付订单{order.OrderNo}-{payLog.TransactionNo}";
            var body    = string.Join(";", _currencyService.GetList <OrderGoods>(x => x.OrderId == order.Id).Select(g => g.GoodsName));

            ViewBag.Html = paymentDispatcher.H5Pay(subject, body, notifyUrl, returnUrl, payLog, payment);

            return(View());
        }
        public ActionResult Result()
        {
            string Resp    = Request.QueryString["resp"];
            string Sign    = Request.QueryString["sign"];
            string SignStr = Resp;

            Resp = LokFuEncode.Base64Decode(Resp, "utf-8");
            JObject json = new JObject();

            try
            {
                json = (JObject)JsonConvert.DeserializeObject(Resp);
            }
            catch (Exception Ex)
            {
                ViewBag.ErrorMsg = Ex.ToString();
                return(View("Error"));
            }
            if (json == null)
            {
                ViewBag.ErrorMsg = "数据处理出错";
                return(View("Error"));
            }
            string resultcode = json["resultcode"].ToString(); //交易结果码
            string resultmsg  = json["resultmsg"].ToString();  //交易结果信息
            string queryid    = json["queryid"].ToString();    //交易流水号
            string txnamt     = json["txnamt"].ToString();     //交易金额\
            string merid      = json["merid"].ToString();      //交易金额
            string orderid    = json["orderid"].ToString();    //交易金额

            Orders Orders = Entity.Orders.FirstOrDefault(n => n.TNum == orderid);

            if (Orders == null)
            {
                ViewBag.ErrorMsg = "订单信息有误!";
                return(View("Error"));
            }
            PayConfig PayConfig = Entity.PayConfig.FirstOrDefault(n => n.Id == Orders.PayWay && n.State == 1);

            if (PayConfig == null)
            {
                ViewBag.ErrorMsg = "支付通道已关闭!";
                return(View("Error"));
            }
            string ConfigStr = PayConfig.QueryArray;

            string[] ConfigArr = ConfigStr.Split(',');
            string   merId     = ConfigArr[0];
            string   merKey    = ConfigArr[1];
            string   MD5Str    = SignStr + merKey;
            string   sign      = MD5Str.GetMD5();
            //================================================
            PayLog PayLog = new PayLog();

            PayLog.PId     = PayConfig.Id;
            PayLog.OId     = orderid;
            PayLog.TId     = queryid;
            PayLog.Amount  = decimal.Parse(txnamt) / 100;
            PayLog.Way     = "GET";
            PayLog.AddTime = DateTime.Now;
            PayLog.Data    = Request.QueryString.ToString();
            PayLog.State   = 1;
            Entity.PayLog.AddObject(PayLog);
            Entity.SaveChanges();
            //================================================
            if (Sign != sign)
            {
                ViewBag.ErrorMsg = "签名错误!";
                return(View("Error"));
            }
            if (merId != merid)
            {
                ViewBag.ErrorMsg = "商户号不一置!";
                return(View("Error"));
            }
            if (resultcode != "0000" && resultcode != "1002")
            {
                ViewBag.ErrorMsg = "支付失败![" + resultcode + "]" + resultmsg;
                return(View("Error"));
            }
            //string respMsg = resData["respMsg"];//应答信息
            //if (respMsg != "success")
            //{
            //    ViewBag.ErrorMsg = "支付失败![" + respMsg + "]";
            //    return View("Error");
            //}
            int factmoney = int.Parse(txnamt);

            if (((int)(Orders.Amoney * 100)) > factmoney)
            {
                ViewBag.ErrorMsg = "支付金额与交易金额不符!";
                return(View("Error"));
            }
            Orders         = Orders.PaySuccess(Entity);
            ViewBag.Orders = Orders;
            return(View("Success"));
        }
        public void FastNotice()
        {
            string Resp    = Request.Form["resp"];
            string Sign    = Request.Form["sign"];
            string SignStr = Resp;

            Resp = LokFuEncode.Base64Decode(Resp, "utf-8");
            JObject json = new JObject();

            try
            {
                json = (JObject)JsonConvert.DeserializeObject(Resp);
            }
            catch (Exception Ex)
            {
                Response.Write(Ex.ToString());
                return;
            }
            if (json == null)
            {
                Response.Write("Json Null");
                return;
            }
            string resultcode = json["resultcode"].ToString(); //交易结果码
            string resultmsg  = json["resultmsg"].ToString();  //交易结果信息
            string queryid    = json["queryid"].ToString();    //交易流水号
            string txnamt     = json["txnamt"].ToString();     //交易金额\
            string merid      = json["merid"].ToString();      //交易金额
            string orderid    = json["orderid"].ToString();    //交易金额

            FastOrder FastOrder = Entity.FastOrder.FirstOrDefault(n => n.TNum == orderid);

            if (FastOrder == null)
            {
                Response.Write("E1");
                return;
            }
            if (FastOrder.PayState == 1)
            {
                Response.Write("P1");
                return;
            }
            FastPayWay FastPayWay = Entity.FastPayWay.FirstOrDefault(n => n.Id == FastOrder.PayWay);

            if (FastPayWay == null)
            {
                Response.Write("E3");
                return;
            }
            if (FastPayWay.State != 1)
            {
                Response.Write("E4");
                return;
            }
            if (FastPayWay.DllName != "HFPay")
            {
                Response.Write("E5");
                return;
            }
            string[] PayConfigArr = FastPayWay.QueryArray.Split(',');
            if (PayConfigArr.Length != 3)
            {
                Response.Write("E53");
                return;
            }
            string MerId  = PayConfigArr[0];
            string MerKey = PayConfigArr[1];

            string MD5Str = SignStr + MerKey;
            string sign   = MD5Str.GetMD5();
            //================================================
            //这里记录日志
            PayLog PayLog = new PayLog();

            PayLog.PId     = (int)FastOrder.PayWay;
            PayLog.OId     = FastOrder.TNum;
            PayLog.TId     = FastOrder.Trade;
            PayLog.Amount  = decimal.Parse(txnamt) / 100;
            PayLog.Way     = "POST";
            PayLog.AddTime = DateTime.Now;
            PayLog.Data    = Request.Form.ToString();
            PayLog.State   = 1;
            Entity.PayLog.AddObject(PayLog);
            Entity.SaveChanges();
            //================================================
            if (Sign != sign)
            {
                Response.Write("E4");
                return;
            }
            if (MerId != merid)
            {
                Response.Write("E5");
                return;
            }
            if (resultcode != "0000" && resultcode != "1002")
            {
                Response.Write("E6");
                return;
            }
            int factmoney = int.Parse(txnamt);

            if (((int)(FastOrder.Amoney * 100)) != factmoney)
            {
                Response.Write("E7");
                return;
            }
            FastOrder.Trade = queryid;
            Entity.SaveChanges();

            FastOrder         = FastOrder.PaySuccess(Entity);
            ViewBag.FastOrder = FastOrder;

            Response.Write("0000");
        }
Ejemplo n.º 29
0
        public ApiResult SignInfo(string paymentCode, Guid orderId, int useBalance)
        {
            if (orderId.Equals(Guid.Empty))
            {
                throw new WebApiInnerException("0001", "订单Id不合法");
            }

            var order = _orderService.Load(orderId);

            if (order == null)
            {
                throw new WebApiInnerException("0002", "订单数据不存在");
            }

            if (order.OrderStatus != OrderStatus.PendingPayment && order.PayStatus != PayStatus.Unpaid)
            {
                throw new WebApiInnerException("0003", "订单状态不合理,无法支付");
            }

            var payment = _paymentService.LoadPayment(paymentCode);

            if (payment == null || !payment.Enabled)
            {
                throw new WebApiInnerException("0004", "支付方式不合法或已停用");
            }

            var paymentDispatcher = HostConstObject.Container.ResolveNamed <IPaymentDispatcher>(payment.Code.ToLower());

            if (paymentDispatcher == null)
            {
                throw new WebApiInnerException("0005", "支付方式不合法");
            }

            var result = new ApiResult();

            try
            {
                var routeParas = new RouteValueDictionary {
                    { "area", PaymentProcessModule.Area },
                    { "controller", "Receive" },
                    { "action", "AsyncReturn" },
                    { "paymentCode", payment.Code }
                };
                var notifyUrl = HostConstObject.HostUrl + _urlHelper.RouteUrl(routeParas);

                if (payment.Code.Equals("balance"))
                {
                    //使用余额付款
                    #region

                    using (TransactionScope scope = new TransactionScope())
                    {
                        var cashWallet = _walletService.GetWalletByMemberId(order.MemberId,
                                                                            Wallet.Models.WalletType.Cash);
                        if (cashWallet != null && cashWallet.Available >= order.PayFee)
                        {
                            string error;
                            if (_walletService.Draw(order.MemberId, Wallet.Models.WalletType.Cash, order.PayFee,
                                                    "支付订单" + order.OrderNo, out error))
                            {
                                order.BalancePay  = order.PayFee;
                                order.OrderStatus = OrderStatus.WaitingForDelivery;
                                order.PayStatus   = PayStatus.Paid;
                                order.PayTime     = DateTime.Now;

                                var balancePayment = _paymentService.LoadPayment(PaymentType.Balance.ToString());
                                order.PaymentId   = balancePayment.Id;
                                order.PaymentName = balancePayment.Name;
                                _orderService.ChangeOrderStatus(order.Id, order.OrderStatus, order.PayStatus);
                                _currencyService.Update(order);

                                scope.Complete();
                            }
                        }
                        else
                        {
                            throw new WebApiInnerException("0008", "账号余额不足");
                        }
                    }

                    #endregion
                }
                else if (useBalance == 1)
                {
                    //使用余额付款
                    #region

                    using (TransactionScope scope = new TransactionScope())
                    {
                        var cashWallet = _walletService.GetWalletByMemberId(order.MemberId,
                                                                            Wallet.Models.WalletType.Cash);
                        if (cashWallet != null && cashWallet.Available > 0)
                        {
                            if (cashWallet.Available >= order.PayFee)
                            {
                                string error;
                                if (_walletService.Draw(order.MemberId, Wallet.Models.WalletType.Cash, order.PayFee, "支付订单" + order.OrderNo, out error))
                                {
                                    order.BalancePay  = order.PayFee;
                                    order.OrderStatus = OrderStatus.WaitingForDelivery;
                                    order.PayStatus   = PayStatus.Paid;
                                    order.PayTime     = DateTime.Now;

                                    var balancePayment = _paymentService.LoadPayment(PaymentType.Balance.ToString());
                                    order.PaymentId   = balancePayment.Id;
                                    order.PaymentName = balancePayment.Name;
                                    _orderService.ChangeOrderStatus(order.Id, order.OrderStatus, order.PayStatus);
                                    _currencyService.Update(order);

                                    scope.Complete();
                                }
                            }
                            else
                            {
                                string error;
                                if (_walletService.Draw(order.MemberId, Wallet.Models.WalletType.Cash, cashWallet.Available, "支付订单" + order.OrderNo, out error))
                                {
                                    order.UnpayFee   = order.PayFee - cashWallet.Available;
                                    order.BalancePay = cashWallet.Available;
                                    _currencyService.Update(order);

                                    scope.Complete();
                                }
                            }
                        }
                    }

                    #endregion
                }

                var payLog = new PayLog
                {
                    Id            = KeyGenerator.GetGuidKey(),
                    TransactionNo = $"{order.OrderNo}{KeyGenerator.GenerateRandom(1000, 1)}",
                    OrderId       = order.Id,
                    OrderNo       = order.OrderNo,
                    OrderAmount   = order.UnpayFee,
                    PaymentId     = payment.Id,
                    PaymentName   = payment.Name,
                    CreateTime    = DateTime.Now,
                    LogStatus     = LogStatus.Unpaid
                };
                if (!_currencyService.Create(payLog))
                {
                    throw new WebApiInnerException("0007", "生成支付流水失败");
                }

                var subject = $"支付订单{order.OrderNo}-{payLog.TransactionNo}";
                var body    = string.Join(";", order.OrderGoods.Select(g => g.GoodsName));

                result.SetData(paymentDispatcher.GetSignInfo(subject, body, notifyUrl, payLog, payment));
            }
            catch (WebApiInnerException ex)
            {
                Logger.Error(ex, "获取订单支付签名数据失败");
                throw new WebApiInnerException(ex.ErrorCode, ex.Message);
            }
            catch (Exception ex)
            {
                Logger.Error(ex, "获取订单支付签名数据失败");
                throw new WebApiInnerException("0006", "生成签名数据出现异常");
            }

            return(result);
        }
        public void Notice()
        {
            string Resp    = Request.Form["resp"];
            string Sign    = Request.Form["sign"];
            string SignStr = Resp;

            Resp = LokFuEncode.Base64Decode(Resp, "utf-8");
            JObject json = new JObject();

            try
            {
                json = (JObject)JsonConvert.DeserializeObject(Resp);
            }
            catch (Exception Ex)
            {
                Response.Write(Ex.ToString());
                return;
            }
            if (json == null)
            {
                Response.Write("Json Null");
                return;
            }
            string resultcode = json["resultcode"].ToString(); //交易结果码
            string resultmsg  = json["resultmsg"].ToString();  //交易结果信息
            string queryid    = json["queryid"].ToString();    //交易流水号
            string txnamt     = json["txnamt"].ToString();     //交易金额\
            string merid      = json["merid"].ToString();      //交易金额
            string orderid    = json["orderid"].ToString();    //交易金额

            Orders Orders = Entity.Orders.FirstOrDefault(n => n.TNum == orderid);

            if (Orders == null)
            {
                Response.Write("E4");
                return;
            }
            PayConfig PayConfig = Entity.PayConfig.FirstOrDefault(n => n.Id == Orders.PayWay && n.State == 1);

            if (PayConfig == null)
            {
                Response.Write("E0");
                return;
            }
            string ConfigStr = PayConfig.QueryArray;

            string[] ConfigArr = ConfigStr.Split(',');
            string   merId     = ConfigArr[0];
            string   merKey    = ConfigArr[1];
            string   MD5Str    = SignStr + merKey;
            string   sign      = MD5Str.GetMD5();
            //================================================
            PayLog PayLog = new PayLog();

            PayLog.PId     = PayConfig.Id;
            PayLog.OId     = orderid;
            PayLog.TId     = queryid;
            PayLog.Amount  = decimal.Parse(txnamt) / 100;
            PayLog.Way     = "POST";
            PayLog.AddTime = DateTime.Now;
            PayLog.Data    = Request.Form.ToString();
            PayLog.State   = 1;
            Entity.PayLog.AddObject(PayLog);
            Entity.SaveChanges();
            //================================================
            if (Sign != sign)
            {
                Response.Write("E2");
                return;
            }
            if (merId != merid)
            {
                Response.Write("E1");
                return;
            }
            if (resultcode != "0000" && resultcode != "1002")
            {
                Response.Write("E3");
                return;
            }
            int factmoney = int.Parse(txnamt);

            if (((int)(Orders.Amoney * 100)) > factmoney)
            {
                Response.Write("E5");
                return;
            }
            Orders = Orders.PaySuccess(Entity);
            Response.Write("0000");
        }