Exemple #1
0
        public string OrderQuery()
        {
            int    orderId = MyCommFun.RequestInt("orderid");
            int    wid     = MyCommFun.RequestInt("wid");
            string code    = MyCommFun.RequestParam("code");
            string state   = MyCommFun.RequestParam("state");

            BLL.wx_payment_wxpay   wxPayBll    = new BLL.wx_payment_wxpay();
            Model.wx_payment_wxpay paymentInfo = wxPayBll.GetModelByWid(wid);
            BLL.wx_userweixin      wx          = new BLL.wx_userweixin();
            Model.wx_userweixin    wxModel     = wx.GetModel(wid);
            BLL.orders             otBll       = new BLL.orders();
            Model.orders           orderEntity = otBll.GetModel(orderId, wid);
            litout_trade_no = orderEntity.order_no;
            string         nonceStr          = TenPayV3Util.GetNoncestr();
            RequestHandler packageReqHandler = new RequestHandler(null);

            //设置package订单参数
            packageReqHandler.SetParameter("appid", paymentInfo.appId);      //公众账号ID
            packageReqHandler.SetParameter("mch_id", paymentInfo.partnerId); //商户号
            packageReqHandler.SetParameter("transaction_id", "");            //填入微信订单号
            packageReqHandler.SetParameter("out_trade_no", litout_trade_no); //填入商家订单号
            packageReqHandler.SetParameter("nonce_str", nonceStr);           //随机字符串
            string sign = packageReqHandler.CreateMd5Sign("key", paymentInfo.paySignKey);

            packageReqHandler.SetParameter("sign", sign);                           //签名

            string data = packageReqHandler.ParseXML();

            var result = TenPayV3.OrderQuery(data);
            var res    = XDocument.Parse(result);

            openid = res.Element("xml").Element("sign").Value;
            string transaction_id = res.Element("xml").Element("sign").Value;

            openids   = res.Element("xml").Element("openid").Value;
            bank_type = res.Element("xml").Element("bank_type").Value;
            if (bank_type == "CNY")
            {
                bank_type = "钱包零钱";
            }
            if (bank_type == "CFT")
            {
                bank_type = "银行卡";
            }
            total_fee      = res.Element("xml").Element("total_fee").Value;
            time_end       = res.Element("xml").Element("time_end").Value;
            out_trade_no   = res.Element("xml").Element("out_trade_no").Value;
            transaction_id = res.Element("xml").Element("transaction_id").Value;
            result_code    = res.Element("xml").Element("result_code").Value;

            return(openid);
        }
Exemple #2
0
        /// <summary>
        /// 微信退单
        /// </summary>
        /// <param name="dingdan"></param>
        /// <param name="dto"></param>
        /// <param name="returnMsg"></param>
        /// <returns></returns>
        private bool WeChatRefund(wx_hotel_dingdan dingdan, TuidanDto dto, int wid, out string returnMsg)
        {
            bool result = false;

            returnMsg = null;

            var refundResult = dingdanbll.GetWeChatRefundParams(wid, dingdan.hotelid.Value, dingdan.id, dto.refundCode);

            //使用系统订单号退单
            if (refundResult != null && refundResult.Tables.Count > 0 && refundResult.Tables[0].Rows.Count > 0)
            {
                var orderNumber    = refundResult.Tables[0].Rows[0]["orderNumber"].ToString();
                var transaction_id = refundResult.Tables[0].Rows[0]["transaction_id"].ToString();
                var refundAmount   = Convert.ToInt32(refundResult.Tables[0].Rows[0]["refundAmount"]);
                var payAmount      = Convert.ToInt32(refundResult.Tables[0].Rows[0]["payAmount"]);


                var wxModel = new BLL.wx_userweixin().GetModel(wid);
                var payInfo = new BLL.wx_payment_wxpay().GetModelByWid(wid);

                var requestHandler = new RequestHandler(null);
                requestHandler.SetParameter("out_trade_no", orderNumber);
                //requestHandler.SetParameter("transaction_id", transaction_id);
                requestHandler.SetParameter("out_refund_no", dto.refundCode);
                requestHandler.SetParameter("appid", wxModel.AppId);
                requestHandler.SetParameter("mch_id", payInfo.mch_id);//商户号
                requestHandler.SetParameter("nonce_str", Guid.NewGuid().ToString().Replace("-", ""));

                //退款金额
                if (PayHelper.IsDebug)
                {
                    requestHandler.SetParameter("total_fee", (payAmount).ToString());
                    requestHandler.SetParameter("refund_fee", (refundAmount).ToString());
                }
                else
                {
                    requestHandler.SetParameter("total_fee", (payAmount * 100).ToString());
                    requestHandler.SetParameter("refund_fee", (refundAmount * 100).ToString());
                }

                requestHandler.SetParameter("op_user_id", wxModel.AppId);
                requestHandler.SetParameter("sign", requestHandler.CreateMd5Sign("key", payInfo.paykey));

                var refundInfo          = TenPayV3Helper.Refund(requestHandler.ParseXML(), string.Format(@"{0}{1}", AppDomain.CurrentDomain.BaseDirectory, payInfo.certInfoPath), payInfo.cerInfoPwd);
                var refundOrderResponse = new RefundOrderResponse(refundInfo);

                result    = refundOrderResponse.IsSuccess;
                returnMsg = refundOrderResponse.return_msg;
            }

            return(result);
        }
Exemple #3
0
        protected void Page_Load(object sender, EventArgs e)
        {
            int productId = MyCommFun.RequestInt("orderid");
            int hc        = this.GetHashCode();
            int wid       = MyCommFun.RequestInt("wid");

            BLL.wx_payment_wxpay   wxPayBll    = new BLL.wx_payment_wxpay();
            Model.wx_payment_wxpay paymentInfo = wxPayBll.GetModelByWid(wid);

            var returnUrl = string.Format(MyCommFun.getWebSite() + "/api/payment/wxpay/JsApi.aspx?wid=" + wid + "&orderid=" + productId + "");
            var state     = string.Format("{0}|{1}", productId, hc);
            var url       = OAuthApi.GetAuthorizeUrl(PayV3Config.Mch_appId, returnUrl, state, OAuthScope.snsapi_userinfo);

            Response.Redirect(url);
        }
        /// <summary>
        /// 微信支付:生成请求数据
        /// </summary>
        /// <param name="openid">微信用户id</openid>
        /// <param name="ttFee">商品总价格</param>
        /// <param name="busiBody"></param>
        /// <returns></returns>
        protected void WxPayData(decimal ttFee, string busiBody, string out_trade_no)
        {
            WxPayHelper wxPayHelper = new WxPayHelper();
            BLL.wx_payment_wxpay wxPayBll = new BLL.wx_payment_wxpay();
            Model.wx_payment_wxpay paymentInfo = wxPayBll.GetModelByWid(wid);

            //先设置基本信息
            string partnerId = paymentInfo.partnerId;// "1218574001";//  
            string appId = paymentInfo.appId;// "wxa9b8e33e48ac5e0f";// 
            string partnerKey = paymentInfo.partnerKey;// "huyuxianghuyuxianghuyuxiang12345";//  
            //paysignkey(非appkey) 
            string appKey = paymentInfo.paySignKey; //"nwRmqgvSG08pe3vU5qzBLb7Bvih0WOABGzUPvqgFqE0iSkJlJ8wh7JlLYy2cXFgFA3v1bM8eTDm1y1UcyeW9IGq2py2qei7J5xDoVR9lfO3cS6fMjFbMQeeqBRit0bKp";// 

            wxPayHelper.SetAppId(appId);
            wxPayHelper.SetAppKey(appKey);
            wxPayHelper.SetPartnerKey(partnerKey);
            wxPayHelper.SetSignType("SHA1");
            //设置请求package信息
            wxPayHelper.SetParameter("bank_type", "WX");
            wxPayHelper.SetParameter("body", busiBody);
            wxPayHelper.SetParameter("attach",wid+"|"+busiBody);
            wxPayHelper.SetParameter("partner", partnerId);
            wxPayHelper.SetParameter("out_trade_no", out_trade_no);
            wxPayHelper.SetParameter("total_fee", ((int)(ttFee * 100)).ToString());
            wxPayHelper.SetParameter("fee_type", "1");
           // wxPayHelper.SetParameter("notify_url", "http://" + HttpContext.Current.Request.Url.Authority + "/api/payment/wxpay/notify_url.aspx?wid="+wid);

            wxPayHelper.SetParameter("notify_url", "http://" + HttpContext.Current.Request.Url.Authority + "/api/payment/wxpay/notify_url.aspx");//不能带参数
            wxPayHelper.SetParameter("spbill_create_ip", MXRequest.GetIP());
            wxPayHelper.SetParameter("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));
            //---------有效期截至日期------
          
            wxPayHelper.SetParameter("time_expire", DateTime.Now.AddMinutes(expireMinute).ToString("yyyyMMddHHmmss"));

            wxPayHelper.SetParameter("input_charset", "UTF-8");
            packageValue = wxPayHelper.CreateBizPackage();


        }
Exemple #5
0
        /// <summary>
        /// 微信支付:生成请求数据
        /// </summary>
        /// <param name="openid">微信用户id</openid>
        /// <param name="ttFee">商品总价格</param>
        /// <param name="busiBody"></param>
        /// <returns></returns>
        protected void WxPayData(decimal ttFee, string busiBody, string out_trade_no)
        {
            WxPayHelper wxPayHelper = new WxPayHelper();

            BLL.wx_payment_wxpay   wxPayBll    = new BLL.wx_payment_wxpay();
            Model.wx_payment_wxpay paymentInfo = wxPayBll.GetModelByWid(wid);

            //先设置基本信息
            string partnerId  = paymentInfo.partnerId;  // "1218574001";//
            string appId      = paymentInfo.appId;      // "wxa9b8e33e48ac5e0f";//
            string partnerKey = paymentInfo.partnerKey; // "huyuxianghuyuxianghuyuxiang12345";//
            //paysignkey(非appkey)
            string appKey = paymentInfo.paySignKey;     //"nwRmqgvSG08pe3vU5qzBLb7Bvih0WOABGzUPvqgFqE0iSkJlJ8wh7JlLYy2cXFgFA3v1bM8eTDm1y1UcyeW9IGq2py2qei7J5xDoVR9lfO3cS6fMjFbMQeeqBRit0bKp";//

            wxPayHelper.SetAppId(appId);
            wxPayHelper.SetAppKey(appKey);
            wxPayHelper.SetPartnerKey(partnerKey);
            wxPayHelper.SetSignType("SHA1");
            //设置请求package信息
            wxPayHelper.SetParameter("bank_type", "WX");
            wxPayHelper.SetParameter("body", busiBody);
            wxPayHelper.SetParameter("attach", wid + "|" + busiBody);
            wxPayHelper.SetParameter("partner", partnerId);
            wxPayHelper.SetParameter("out_trade_no", out_trade_no);
            wxPayHelper.SetParameter("total_fee", ((int)(ttFee * 100)).ToString());
            wxPayHelper.SetParameter("fee_type", "1");
            // wxPayHelper.SetParameter("notify_url", "http://" + HttpContext.Current.Request.Url.Authority + "/api/payment/wxpay/notify_url.aspx?wid="+wid);

            wxPayHelper.SetParameter("notify_url", "http://" + HttpContext.Current.Request.Url.Authority + "/api/payment/wxpay/notify_url.aspx");//不能带参数
            wxPayHelper.SetParameter("spbill_create_ip", MXRequest.GetIP());
            wxPayHelper.SetParameter("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));
            //---------有效期截至日期------

            wxPayHelper.SetParameter("time_expire", DateTime.Now.AddMinutes(expireMinute).ToString("yyyyMMddHHmmss"));

            wxPayHelper.SetParameter("input_charset", "UTF-8");
            packageValue = wxPayHelper.CreateBizPackage();
        }
Exemple #6
0
        /// <summary>
        /// 【微支付】 订单付款成功,处理订单:1将订单的状态改成付款完成;
        ///
        /// </summary>
        /// <param name="beforeFunName"></param>
        /// <param name="notify_id">通知id</param>
        /// <param name="out_trade_no">商户订单号</param>
        /// <param name="transaction_id">订单交易号</param>
        /// <param name="pay_info">支付结果</param>
        /// <param name="total_fee">付款金额(单位为分)</param>
        /// <param name="otid">订单临时表id</param>
        /// <returns>有错误则返回错误信息,正确,则返回空字符串</returns>
        public string ProcessPaySuccess_wx(string beforeFunName, string notify_id, string out_trade_no, string transaction_id, string pay_info, int total_fee, int otid, int wid)
        {
            string payTmpType = "【微支付】";

            total_fee = total_fee / 100;
            BLL.orders orderBll = new BLL.orders();

            string funName = payTmpType + beforeFunName + " ProcessPaySuccess_wx ";

            BLL.wx_logs logBll = new BLL.wx_logs();
            logBll.AddLog(wid, "微支付", funName, "开始执行ProcessPaySuccess_wx方法[otid:" + otid + "]");
            try
            {
                #region 数据同步前
                IList <Model.orders> orderlist = orderBll.GetModelList("id=" + otid + " and order_no='" + out_trade_no + "'");
                if (orderlist == null || orderlist.Count <= 0)
                {
                    logBll.AddLog(wid, payTmpType, funName, "订单号【" + out_trade_no + "】订单号不存在", 0);
                    return("订单号不存在");
                }
                //这个暂时不处理
                if (logBll.ExistsFlg((out_trade_no + otid)))
                {  //如果已经处理过,则不再处理
                    return("");
                }
                logBll.AddFlg(wid, payTmpType, funName, (out_trade_no + otid));//加标志,防止重复提交

                Model.orders orderEntity = orderlist[0];
                if (orderEntity.order_amount > total_fee)
                {
                    return("付款的金额(" + total_fee + ")小于订单的预付款金额(" + orderEntity.order_amount + ")信息,直接退款");
                }
                orderEntity.notify_id      = notify_id;
                orderEntity.trade_no       = transaction_id;
                orderEntity.pay_info       = pay_info;
                orderEntity.order_amount   = total_fee;
                orderEntity.payment_time   = DateTime.Now;
                orderEntity.status         = 2;
                orderEntity.payment_status = 2;

                //判断是否需要立即发货
                if (orderEntity.express_status == 0)
                {
                    //立即发货
                    FaHuoProc fahuo = new FaHuoProc();

                    BLL.wx_payment_wxpay        payBll      = new BLL.wx_payment_wxpay();
                    Model.wx_payment_wxpay      paymentInfo = payBll.GetModelByWid(wid);
                    Dictionary <string, object> fahuoDict   = fahuo.fahuomgr(paymentInfo, orderEntity);
                    string errcode = fahuoDict["errcode"].ToString();
                    string errmsg  = fahuoDict["errmsg"].ToString();
                    orderEntity.fahuoCode = errcode;
                    orderEntity.fahuoMsg  = errmsg;
                    if (errcode == "0")
                    {
                        orderEntity.express_status = 2;
                        orderEntity.express_time   = DateTime.Now;
                    }
                    else
                    {
                        orderEntity.express_status = 1;
                    }
                }

                bool ret = orderBll.Update(orderEntity);
                if (!ret)
                {
                    logBll.AddLog(wid, payTmpType, funName, "订单号【" + out_trade_no + "】支付成功后处理数据失败", 0);
                    return("订单号【" + out_trade_no + "】支付成功后处理数据失败");
                }

                logBll.AddLog(payTmpType, funName, "订单号【" + out_trade_no + "】支付成功后,处理数据成功", 1);
                return("");

                #endregion
            }
            catch (Exception ex)
            {
                logBll.AddLog(wid, payTmpType, funName, "订单号【" + out_trade_no + "】支付成功后处理数据同步出现错误:" + ex.Message, 0);
                return(null);
            }
        }
        protected string UserOpenId = ""; //微信用户openid

        protected void Page_Load(object sender, EventArgs e)
        {
            this.BindData();

            LogUtil.WriteLog("============ 单次支付开始 ===============");
            LogUtil.WriteLog(string.Format("传递支付参数:OrderSN={0}、Body={1}、TotalFee={2}、Attach={3}、UserOpenId={4}",
                                           this.OrderSN, this.Body, this.TotalFee, this.Attach, this.UserOpenId));


            #region 支付操作============================


            #region 基本参数===========================
            //时间戳
            TimeStamp = TenpayUtil.getTimestamp();
            //随机字符串
            NonceStr = TenpayUtil.getNoncestr();

            int wid = MyCommFun.RequestInt("wid");
            BLL.wx_payment_wxpay   wxPayBll    = new BLL.wx_payment_wxpay();
            Model.wx_payment_wxpay paymentInfo = wxPayBll.GetModelByWid(wid);

            //创建支付应答对象
            var packageReqHandler = new RequestHandler(Context);
            //初始化
            packageReqHandler.init();

            //设置package订单参数  具体参数列表请参考官方pdf文档,请勿随意设置
            packageReqHandler.setParameter("body", this.Body); //商品信息 127字符
            packageReqHandler.setParameter("appid", PayConfig.AppId);
            packageReqHandler.setParameter("mch_id", PayConfig.MchId);
            packageReqHandler.setParameter("nonce_str", NonceStr.ToLower());
            packageReqHandler.setParameter("notify_url", PayConfig.NotifyUrl);
            packageReqHandler.setParameter("openid", this.UserOpenId);
            packageReqHandler.setParameter("out_trade_no", this.OrderSN);                     //商家订单号
            packageReqHandler.setParameter("spbill_create_ip", Page.Request.UserHostAddress); //用户的公网ip,不是商户服务器IP
            packageReqHandler.setParameter("total_fee", this.TotalFee);                       //商品金额,以分为单位(money * 100).ToString()
            packageReqHandler.setParameter("trade_type", "JSAPI");
            if (!string.IsNullOrEmpty(this.Attach))
            {
                packageReqHandler.setParameter("attach", this.Attach);//自定义参数 127字符
            }
            #endregion

            #region sign===============================
            Sign = packageReqHandler.CreateMd5Sign("key", PayConfig.AppKey);
            LogUtil.WriteLog("WeiPay 页面  sign:" + Sign);
            #endregion

            #region 获取package包======================
            packageReqHandler.setParameter("sign", Sign);

            string data = packageReqHandler.parseXML();
            LogUtil.WriteLog("WeiPay 页面  package(XML):" + data);

            string prepayXml = HttpUtil.Send(data, "https://api.mch.weixin.qq.com/pay/unifiedorder");
            LogUtil.WriteLog("WeiPay 页面  package(Back_XML):" + prepayXml);

            //获取预支付ID
            var xdoc = new XmlDocument();
            xdoc.LoadXml(prepayXml);
            XmlNode     xn  = xdoc.SelectSingleNode("xml");
            XmlNodeList xnl = xn.ChildNodes;
            if (xnl.Count > 7)
            {
                PrepayId = xnl[7].InnerText;
                Package  = string.Format("prepay_id={0}", PrepayId);
                LogUtil.WriteLog("WeiPay 页面  package:" + Package);
            }
            #endregion

            #region 设置支付参数 输出页面  该部分参数请勿随意修改 ==============
            var paySignReqHandler = new RequestHandler(Context);
            paySignReqHandler.setParameter("appId", PayConfig.AppId);
            paySignReqHandler.setParameter("timeStamp", TimeStamp);
            paySignReqHandler.setParameter("nonceStr", NonceStr);
            paySignReqHandler.setParameter("package", Package);
            paySignReqHandler.setParameter("signType", "MD5");
            PaySign = paySignReqHandler.CreateMd5Sign("key", PayConfig.AppKey);

            LogUtil.WriteLog("WeiPay 页面  paySign:" + PaySign);
            #endregion
            #endregion
        }
Exemple #8
0
        /// <summary>
        /// 处理回调的页面
        /// </summary>
        private void ProcessNotify()
        {
            int    wid        = 0;
            string payTmpType = "【微支付】";
            string funName    = payTmpType + " notify_url ProcessNotify ";

            WXLogs.AddLog(payTmpType, funName, "从微支付返回到notify_url.aspx页面", 1);

            byte[] byts = new byte[Request.InputStream.Length];
            Request.InputStream.Read(byts, 0, byts.Length);
            string req = System.Text.Encoding.Default.GetString(byts);

            req = Server.UrlDecode(req);
            WXLogs.AddLog(payTmpType, funName, "req:" + req, 1);

            //返回的状态码
            string return_code = ReadXmlValue(req, "xml/return_code");

            WXLogs.AddLog(payTmpType, "notify_url ProcessNotify", "返回的状态码return_code:" + return_code, 1);

            if (return_code.Trim().ToLower() == "fail")
            {
                string return_msg = ReadXmlValue(req, "xml/return_msg");
                WXLogs.AddLog(payTmpType, funName, "订单处理错误:" + return_msg, 0);
                WriteContent("fail", "订单处理错误:" + return_msg);
                return;
            }


            string attach = ReadXmlValue(req, "xml/attach");

            string[] attachArr = attach.Split('|');
            wid = MyCommFun.Str2Int(attachArr[0]);
            int otid = MyCommFun.Str2Int(attachArr[1]);

            BLL.wx_payment_wxpay   payBll      = new BLL.wx_payment_wxpay();
            Model.wx_payment_wxpay paymentInfo = payBll.GetModelByWid(wid);
            WXLogs.AddLog(wid, payTmpType, funName, "取到wid=" + wid, 1);



            string appId = ReadXmlValue(req, "xml/appid");             //公众账号id
            string mchId = ReadXmlValue(req, "xml/mch_id");            //商户号

            string result_code = ReadXmlValue(req, "xml/result_code"); //业务结果

            if (result_code.Trim().ToLower() == "fail")
            {
                //支付失败
                string err_code     = ReadXmlValue(req, "xml/err_code");
                string err_code_des = ReadXmlValue(req, "xml/err_code_des");
                WXLogs.AddLog(wid, payTmpType, funName, "业务结果处理错误err_code:" + err_code + "[err_code_des]:" + err_code_des, 0);
                WriteContent("fail", "业务结果处理错误err_code:" + err_code + "[err_code_des]:" + err_code_des);
                return;
            }
            //支付成功
            string openid = ReadXmlValue(req, "xml/openid");
            //金额,以分为单位
            string total_fee = ReadXmlValue(req, "xml/total_fee");

            string out_trade_no = ReadXmlValue(req, "xml/out_trade_no");

            string transaction_id = ReadXmlValue(req, "xml/transaction_id");

            WXLogs.AddLog(wid, payTmpType, "notify_url ProcessNotify", "支付成功了:openid=" + openid + " out_trade_no=" + out_trade_no + " transaction_id=" + transaction_id + " total_fee(分)=" + total_fee + " result_code=" + result_code + " orderid=" + otid + " wid=" + wid, 1);
            //------------------------------
            //处理业务开始
            //处理数据库逻辑
            //注意交易单不要重复处理
            //注意判断返回金额
            //------------------------------
            wxOrderTmpMgr Totbll = wxOrderTmpMgr.instance();
            string        ret    = Totbll.ProcessPaySuccess_wx("notify_url", out_trade_no, transaction_id, result_code, MyCommFun.Str2Int(total_fee), otid, wid);

            ret = ret == "" ? "处理数据同步发送成功" : ret;

            WXLogs.AddLog(wid, payTmpType, funName, ret, 1);

            //------------------------------
            //处理业务完毕
            //------------------------------
            //回复服务器处理成功
            WriteContent("success");
        }
        /// <summary>
        /// 【微支付】 订单付款成功,处理订单:1将订单的状态改成付款完成;
        /// 
        /// </summary>
        /// <param name="beforeFunName"></param>
        /// <param name="notify_id">通知id</param>
        /// <param name="out_trade_no">商户订单号</param>
        /// <param name="transaction_id">订单交易号</param>
        /// <param name="pay_info">支付结果</param>
        /// <param name="total_fee">付款金额(单位为分)</param>
        /// <param name="otid">订单临时表id</param>
        /// <returns>有错误则返回错误信息,正确,则返回空字符串</returns>
        public string ProcessPaySuccess_wx(string beforeFunName, string notify_id, string out_trade_no, string transaction_id, string pay_info, int total_fee, int otid, int wid)
        {
            string payTmpType = "【微支付】";
            total_fee = total_fee / 100;
            BLL.orders orderBll = new BLL.orders();

            string funName = payTmpType + beforeFunName + " ProcessPaySuccess_wx ";

            BLL.wx_logs logBll = new BLL.wx_logs();
            logBll.AddLog(wid, "微支付", funName, "开始执行ProcessPaySuccess_wx方法[otid:" + otid + "]");
            try
            {
                #region 数据同步前
                IList<Model.orders> orderlist = orderBll.GetModelList("id=" + otid + " and order_no='" + out_trade_no + "'");
                if (orderlist == null || orderlist.Count <= 0)
                {
                    logBll.AddLog(wid,payTmpType, funName, "订单号【" + out_trade_no + "】订单号不存在", 0);
                    return "订单号不存在";
                }
                //这个暂时不处理
                if (logBll.ExistsFlg((out_trade_no + otid)))
                {  //如果已经处理过,则不再处理
                    return "";
                }
                logBll.AddFlg(wid,payTmpType, funName, (out_trade_no + otid));//加标志,防止重复提交

                Model.orders orderEntity = orderlist[0];
                if (orderEntity.order_amount > total_fee)
                {
                    return "付款的金额(" + total_fee + ")小于订单的预付款金额(" + orderEntity.order_amount + ")信息,直接退款";
                }
                orderEntity.notify_id = notify_id;
                orderEntity.trade_no = transaction_id;
                orderEntity.pay_info = pay_info;
                orderEntity.order_amount = total_fee;
                orderEntity.payment_time = DateTime.Now;
                orderEntity.status = 2;
                orderEntity.payment_status = 2;

                //判断是否需要立即发货
                if (orderEntity.express_status == 0)
                {
                    //立即发货
                    FaHuoProc fahuo = new FaHuoProc();
                    
                    BLL.wx_payment_wxpay payBll = new BLL.wx_payment_wxpay();
                    Model.wx_payment_wxpay paymentInfo = payBll.GetModelByWid(wid);
                    Dictionary<string, object> fahuoDict = fahuo.fahuomgr(paymentInfo, orderEntity);
                    string errcode = fahuoDict["errcode"].ToString();
                    string errmsg = fahuoDict["errmsg"].ToString();
                    orderEntity.fahuoCode = errcode;
                    orderEntity.fahuoMsg = errmsg;
                    if (errcode == "0")
                    {
                        orderEntity.express_status = 2;
                        orderEntity.express_time = DateTime.Now;
                    }
                    else
                    {
                        orderEntity.express_status =1;
                    }
                }

                bool ret = orderBll.Update(orderEntity);
                if (!ret)
                {
                    logBll.AddLog(wid,payTmpType, funName, "订单号【" + out_trade_no + "】支付成功后处理数据失败", 0);
                    return "订单号【" + out_trade_no + "】支付成功后处理数据失败";
                }

                logBll.AddLog(payTmpType, funName, "订单号【" + out_trade_no + "】支付成功后,处理数据成功", 1);
                return "";

                #endregion

            }
            catch (Exception ex)
            {

                logBll.AddLog(wid,payTmpType, funName, "订单号【" + out_trade_no + "】支付成功后处理数据同步出现错误:" + ex.Message, 0);
                return null;
            }

        }
        /// <summary>
        /// 微信退单
        /// </summary>
        /// <param name="dingdan"></param>
        /// <param name="dto"></param>
        /// <param name="returnMsg"></param>
        /// <returns></returns>
        private bool WeChatRefund(wx_hotel_dingdan dingdan, TuidanDto dto, int wid, out string returnMsg)
        {
            bool result = false;
            returnMsg = null;

            var refundResult = _hotelOrderService.GetWeChatRefundParams(wid, dingdan.hotelid.Value, dingdan.id, dto.refundCode);

            //使用系统订单号退单
            if (refundResult != null && refundResult.Tables.Count > 0 && refundResult.Tables[0].Rows.Count > 0)
            {
                var orderNumber = refundResult.Tables[0].Rows[0]["orderNumber"].ToString();
                var transaction_id = refundResult.Tables[0].Rows[0]["transaction_id"].ToString();
                var refundAmount = Convert.ToInt32(refundResult.Tables[0].Rows[0]["refundAmount"]);
                var payAmount = Convert.ToInt32(refundResult.Tables[0].Rows[0]["payAmount"]);


                var wxModel = new BLL.wx_userweixin().GetModel(wid);
                var payInfo = new BLL.wx_payment_wxpay().GetModelByWid(wid);

                var requestHandler = new RequestHandler(null);
                requestHandler.SetParameter("out_trade_no", orderNumber);
                //requestHandler.SetParameter("transaction_id", transaction_id);
                requestHandler.SetParameter("out_refund_no", dto.refundCode);
                requestHandler.SetParameter("appid", wxModel.AppId);
                requestHandler.SetParameter("mch_id", payInfo.mch_id);//商户号
                requestHandler.SetParameter("nonce_str", Guid.NewGuid().ToString().Replace("-", ""));

                //退款金额
                if (PayHelper.IsDebug)
                {
                    requestHandler.SetParameter("total_fee", (payAmount).ToString());
                    requestHandler.SetParameter("refund_fee", (refundAmount).ToString());
                }
                else
                {
                    requestHandler.SetParameter("total_fee", (payAmount * 100).ToString());
                    requestHandler.SetParameter("refund_fee", (refundAmount * 100).ToString());
                }

                requestHandler.SetParameter("op_user_id", wxModel.AppId);
                requestHandler.SetParameter("sign", requestHandler.CreateMd5Sign("key", payInfo.paykey));

                var refundInfo = TenPayV3Helper.Refund(requestHandler.ParseXML(), string.Format(@"{0}{1}", AppDomain.CurrentDomain.BaseDirectory, payInfo.certInfoPath), payInfo.cerInfoPwd);
                var refundOrderResponse = new RefundOrderResponse(refundInfo);

                result = refundOrderResponse.IsSuccess;
                returnMsg = refundOrderResponse.return_msg;
            }

            return result;
        }
        protected string UserOpenId = "";//微信用户openid

        protected void Page_Load(object sender, EventArgs e)
        {
           
            this.BindData();

            LogUtil.WriteLog("============ 单次支付开始 ===============");
            LogUtil.WriteLog(string.Format("传递支付参数:OrderSN={0}、Body={1}、TotalFee={2}、Attach={3}、UserOpenId={4}",
           this.OrderSN, this.Body, this.TotalFee, this.Attach,  this.UserOpenId));


            #region 支付操作============================


            #region 基本参数===========================
            //时间戳 
            TimeStamp = TenpayUtil.getTimestamp();
            //随机字符串 
            NonceStr = TenpayUtil.getNoncestr();

            int  wid = MyCommFun.RequestInt("wid");
            BLL.wx_payment_wxpay wxPayBll = new BLL.wx_payment_wxpay();
            Model.wx_payment_wxpay paymentInfo = wxPayBll.GetModelByWid(wid);

            //创建支付应答对象
            var packageReqHandler = new RequestHandler(Context);
            //初始化
            packageReqHandler.init();

            //设置package订单参数  具体参数列表请参考官方pdf文档,请勿随意设置
            packageReqHandler.setParameter("body", this.Body); //商品信息 127字符
            packageReqHandler.setParameter("appid", PayConfig.AppId);
            packageReqHandler.setParameter("mch_id", PayConfig.MchId);
            packageReqHandler.setParameter("nonce_str", NonceStr.ToLower());
            packageReqHandler.setParameter("notify_url", PayConfig.NotifyUrl);
            packageReqHandler.setParameter("openid", this.UserOpenId);
            packageReqHandler.setParameter("out_trade_no", this.OrderSN); //商家订单号
            packageReqHandler.setParameter("spbill_create_ip", Page.Request.UserHostAddress); //用户的公网ip,不是商户服务器IP
            packageReqHandler.setParameter("total_fee", this.TotalFee); //商品金额,以分为单位(money * 100).ToString()
            packageReqHandler.setParameter("trade_type", "JSAPI");
            if (!string.IsNullOrEmpty(this.Attach))
                packageReqHandler.setParameter("attach", this.Attach);//自定义参数 127字符
       
            #endregion

            #region sign===============================
            Sign = packageReqHandler.CreateMd5Sign("key", PayConfig.AppKey);
            LogUtil.WriteLog("WeiPay 页面  sign:" + Sign);
            #endregion

            #region 获取package包======================
            packageReqHandler.setParameter("sign", Sign);

            string data = packageReqHandler.parseXML();
            LogUtil.WriteLog("WeiPay 页面  package(XML):" + data);

            string prepayXml = HttpUtil.Send(data, "https://api.mch.weixin.qq.com/pay/unifiedorder");
            LogUtil.WriteLog("WeiPay 页面  package(Back_XML):" + prepayXml);

            //获取预支付ID
            var xdoc = new XmlDocument();
            xdoc.LoadXml(prepayXml);
            XmlNode xn = xdoc.SelectSingleNode("xml");
            XmlNodeList xnl = xn.ChildNodes;
            if (xnl.Count > 7)
            {
                PrepayId = xnl[7].InnerText;
                Package = string.Format("prepay_id={0}", PrepayId);
                LogUtil.WriteLog("WeiPay 页面  package:" + Package);
            }
            #endregion

            #region 设置支付参数 输出页面  该部分参数请勿随意修改 ==============
            var paySignReqHandler = new RequestHandler(Context);
            paySignReqHandler.setParameter("appId", PayConfig.AppId);
            paySignReqHandler.setParameter("timeStamp", TimeStamp);
            paySignReqHandler.setParameter("nonceStr", NonceStr);
            paySignReqHandler.setParameter("package", Package);
            paySignReqHandler.setParameter("signType", "MD5");
            PaySign = paySignReqHandler.CreateMd5Sign("key", PayConfig.AppKey);

            LogUtil.WriteLog("WeiPay 页面  paySign:" + PaySign);
            #endregion
            #endregion
        }
Exemple #12
0
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/json";
            BLL.wx_shop_cart cartBll = new BLL.wx_shop_cart();
            string _action = MyCommFun.QueryString("myact");
            string openid = MyCommFun.RequestOpenid();  //得到微信用户的openid
            Dictionary<string, string> jsonDict = new Dictionary<string, string>();
            if (_action == "addCart")
            {
                #region 添加购物车
                try
                {
                    int wid = MyCommFun.RequestInt("wid");
                    int productId = MyCommFun.RequestInt("productid");
                    int skuId = MyCommFun.RequestInt("mid");
                    string skuInfo = MyCommFun.QueryString("attr");
                    int productNum = MyCommFun.RequestInt("bc");
                    decimal totalPrice = (decimal)MyCommFun.RequestFloat("totprice", 0);

                    Model.wx_shop_cart cart = new Model.wx_shop_cart();

                    IList<Model.wx_shop_cart> cartList = cartBll.GetModelList("productId=" + productId + " and openid='" + openid + "' and skuId=" + skuId);
                    bool isAdd = true;
                    if (cartList != null && cartList.Count > 0)
                    {
                        isAdd = false;
                        cart = cartList[0];
                    }
                    if (isAdd)
                    {
                        cart.createDate = DateTime.Now;
                        cart.openid = openid;
                        cart.productId = productId;
                        cart.productNum = productNum;
                        cart.skuId = skuId;
                        cart.skuInfo = skuInfo;
                        cart.totPrice = totalPrice * productNum;
                        cart.wid = wid;
                        int ret = cartBll.Add(cart);
                        if (ret > 0)
                        {
                            jsonDict.Add("errCode", "false");
                        }
                        else
                        {
                            jsonDict.Add("errCode", "true");
                        }
                    }
                    else
                    {

                        cart.openid = openid;

                        cart.productNum += productNum;
                        cart.skuId = skuId;
                        cart.skuInfo = skuInfo;
                        cart.totPrice += totalPrice * productNum;
                        cart.wid = wid;
                        bool ret = cartBll.Update(cart);
                        if (ret)
                        {
                            jsonDict.Add("errCode", "false");
                        }
                        else
                        {
                            jsonDict.Add("errCode", "true");
                        }
                    }

                }
                catch (Exception ex)
                {
                    jsonDict.Add("errCode", "true");
                }
                finally
                {
                    context.Response.Write(MyCommFun.getJsonStr(jsonDict));

                }
                #endregion
            }
            else if (_action == "pcount")
            {
                #region 购物车商品数量
                jsonDict = new Dictionary<string, string>();
                int wid = MyCommFun.RequestInt("wid");
                int count = cartBll.GetRecordCount("wid=" + wid + " and openid='" + openid + "'");
                jsonDict.Add("data", count.ToString());
                context.Response.Write(MyCommFun.getJsonStr(jsonDict));
                #endregion

            }
            else if (_action == "remove")
            {
                #region 移除购物车商品
                jsonDict = new Dictionary<string, string>();
                int cartId = MyCommFun.RequestInt("id");
                cartBll.Delete(cartId);
                jsonDict.Add("errCode", "false");
                context.Response.Write(MyCommFun.getJsonStr(jsonDict));
                #endregion
            }
            else if (_action == "modifyNum")
            {
                #region 修改购物车商品数量
                jsonDict = new Dictionary<string, string>();
                int cartId = MyCommFun.RequestInt("ic");
                int newNum = MyCommFun.RequestInt("bc");
                cartBll.UpdateNum(cartId, newNum);
                jsonDict.Add("errCode", "false");
                context.Response.Write(MyCommFun.getJsonStr(jsonDict));
                #endregion

            }
            else if (_action == "getCity")
            {
                #region 选择省份,改变城市列表
                int privice = MyCommFun.RequestInt("pvid");
                BLL.pre_common_district areaBll = new BLL.pre_common_district();
                IList<Model.pre_common_district> disList = areaBll.GetModelList("upid=" + privice + " and level=2");
                Model.pre_common_district dis;
                StringBuilder jsonStr = new StringBuilder("{\"errCode\":0,\"retCode\":0,\"msgType\":0,\"errMsg\":\"\",\"data\":[");
                for (int i = 0; i < disList.Count; i++)
                {
                    dis = new Model.pre_common_district();
                    if (i != disList.Count - 1)
                    {
                        jsonStr.Append("{\"id\":" + disList[i].id + ",\"name\":\"" + disList[i].name + "\"},");
                    }
                    else
                    {
                        jsonStr.Append("{\"id\":" + disList[i].id + ",\"name\":\"" + disList[i].name + "\"}");
                    }
                }
                jsonStr.Append("]}");
                context.Response.Write(jsonStr);
                #endregion

            }
            else if (_action == "getArea")
            {
                #region 选择城市,改变区域列表
                int ctid = MyCommFun.RequestInt("ctid");
                BLL.pre_common_district areaBll = new BLL.pre_common_district();
                IList<Model.pre_common_district> disList = areaBll.GetModelList("upid=" + ctid + " and level=3");
                Model.pre_common_district dis;
                StringBuilder jsonStr = new StringBuilder("{\"errCode\":0,\"retCode\":0,\"msgType\":0,\"errMsg\":\"\",\"data\":[");
                for (int i = 0; i < disList.Count; i++)
                {
                    dis = new Model.pre_common_district();
                    if (i != disList.Count - 1)
                    {
                        jsonStr.Append("{\"id\":" + disList[i].id + ",\"name\":\"" + disList[i].name + "\"},");
                    }
                    else
                    {
                        jsonStr.Append("{\"id\":" + disList[i].id + ",\"name\":\"" + disList[i].name + "\"}");
                    }
                }
                jsonStr.Append("]}");
                context.Response.Write(jsonStr);
                #endregion

            }
            else if (_action == "order_save")
            {
                #region 保存订单信息
                //获得传参信息
                int wid = MyCommFun.RequestInt("wid");

                int payment_id = MyCommFun.RequestInt("pc");//支付方式:1货到付款;3微支付
                int express_id = MyCommFun.RequestInt("mtype");//物流方式
                // string orderStrList = MyCommFun.QueryString("orderStrList");

                //检查物流方式
                if (express_id == 0)
                {
                    context.Response.Write("{\"errCode\":3, \"msg\":\"对不起,请选择配送方式!\"}");
                    return;
                }
                BLL.wx_shop_user_addr uAddrBll = new BLL.wx_shop_user_addr();
                IList<Model.wx_shop_user_addr> uaddrList = uAddrBll.GetOpenidAddrName(openid, wid);
                if (uaddrList == null || uaddrList.Count <= 0 || uaddrList[0].id <= 0)
                {
                    context.Response.Write("{\"errCode\":3, \"msg\":\"收货地址不存在,无法结算!\"}");
                    return;
                }

                //检查购物车商品
                IList<Model.cartProduct> cartList = cartBll.GetCartList(openid, wid);
                if (cartList == null)
                {
                    context.Response.Write("{\"errCode\":3, \"msg\":\"对不起,购物车为空,无法结算!\"}");
                    return;
                }
                //统计购物车
                decimal payable_amount = cartList.Sum(c => c.totPrice);
                //物流费用
                BLL.express expressBll = new BLL.express();
                Model.express expModel = expressBll.GetModel(express_id);
                //支付方式
                BLL.payment pbll = new BLL.payment();
                Model.payment payModel = pbll.GetModelBypTypeId(payment_id);
                //保存订单=======================================================================
                Model.orders model = new Model.orders();
                model.order_no = "b" + Utils.GetOrderNumber(); //订单号B开头为商品订单

                model.wid = wid;
                model.openid = openid;
                model.modelName = "微商城";
                model.modelCode = "shop";
                model.modelActionName = "";
                model.modelActionId = 0;
                model.user_id = 0;
                model.user_name = "";
                model.payment_id = payment_id;
                model.express_id = express_id;
                model.accept_name = uaddrList[0].contractPerson;
                model.post_code = "";
                model.telphone = uaddrList[0].tel;
                model.mobile = uaddrList[0].tel;
                model.area = uaddrList[0].province;
                model.city = uaddrList[0].city;
                model.district = uaddrList[0].area;
                model.address = uaddrList[0].province + " " + uaddrList[0].city + " " + uaddrList[0].area + " " + uaddrList[0].addrDetail;
                model.message = "";
                model.payable_amount = payable_amount;//应付商品总金额
                model.real_amount = payable_amount;//实际商品总金额,
                model.status = 1;
                model.express_status = 1;
                model.express_fee = expModel.express_fee; //物流费用

                if (payment_id == 1)
                {  //货到付款,需要确认订单
                    model.payment_status = 0; //标记未付款
                }
                else
                {//先款后货
                    model.payment_status = 1; //标记未付款
                }
                bool quicklyFH = false;
                //如果是先款后货的话
                if (payment_id == 3)
                {

                    if (payModel.poundage_type == 1) //百分比
                    {
                        model.payment_fee = model.real_amount * payModel.poundage_amount / 100;
                    }
                    else //固定金额
                    {
                        model.payment_fee = payModel.poundage_amount;
                    }
                    BLL.wx_payment_wxpay wxBll = new BLL.wx_payment_wxpay();
                    Model.wx_payment_wxpay wxpay = wxBll.GetModelByWid(wid);
                    quicklyFH = wxpay.quicklyFH;

                }
                if (quicklyFH)
                {
                    model.express_status = 0;
                }
                //订单总金额=实付商品金额+运费+支付手续费
                model.order_amount = model.real_amount + model.express_fee + model.payment_fee;
                //购物积分,可为负数
                model.point = 0;
                model.add_time = DateTime.Now;
                //商品详细列表
                List<Model.order_goods> gls = new List<Model.order_goods>();
                foreach (Model.cartProduct item in cartList)
                {
                    gls.Add(new Model.order_goods { goods_id = item.productId, goods_title = item.productName, goods_price = item.totPrice, real_price = item.totPrice, quantity = item.productNum, point = 0 });
                }
                model.order_goods = gls;
                int result = new BLL.orders().Add(model);
                if (result < 1)
                {
                    context.Response.Write("{\"errCode\":3, \"msg\":\"订单保存过程中发生错误,请重新提交!\"}");
                    return;
                }

                //清空购物车
                cartBll.RemoveCartInfo(wid, openid);
                //提交成功,返回URL  order_no
                context.Response.Write("{\"errCode\":true, \"payType\":\"" + payment_id + "\", \"order_no\":\"" + model.order_no + "\",\"orderid\":\"" + result + "\",\"wid\":\"" + wid + "\",\"openid\":\"" + openid + "\",\"payable_amount\":\"" + payable_amount + "\", \"msg\":\"恭喜您,订单已成功提交!\"}");
                return;
                #endregion
            }
            else if (_action == "order_canel")
            {
                #region  //取消订单
                int orderid = MyCommFun.RequestInt("order_id");
                BLL.orders oBll = new BLL.orders();
                oBll.UpdateField(orderid, "status=4");
                context.Response.Write("{\"errCode\":true, \"msg\":\"订单已取消!\"}");
                #endregion

            }
            else if (_action == "shouhuo")
            {
                #region  //确认收货
                int orderid = MyCommFun.RequestInt("order_id");
                BLL.orders oBll = new BLL.orders();
                Model.orders order = oBll.GetModel(orderid);
                if (order.payment_id == 1)
                {
                    //货到付款
                    oBll.UpdateField(orderid, "express_status=2,payment_status=2 , status=3");
                }
                else
                {
                    //在线支付
                    oBll.UpdateField(orderid, "express_status=2,payment_status=2 , status=3");
                }

                context.Response.Write("{\"errCode\":true, \"msg\":\"确人收货!\"}");
                #endregion

            }
        }
        private void edit_order_status(HttpContext context)
        {
            //取得管理员登录信息
            Model.manager adminInfo = new Web.UI.ManagePage().GetAdminInfo();
            if (adminInfo == null)
            {
                context.Response.Write("{\"status\": 0, \"msg\": \"未登录或已超时,请重新登录!\"}");
                return;
            }
            //取得站点配置信息
            Model.siteconfig siteConfig = new BLL.siteconfig().loadConfig();
            //取得订单配置信息
            Model.orderconfig orderConfig = new BLL.orderconfig().loadConfig();

            string order_no = MXRequest.GetString("order_no");
            string edit_type = MXRequest.GetString("edit_type");
            if (order_no == "")
            {
                context.Response.Write("{\"status\": 0, \"msg\": \"传输参数有误,无法获取订单号!\"}");
                return;
            }
            if (edit_type == "")
            {
                context.Response.Write("{\"status\": 0, \"msg\": \"无法获取修改订单类型!\"}");
                return;
            }

            BLL.orders bll = new BLL.orders();
            Model.orders model = bll.GetModel(order_no);
            if (model == null)
            {
                context.Response.Write("{\"status\": 0, \"msg\": \"订单号不存在或已被删除!\"}");
                return;
            }
            switch (edit_type.ToLower())
            {
                case "order_confirm": //确认订单
                    //检查权限
                    if (!new BLL.manager_role().Exists(adminInfo.role_id, "order_list", MXEnums.ActionEnum.Confirm.ToString()))
                    {
                        context.Response.Write("{\"status\": 0, \"msg\": \"您没有确认订单的权限!\"}");
                        return;
                    }
                    if (model.status > 1)
                    {
                        context.Response.Write("{\"status\": 0, \"msg\": \"订单已经确认,不能重复处理!\"}");
                        return;
                    }
                    model.status = 2;
                    model.confirm_time = DateTime.Now;
                    if (!bll.Update(model))
                    {
                        context.Response.Write("{\"status\": 0, \"msg\": \"订单确认失败!\"}");
                        return;
                    }
                    new BLL.manager_log().Add(adminInfo.id, adminInfo.user_name, MXEnums.ActionEnum.Confirm.ToString(), "确认订单号:" + model.order_no); //记录日志
                    #region 发送短信或邮件
                    if (orderConfig.confirmmsg > 0)
                    {
                        switch (orderConfig.confirmmsg)
                        {
                            case 1: //短信通知
                                if (string.IsNullOrEmpty(model.mobile))
                                {
                                    context.Response.Write("{\"status\": 1, \"msg\": \"订单确认成功,但无法发送短信<br/ >对方未填写手机号码!\"}");
                                    return;
                                }
                                Model.sms_template smsModel = new BLL.sms_template().GetModel(orderConfig.confirmcallindex); //取得短信内容
                                if (smsModel == null)
                                {
                                    context.Response.Write("{\"status\": 1, \"msg\": \"订单确认成功,但无法发送短信<br/ >短信通知模板不存在!\"}");
                                    return;
                                }
                                //替换标签
                                string msgContent = smsModel.content;
                                msgContent = msgContent.Replace("{webname}", siteConfig.webname);
                                msgContent = msgContent.Replace("{username}", model.user_name);
                                msgContent = msgContent.Replace("{orderno}", model.order_no);
                                msgContent = msgContent.Replace("{amount}", model.order_amount.ToString());
                                //发送短信
                                string tipMsg = string.Empty;
                                bool sendStatus = new BLL.sms_message().Send(model.mobile, msgContent, 2, out tipMsg);
                                if (!sendStatus)
                                {
                                    context.Response.Write("{\"status\": 1, \"msg\": \"订单确认成功,但无法发送短信<br/ >" + tipMsg + "\"}");
                                    return;
                                }
                                break;
                            case 2: //邮件通知
                                //取得用户的邮箱地址
                                if (model.user_id > 0)
                                {
                                    Model.users userModel = new BLL.users().GetModel(model.user_id);
                                    if (userModel == null || string.IsNullOrEmpty(userModel.email))
                                    {
                                        context.Response.Write("{\"status\": 1, \"msg\": \"订单确认成功,但无法发送邮件<br/ >该用户不存在或没有填写邮箱地址。\"}");
                                        return;
                                    }
                                    //取得邮件模板内容
                                    Model.mail_template mailModel = new BLL.mail_template().GetModel(orderConfig.confirmcallindex);
                                    if (mailModel == null)
                                    {
                                        context.Response.Write("{\"status\": 1, \"msg\": \"订单确认成功,但无法发送邮件<br/ >邮件通知模板不存在。\"}");
                                        return;
                                    }
                                    //替换标签
                                    string mailTitle = mailModel.maill_title;
                                    mailTitle = mailTitle.Replace("{username}", model.user_name);
                                    string mailContent = mailModel.content;
                                    mailContent = mailContent.Replace("{webname}", siteConfig.webname);
                                    mailContent = mailContent.Replace("{weburl}", siteConfig.weburl);
                                    mailContent = mailContent.Replace("{webtel}", siteConfig.webtel);
                                    mailContent = mailContent.Replace("{username}", model.user_name);
                                    mailContent = mailContent.Replace("{orderno}", model.order_no);
                                    mailContent = mailContent.Replace("{amount}", model.order_amount.ToString());
                                    //发送邮件
                                    MXMail.sendMail(siteConfig.emailsmtp, siteConfig.emailusername, siteConfig.emailpassword, siteConfig.emailnickname,
                                        siteConfig.emailfrom, userModel.email, mailTitle, mailContent);
                                }
                                break;
                        }
                    }
                    #endregion
                    context.Response.Write("{\"status\": 1, \"msg\": \"订单确认成功!\"}");
                    break;
                case "order_payment": //确认付款
                    //检查权限
                    if (!new BLL.manager_role().Exists(adminInfo.role_id, "order_list", MXEnums.ActionEnum.Confirm.ToString()))
                    {
                        context.Response.Write("{\"status\": 0, \"msg\": \"您没有确认付款的权限!\"}");
                        return;
                    }
                    if (model.status > 1 || model.payment_status == 2)
                    {
                        context.Response.Write("{\"status\": 0, \"msg\": \"订单已确认,不能重复处理!\"}");
                        return;
                    }
                    model.payment_status = 2;
                    model.payment_time = DateTime.Now;
                    model.status = 2;
                    model.confirm_time = DateTime.Now;
                    if (!bll.Update(model))
                    {
                        context.Response.Write("{\"status\": 0, \"msg\": \"订单确认付款失败!\"}");
                        return;
                    }
                    new BLL.manager_log().Add(adminInfo.id, adminInfo.user_name, MXEnums.ActionEnum.Confirm.ToString(), "确认付款订单号:" + model.order_no); //记录日志
                    #region 发送短信或邮件
                    if (orderConfig.confirmmsg > 0)
                    {
                        switch (orderConfig.confirmmsg)
                        {
                            case 1: //短信通知
                                if (string.IsNullOrEmpty(model.mobile))
                                {
                                    context.Response.Write("{\"status\": 1, \"msg\": \"订单确认成功,但无法发送短信<br/ >对方未填写手机号码!\"}");
                                    return;
                                }
                                Model.sms_template smsModel = new BLL.sms_template().GetModel(orderConfig.confirmcallindex); //取得短信内容
                                if (smsModel == null)
                                {
                                    context.Response.Write("{\"status\": 1, \"msg\": \"订单确认成功,但无法发送短信<br/ >短信通知模板不存在!\"}");
                                    return;
                                }
                                //替换标签
                                string msgContent = smsModel.content;
                                msgContent = msgContent.Replace("{webname}", siteConfig.webname);
                                msgContent = msgContent.Replace("{username}", model.user_name);
                                msgContent = msgContent.Replace("{orderno}", model.order_no);
                                msgContent = msgContent.Replace("{amount}", model.order_amount.ToString());
                                //发送短信
                                string tipMsg = string.Empty;
                                bool sendStatus = new BLL.sms_message().Send(model.mobile, msgContent, 2, out tipMsg);
                                if (!sendStatus)
                                {
                                    context.Response.Write("{\"status\": 1, \"msg\": \"订单确认成功,但无法发送短信<br/ >" + tipMsg + "\"}");
                                    return;
                                }
                                break;
                            case 2: //邮件通知
                                //取得用户的邮箱地址
                                if (model.user_id > 0)
                                {
                                    Model.users userModel = new BLL.users().GetModel(model.user_id);
                                    if (userModel == null || string.IsNullOrEmpty(userModel.email))
                                    {
                                        context.Response.Write("{\"status\": 1, \"msg\": \"订单确认成功,但无法发送邮件<br/ >该用户不存在或没有填写邮箱地址。\"}");
                                        return;
                                    }
                                    //取得邮件模板内容
                                    Model.mail_template mailModel = new BLL.mail_template().GetModel(orderConfig.confirmcallindex);
                                    if (mailModel == null)
                                    {
                                        context.Response.Write("{\"status\": 1, \"msg\": \"订单确认成功,但无法发送邮件<br/ >邮件通知模板不存在。\"}");
                                        return;
                                    }
                                    //替换标签
                                    string mailTitle = mailModel.maill_title;
                                    mailTitle = mailTitle.Replace("{username}", model.user_name);
                                    string mailContent = mailModel.content;
                                    mailContent = mailContent.Replace("{webname}", siteConfig.webname);
                                    mailContent = mailContent.Replace("{weburl}", siteConfig.weburl);
                                    mailContent = mailContent.Replace("{webtel}", siteConfig.webtel);
                                    mailContent = mailContent.Replace("{username}", model.user_name);
                                    mailContent = mailContent.Replace("{orderno}", model.order_no);
                                    mailContent = mailContent.Replace("{amount}", model.order_amount.ToString());
                                    //发送邮件
                                    MXMail.sendMail(siteConfig.emailsmtp, siteConfig.emailusername, siteConfig.emailpassword, siteConfig.emailnickname,
                                        siteConfig.emailfrom, userModel.email, mailTitle, mailContent);
                                }
                                break;
                        }
                    }
                    #endregion
                    context.Response.Write("{\"status\": 1, \"msg\": \"订单确认付款成功!\"}");
                    break;
                case "order_express": //确认发货
                    //检查权限
                    if (!new BLL.manager_role().Exists(adminInfo.role_id, "order_list", MXEnums.ActionEnum.Confirm.ToString()))
                    {
                        context.Response.Write("{\"status\": 0, \"msg\": \"您没有确认发货的权限!\"}");
                        return;
                    }
                    if (model.status > 2 || model.express_status == 2)
                    {
                        context.Response.Write("{\"status\": 0, \"msg\": \"订单已完成或已发货,不能重复处理!\"}");
                        return;
                    }
                    int express_id = MXRequest.GetFormInt("express_id");
                    string express_no = MXRequest.GetFormString("express_no");
                    if (express_id == 0)
                    {
                        context.Response.Write("{\"status\": 0, \"msg\": \"请选择配送方式!\"}");
                        return;
                    }
                    model.express_id = express_id;
                    model.express_no = express_no;
                  
                    model.express_time = DateTime.Now;
                    string ret = "";
                    if (model.payment_id == 3 && model.express_status != 2)
                    { 
                        //通知微信支付,改变发货状态
                        FaHuoProc fahuo = new FaHuoProc();

                        BLL.wx_payment_wxpay payBll = new BLL.wx_payment_wxpay();
                        Model.wx_payment_wxpay paymentInfo = payBll.GetModelByWid(model.wid.Value);
                        Dictionary<string, object> fahuoDict = fahuo.fahuomgr(paymentInfo, model);
                        string errcode = fahuoDict["errcode"].ToString();
                        string errmsg = fahuoDict["errmsg"].ToString();
                        model.fahuoCode = errcode;
                        model.fahuoMsg = errmsg;
                        if (errcode == "0")
                        {
                            model.express_status = 2;
                        }
                        else
                        {
                            ret = "通知微信支付,改变发货状态失败:"+errmsg;
                        }
                    }
                    model.express_status = 2;
                    if (!bll.Update(model))
                    {
                        ret += "订单发货失败!";
                        context.Response.Write("{\"status\": 0, \"msg\": \"" + ret + "\"}");
                        return;
                    }
                    new BLL.manager_log().Add(adminInfo.id, adminInfo.user_name, MXEnums.ActionEnum.Confirm.ToString(), "确认发货订单号:" + model.order_no); //记录日志
                    #region 发送短信或邮件
                    if (orderConfig.expressmsg > 0)
                    {
                        switch (orderConfig.expressmsg)
                        {
                            case 1: //短信通知
                                if (string.IsNullOrEmpty(model.mobile))
                                {
                                    context.Response.Write("{\"status\": 1, \"msg\": \"订单确认成功,但无法发送短信<br/ >对方未填写手机号码!\"}");
                                    return;
                                }
                                Model.sms_template smsModel = new BLL.sms_template().GetModel(orderConfig.expresscallindex); //取得短信内容
                                if (smsModel == null)
                                {
                                    context.Response.Write("{\"status\": 1, \"msg\": \"订单确认成功,但无法发送短信<br/ >短信通知模板不存在!\"}");
                                    return;
                                }
                                //替换标签
                                string msgContent = smsModel.content;
                                msgContent = msgContent.Replace("{webname}", siteConfig.webname);
                                msgContent = msgContent.Replace("{username}", model.user_name);
                                msgContent = msgContent.Replace("{orderno}", model.order_no);
                                msgContent = msgContent.Replace("{amount}", model.order_amount.ToString());
                                //发送短信
                                string tipMsg = string.Empty;
                                bool sendStatus = new BLL.sms_message().Send(model.mobile, msgContent, 2, out tipMsg);
                                if (!sendStatus)
                                {
                                    context.Response.Write("{\"status\": 1, \"msg\": \"订单确认成功,但无法发送短信<br/ >" + tipMsg + "\"}");
                                    return;
                                }
                                break;
                            case 2: //邮件通知
                                //取得用户的邮箱地址
                                if (model.user_id > 0)
                                {
                                    Model.users userModel = new BLL.users().GetModel(model.user_id);
                                    if (userModel == null || string.IsNullOrEmpty(userModel.email))
                                    {
                                        context.Response.Write("{\"status\": 1, \"msg\": \"订单确认成功,但无法发送邮件<br/ >该用户不存在或没有填写邮箱地址。\"}");
                                        return;
                                    }
                                    //取得邮件模板内容
                                    Model.mail_template mailModel = new BLL.mail_template().GetModel(orderConfig.expresscallindex);
                                    if (mailModel == null)
                                    {
                                        context.Response.Write("{\"status\": 1, \"msg\": \"订单确认成功,但无法发送邮件<br/ >邮件通知模板不存在。\"}");
                                        return;
                                    }
                                    //替换标签
                                    string mailTitle = mailModel.maill_title;
                                    mailTitle = mailTitle.Replace("{username}", model.user_name);
                                    string mailContent = mailModel.content;
                                    mailContent = mailContent.Replace("{webname}", siteConfig.webname);
                                    mailContent = mailContent.Replace("{weburl}", siteConfig.weburl);
                                    mailContent = mailContent.Replace("{webtel}", siteConfig.webtel);
                                    mailContent = mailContent.Replace("{username}", model.user_name);
                                    mailContent = mailContent.Replace("{orderno}", model.order_no);
                                    mailContent = mailContent.Replace("{amount}", model.order_amount.ToString());
                                    //发送邮件
                                    MXMail.sendMail(siteConfig.emailsmtp, siteConfig.emailusername, siteConfig.emailpassword, siteConfig.emailnickname,
                                        siteConfig.emailfrom, userModel.email, mailTitle, mailContent);
                                }
                                break;
                        }
                    }
                    #endregion
                    context.Response.Write("{\"status\": 1, \"msg\": \"订单发货成功!\"}");
                    break;
                case "order_complete": //完成订单=========================================
                    //检查权限
                    if (!new BLL.manager_role().Exists(adminInfo.role_id, "order_list", MXEnums.ActionEnum.Confirm.ToString()))
                    {
                        context.Response.Write("{\"status\": 0, \"msg\": \"您没有确认完成订单的权限!\"}");
                        return;
                    }
                    if (model.status > 2)
                    {
                        context.Response.Write("{\"status\": 0, \"msg\": \"订单已经完成,不能重复处理!\"}");
                        return;
                    }
                    model.status = 3;
                    model.complete_time = DateTime.Now;
                    if (!bll.Update(model))
                    {
                        context.Response.Write("{\"status\": 0, \"msg\": \"确认订单完成失败!\"}");
                        return;
                    }
                    //给会员增加积分检查升级
                    if (model.user_id > 0 && model.point > 0)
                    {
                        new BLL.user_point_log().Add(model.user_id, model.user_name, model.point, "购物获得积分,订单号:" + model.order_no, true);
                    }
                    new BLL.manager_log().Add(adminInfo.id, adminInfo.user_name, MXEnums.ActionEnum.Confirm.ToString(), "确认交易完成订单号:" + model.order_no); //记录日志
                    #region 发送短信或邮件
                    if (orderConfig.completemsg > 0)
                    {
                        switch (orderConfig.completemsg)
                        {
                            case 1: //短信通知
                                if (string.IsNullOrEmpty(model.mobile))
                                {
                                    context.Response.Write("{\"status\": 1, \"msg\": \"订单确认成功,但无法发送短信<br/ >对方未填写手机号码!\"}");
                                    return;
                                }
                                Model.sms_template smsModel = new BLL.sms_template().GetModel(orderConfig.completecallindex); //取得短信内容
                                if (smsModel == null)
                                {
                                    context.Response.Write("{\"status\": 1, \"msg\": \"订单确认成功,但无法发送短信<br/ >短信通知模板不存在!\"}");
                                    return;
                                }
                                //替换标签
                                string msgContent = smsModel.content;
                                msgContent = msgContent.Replace("{webname}", siteConfig.webname);
                                msgContent = msgContent.Replace("{username}", model.user_name);
                                msgContent = msgContent.Replace("{orderno}", model.order_no);
                                msgContent = msgContent.Replace("{amount}", model.order_amount.ToString());
                                //发送短信
                                string tipMsg = string.Empty;
                                bool sendStatus = new BLL.sms_message().Send(model.mobile, msgContent, 2, out tipMsg);
                                if (!sendStatus)
                                {
                                    context.Response.Write("{\"status\": 1, \"msg\": \"订单确认成功,但无法发送短信<br/ >" + tipMsg + "\"}");
                                    return;
                                }
                                break;
                            case 2: //邮件通知
                                //取得用户的邮箱地址
                                if (model.user_id > 0)
                                {
                                    Model.users userModel = new BLL.users().GetModel(model.user_id);
                                    if (userModel == null || string.IsNullOrEmpty(userModel.email))
                                    {
                                        context.Response.Write("{\"status\": 1, \"msg\": \"订单确认成功,但无法发送邮件<br/ >该用户不存在或没有填写邮箱地址。\"}");
                                        return;
                                    }
                                    //取得邮件模板内容
                                    Model.mail_template mailModel = new BLL.mail_template().GetModel(orderConfig.completecallindex);
                                    if (mailModel == null)
                                    {
                                        context.Response.Write("{\"status\": 1, \"msg\": \"订单确认成功,但无法发送邮件<br/ >邮件通知模板不存在。\"}");
                                        return;
                                    }
                                    //替换标签
                                    string mailTitle = mailModel.maill_title;
                                    mailTitle = mailTitle.Replace("{username}", model.user_name);
                                    string mailContent = mailModel.content;
                                    mailContent = mailContent.Replace("{webname}", siteConfig.webname);
                                    mailContent = mailContent.Replace("{weburl}", siteConfig.weburl);
                                    mailContent = mailContent.Replace("{webtel}", siteConfig.webtel);
                                    mailContent = mailContent.Replace("{username}", model.user_name);
                                    mailContent = mailContent.Replace("{orderno}", model.order_no);
                                    mailContent = mailContent.Replace("{amount}", model.order_amount.ToString());
                                    //发送邮件
                                    MXMail.sendMail(siteConfig.emailsmtp, siteConfig.emailusername, siteConfig.emailpassword, siteConfig.emailnickname,
                                        siteConfig.emailfrom, userModel.email, mailTitle, mailContent);
                                }
                                break;
                        }
                    }
                    #endregion
                    context.Response.Write("{\"status\": 1, \"msg\": \"确认订单完成成功!\"}");
                    break;
                case "order_cancel": //取消订单==========================================
                    //检查权限
                    if (!new BLL.manager_role().Exists(adminInfo.role_id, "order_list", MXEnums.ActionEnum.Cancel.ToString()))
                    {
                        context.Response.Write("{\"status\": 0, \"msg\": \"您没有取消订单的权限!\"}");
                        return;
                    }
                    if (model.status > 2)
                    {
                        context.Response.Write("{\"status\": 0, \"msg\": \"订单已经完成,不能取消订单!\"}");
                        return;
                    }
                    model.status = 4;
                    if (!bll.Update(model))
                    {
                        context.Response.Write("{\"status\": 0, \"msg\": \"取消订单失败!\"}");
                        return;
                    }
                    int check_revert1 = MXRequest.GetFormInt("check_revert");
                    if (check_revert1 == 1)
                    {
                        //如果存在积分换购则返还会员积分
                        if (model.user_id > 0 && model.point < 0)
                        {
                            new BLL.user_point_log().Add(model.user_id, model.user_name, (model.point * -1), "取消订单返还积分,订单号:" + model.order_no, false);
                        }
                        //如果已支付则退还金额到会员账户
                        if (model.user_id > 0 && model.payment_status == 2 && model.order_amount > 0)
                        {
                            new BLL.user_amount_log().Add(model.user_id, model.user_name, MXEnums.AmountTypeEnum.BuyGoods.ToString(), model.order_amount, "取消订单退还金额,订单号:" + model.order_no);
                        }
                    }
                    new BLL.manager_log().Add(adminInfo.id, adminInfo.user_name, MXEnums.ActionEnum.Cancel.ToString(), "取消订单号:" + model.order_no); //记录日志
                    context.Response.Write("{\"status\": 1, \"msg\": \"取消订单成功!\"}");
                    break;
                case "order_invalid": //作废订单==========================================
                    //检查权限
                    if (!new BLL.manager_role().Exists(adminInfo.role_id, "order_list", MXEnums.ActionEnum.Invalid.ToString()))
                    {
                        context.Response.Write("{\"status\": 0, \"msg\": \"您没有作废订单的权限!\"}");
                        return;
                    }
                    if (model.status != 3)
                    {
                        context.Response.Write("{\"status\": 0, \"msg\": \"订单尚未完成,不能作废订单!\"}");
                        return;
                    }
                    model.status = 5;
                    if (!bll.Update(model))
                    {
                        context.Response.Write("{\"status\": 0, \"msg\": \"作废订单失败!\"}");
                        return;
                    }
                    int check_revert2 = MXRequest.GetFormInt("check_revert");
                    if (check_revert2 == 1)
                    {
                        //扣除购物赠送的积分
                        if (model.user_id > 0 && model.point > 0)
                        {
                            new BLL.user_point_log().Add(model.user_id, model.user_name, (model.point * -1), "作废订单扣除积分,订单号:" + model.order_no, false);
                        }
                        //退还金额到会员账户
                        if (model.user_id > 0 && model.order_amount > 0)
                        {
                            new BLL.user_amount_log().Add(model.user_id, model.user_name, MXEnums.AmountTypeEnum.BuyGoods.ToString(), model.order_amount, "取消订单退还金额,订单号:" + model.order_no);
                        }
                    }
                    new BLL.manager_log().Add(adminInfo.id, adminInfo.user_name, MXEnums.ActionEnum.Invalid.ToString(), "作废订单号:" + model.order_no); //记录日志
                    context.Response.Write("{\"status\": 1, \"msg\": \"作废订单成功!\"}");
                    break;
                case "edit_accept_info": //修改收货信息====================================
                    //检查权限
                    if (!new BLL.manager_role().Exists(adminInfo.role_id, "order_list", MXEnums.ActionEnum.Edit.ToString()))
                    {
                        context.Response.Write("{\"status\": 0, \"msg\": \"您没有修改收货信息的权限!\"}");
                        return;
                    }
                    if (model.express_status == 2)
                    {
                        context.Response.Write("{\"status\": 0, \"msg\": \"订单已经发货,不能修改收货信息!\"}");
                        return;
                    }
                    string accept_name = MXRequest.GetFormString("accept_name");
                    string province = MXRequest.GetFormString("province");
                    string city = MXRequest.GetFormString("city");
                    string area = MXRequest.GetFormString("area");
                    string address = MXRequest.GetFormString("address");
                    string post_code = MXRequest.GetFormString("post_code");
                    string mobile = MXRequest.GetFormString("mobile");
                    string telphone = MXRequest.GetFormString("telphone");

                    if (accept_name == "")
                    {
                        context.Response.Write("{\"status\": 0, \"msg\": \"请填写收货人姓名!\"}");
                        return;
                    }
                    if (area == "")
                    {
                        context.Response.Write("{\"status\": 0, \"msg\": \"请选择所在地区!\"}");
                        return;
                    }
                    if (address == "")
                    {
                        context.Response.Write("{\"status\": 0, \"msg\": \"请填写详细的送货地址!\"}");
                        return;
                    }
                    if (mobile == "" && telphone == "")
                    {
                        context.Response.Write("{\"status\": 0, \"msg\": \"联系手机或电话至少填写一项!\"}");
                        return;
                    }

                    model.accept_name = accept_name;
                    model.area = province + "," + city + "," + area;
                    model.address = address;
                    model.post_code = post_code;
                    model.mobile = mobile;
                    model.telphone = telphone;
                    if (!bll.Update(model))
                    {
                        context.Response.Write("{\"status\": 0, \"msg\": \"修改收货人信息失败!\"}");
                        return;
                    }
                    new BLL.manager_log().Add(adminInfo.id, adminInfo.user_name, MXEnums.ActionEnum.Edit.ToString(), "修改收货信息,订单号:" + model.order_no); //记录日志
                    context.Response.Write("{\"status\": 1, \"msg\": \"修改收货人信息成功!\"}");
                    break;
                case "edit_order_remark": //修改订单备注=================================
                    string remark = MXRequest.GetFormString("remark");
                    if (remark == "")
                    {
                        context.Response.Write("{\"status\": 0, \"msg\": \"请填写订单备注内容!\"}");
                        return;
                    }
                    model.remark = remark;
                    if (!bll.Update(model))
                    {
                        context.Response.Write("{\"status\": 0, \"msg\": \"修改订单备注失败!\"}");
                        return;
                    }
                    new BLL.manager_log().Add(adminInfo.id, adminInfo.user_name, MXEnums.ActionEnum.Edit.ToString(), "修改订单备注,订单号:" + model.order_no); //记录日志
                    context.Response.Write("{\"status\": 1, \"msg\": \"修改订单备注成功!\"}");
                    break;
                case "edit_real_amount": //修改商品总金额================================
                    //检查权限
                    if (!new BLL.manager_role().Exists(adminInfo.role_id, "order_list", MXEnums.ActionEnum.Edit.ToString()))
                    {
                        context.Response.Write("{\"status\": 0, \"msg\": \"您没有修改商品金额的权限!\"}");
                        return;
                    }
                    if (model.status > 1)
                    {
                        context.Response.Write("{\"status\": 0, \"msg\": \"订单已经确认,不能修改金额!\"}");
                        return;
                    }
                    decimal real_amount = MXRequest.GetFormDecimal("real_amount", 0);
                    model.real_amount = real_amount;
                    if (!bll.Update(model))
                    {
                        context.Response.Write("{\"status\": 0, \"msg\": \"修改商品总金额失败!\"}");
                        return;
                    }
                    new BLL.manager_log().Add(adminInfo.id, adminInfo.user_name, MXEnums.ActionEnum.Edit.ToString(), "修改商品金额,订单号:" + model.order_no); //记录日志
                    context.Response.Write("{\"status\": 1, \"msg\": \"修改商品总金额成功!\"}");
                    break;
                case "edit_express_fee": //修改配送费用==================================
                    //检查权限
                    if (!new BLL.manager_role().Exists(adminInfo.role_id, "order_list", MXEnums.ActionEnum.Edit.ToString()))
                    {
                        context.Response.Write("{\"status\": 0, \"msg\": \"您没有配送费用的权限!\"}");
                        return;
                    }
                    if (model.status > 1)
                    {
                        context.Response.Write("{\"status\": 0, \"msg\": \"订单已经确认,不能修改金额!\"}");
                        return;
                    }
                    decimal express_fee = MXRequest.GetFormDecimal("express_fee", 0);
                    model.express_fee = express_fee;
                    if (!bll.Update(model))
                    {
                        context.Response.Write("{\"status\": 0, \"msg\": \"修改配送费用失败!\"}");
                        return;
                    }
                    new BLL.manager_log().Add(adminInfo.id, adminInfo.user_name, MXEnums.ActionEnum.Edit.ToString(), "修改配送费用,订单号:" + model.order_no); //记录日志
                    context.Response.Write("{\"status\": 1, \"msg\": \"修改配送费用成功!\"}");
                    break;
                case "edit_payment_fee": //修改支付手续费=================================
                    //检查权限
                    if (!new BLL.manager_role().Exists(adminInfo.role_id, "order_list", MXEnums.ActionEnum.Edit.ToString()))
                    {
                        context.Response.Write("{\"status\": 0, \"msg\": \"您没有修改支付手续费的权限!\"}");
                        return;
                    }
                    if (model.status > 1)
                    {
                        context.Response.Write("{\"status\": 0, \"msg\": \"订单已经确认,不能修改金额!\"}");
                        return;
                    }
                    decimal payment_fee = MXRequest.GetFormDecimal("payment_fee", 0);
                    model.payment_fee = payment_fee;
                    if (!bll.Update(model))
                    {
                        context.Response.Write("{\"status\": 0, \"msg\": \"修改支付手续费失败!\"}");
                        return;
                    }
                    new BLL.manager_log().Add(adminInfo.id, adminInfo.user_name, MXEnums.ActionEnum.Edit.ToString(), "修改支付手续费,订单号:" + model.order_no); //记录日志
                    context.Response.Write("{\"status\": 1, \"msg\": \"修改支付手续费成功!\"}");
                    break;
            }

        }
Exemple #14
0
        //public static TenPayInfo TenPayInfo
        //{
        //    get
        //    {
        //        if (_tenPayInfo == null)
        //        {
        //            _tenPayInfo =
        //                TenPayInfoCollection.Data[System.Configuration.ConfigurationManager.AppSettings["WeixinPay_PartnerId"]];
        //        }
        //        return _tenPayInfo;
        //    }
        //}
        /// <summary>
        /// 微信支付:生成请求数据
        /// </summary>
        /// <param name="openid">微信用户id</openid>
        /// <param name="ttFee">商品总价格</param>
        /// <param name="busiBody"></param>
        /// <returns></returns>
        protected void WxPayData(decimal ttFee, string busiBody, string out_trade_no)
        {
            WxPayHelper wxPayHelper = new WxPayHelper();

            BLL.wx_payment_wxpay   wxPayBll    = new BLL.wx_payment_wxpay();
            Model.wx_payment_wxpay paymentInfo = wxPayBll.GetModelByWid(wid);

            // //先设置基本信息
            // string partnerId = paymentInfo.partnerId;// "1218574001";//
            // string appId = paymentInfo.appId;// "wxa9b8e33e48ac5e0f";//
            // string partnerKey = paymentInfo.partnerKey;// "huyuxianghuyuxianghuyuxiang12345";//
            // //paysignkey(非appkey)
            // string appKey = paymentInfo.paySignKey; //"nwRmqgvSG08pe3vU5qzBLb7Bvih0WOABGzUPvqgFqE0iSkJlJ8wh7JlLYy2cXFgFA3v1bM8eTDm1y1UcyeW9IGq2py2qei7J5xDoVR9lfO3cS6fMjFbMQeeqBRit0bKp";//

            // wxPayHelper.SetAppId(appId);
            // wxPayHelper.SetAppKey(appKey);
            // wxPayHelper.SetPartnerKey(partnerKey);
            // wxPayHelper.SetSignType("SHA1");
            // //设置请求package信息
            // wxPayHelper.SetParameter("bank_type", "WX");
            // wxPayHelper.SetParameter("body", busiBody);
            // wxPayHelper.SetParameter("attach",wid+"|"+busiBody);
            // wxPayHelper.SetParameter("partner", partnerId);
            // wxPayHelper.SetParameter("out_trade_no", out_trade_no);
            // wxPayHelper.SetParameter("total_fee", ((int)(ttFee * 100)).ToString());
            // wxPayHelper.SetParameter("fee_type", "1");
            //// wxPayHelper.SetParameter("notify_url", "http://" + HttpContext.Current.Request.Url.Authority + "/api/payment/wxpay/notify_url.aspx?wid="+wid);

            // wxPayHelper.SetParameter("notify_url", "http://" + HttpContext.Current.Request.Url.Authority + "/api/payment/wxpay/notify_url.aspx");//不能带参数
            // wxPayHelper.SetParameter("spbill_create_ip", MXRequest.GetIP());
            // wxPayHelper.SetParameter("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));
            // //---------有效期截至日期------

            // wxPayHelper.SetParameter("time_expire", DateTime.Now.AddMinutes(expireMinute).ToString("yyyyMMddHHmmss"));

            // wxPayHelper.SetParameter("input_charset", "UTF-8");
            // packageValue = wxPayHelper.CreateBizPackage();

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


            //通过,用code换取access_token
            //var openIdResult = OAuthApi.GetAccessToken(paymentInfo.appId, "a891edd957f2aede546f9256096bf95a", code);
            //if (openIdResult.errcode != ReturnCode.请求成功)
            //{
            //    return Content("错误:" + openIdResult.errmsg);
            //}

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

            string sp_billno = Request["order_no"];
            //当前时间 yyyyMMdd
            string date = DateTime.Now.ToString("yyyyMMdd");

            if (null == sp_billno)
            {
                //生成订单10位序列号,此处用时间和随机数生成,商户根据自己调整,保证唯一
                sp_billno = DateTime.Now.ToString("HHmmss") + TenPayV3Util.BuildRandomStr(28);
            }
            else
            {
                sp_billno = Request["order_no"].ToString();
            }

            //创建支付应答对象
            Senparc.Weixin.MP.TenPayLibV3.RequestHandler packageReqHandler = new Senparc.Weixin.MP.TenPayLibV3.RequestHandler(null);
            //初始化
            packageReqHandler.Init();

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

            //设置package订单参数
            packageReqHandler.SetParameter("appid", paymentInfo.appId);                                    //公众账号ID
            packageReqHandler.SetParameter("mch_id", paymentInfo.partnerId);                               //商户号
            packageReqHandler.SetParameter("nonce_str", nonceStr);                                         //随机字符串
            packageReqHandler.SetParameter("body", "aaa");                                                 //商品信息
            packageReqHandler.SetParameter("out_trade_no", sp_billno);                                     //商家订单号
            packageReqHandler.SetParameter("total_fee", "100");                                            //商品金额,以分为单位(money * 100).ToString()
            packageReqHandler.SetParameter("spbill_create_ip", Request.UserHostAddress);                   //用户的公网ip,不是商户服务器IP
            packageReqHandler.SetParameter("notify_url", "http://ddd.com");                                //接收财付通通知的URL
            packageReqHandler.SetParameter("trade_type", Senparc.Weixin.MP.TenPayV3Type.JSAPI.ToString()); //交易类型
            packageReqHandler.SetParameter("openid", "oFo2Hjq6_yMhyz6cQ2MZtmxODOVU");                      //用户的openId

            string sign = packageReqHandler.CreateMd5Sign("key", paymentInfo.partnerKey);

            packageReqHandler.SetParameter("sign", sign);                           //签名

            string data = packageReqHandler.ParseXML();

            var    result   = TenPayV3.Unifiedorder(data);
            var    res      = XDocument.Parse(result);
            string prepayId = res.Element("xml").Element("prepay_id").Value;

            //设置支付参数
            Senparc.Weixin.MP.TenPayLibV3.RequestHandler paySignReqHandler = new Senparc.Weixin.MP.TenPayLibV3.RequestHandler(null);
            paySignReqHandler.SetParameter("appId", paymentInfo.appId);
            paySignReqHandler.SetParameter("timeStamp", timeStamp);
            paySignReqHandler.SetParameter("nonceStr", nonceStr);
            paySignReqHandler.SetParameter("package", string.Format("prepay_id={0}", prepayId));
            paySignReqHandler.SetParameter("signType", "MD5");
            paySign = paySignReqHandler.CreateMd5Sign("key", paymentInfo.partnerKey);

            payaddid        = paymentInfo.appId;
            paytimeStamp    = timeStamp;
            paynonceStr     = nonceStr;
            paypackageValue = packageValue;
            paypaySign      = paySign;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            //int wid = MyCommFun.RequestWid();
            int wid =0;
             BLL.wx_logs logBll = new  BLL.wx_logs();
            logBll.AddLog("【微支付】微信预定", "notify_url Page_Load", "从微支付返回到notify_url.aspx页面", 1);
            BLL.wx_payment_wxpay payBll = new BLL.wx_payment_wxpay();

         

            ResponseHandler resHandler = new ResponseHandler(Context);
    
            resHandler.init();
            //取wid
            string attach = resHandler.getParameter("attach");
            string[] attachArr = attach.Split('|');
            wid = MyCommFun.Str2Int(attachArr[0]);
            int otid = MyCommFun.Str2Int(attachArr[1]);
            Model.wx_payment_wxpay paymentInfo = payBll.GetModelByWid(wid);
            logBll.AddLog(wid,"【微支付】微信预定", "notify_url Page_Load", "取到wid="+wid, 1);
            resHandler.setKey(paymentInfo.partnerKey, paymentInfo.paySignKey);// TenpayUtil.key, TenpayUtil.appkey);
            //resHandler.setKey("huyuxianghuyuxianghuyuxiang12345", "nwRmqgvSG08pe3vU5qzBLb7Bvih0WOABGzUPvqgFqE0iSkJlJ8wh7JlLYy2cXFgFA3v1bM8eTDm1y1UcyeW9IGq2py2qei7J5xDoVR9lfO3cS6fMjFbMQeeqBRit0bKp");
            //判断签名
            if (resHandler.isTenpaySign())
            {
                logBll.AddLog(wid,"【微支付】微信预定", "notify_url Page_Load", "resHandler.isTenpaySign()", 1);
                if (resHandler.isWXsign())
                {
                    //商户在收到后台通知后根据通知ID向财付通发起验证确认,采用后台系统调用交互模式
                    string notify_id = resHandler.getParameter("notify_id");
                    //取结果参数做业务处理
                    string out_trade_no = resHandler.getParameter("out_trade_no");
                    //财付通订单号
                    string transaction_id = resHandler.getParameter("transaction_id");
                    //金额,以分为单位
                    string total_fee = resHandler.getParameter("total_fee");
                    //如果有使用折扣券,discount有值,total_fee+discount=原请求的total_fee
                    string discount = resHandler.getParameter("discount");
                    //支付结果
                    string trade_state = resHandler.getParameter("trade_state");

                  
                    string pay_info = resHandler.getParameter("pay_info");
                   

                    logBll.AddLog(wid,"【微支付】微信预定", "notify_url Page_Load", "notify_id=" + notify_id + " out_trade_no=" + out_trade_no + " transaction_id=" + transaction_id + " total_fee=" + total_fee + " trade_state=" + trade_state + " orderid=" + otid + " wid=" + wid + "  pay_info=" + pay_info, 1);

                    //即时到账,支付成功
                    if ("0".Equals(trade_state))
                    {
                        logBll.AddLog(wid,"【微支付】微信预定", "notify_url Page_Load", "支付成功了", 1);
                        //------------------------------
                        //处理业务开始
                        //------------------------------
                        wxOrderTmpMgr Totbll = wxOrderTmpMgr.instance();
                        string ret = Totbll.ProcessPaySuccess_wx("notify_url", notify_id, out_trade_no, transaction_id, pay_info, MyCommFun.Str2Int(total_fee), otid,wid);
                        ret = ret == "" ? "处理数据同步发送成功" : ret;
                        logBll.AddLog(wid,"微信预定", "【微支付】notify_url Page_Load", ret, 1);
                        //处理数据库逻辑
                        //注意交易单不要重复处理
                        //注意判断返回金额


                        //------------------------------
                        //处理业务完毕
                        //------------------------------

                        //给财付通系统发送成功信息,财付通系统收到此结果后不再进行后续通知
                        Response.Write("success");
                    }
                    else
                    {
                        logBll.AddLog(wid,"【微支付】微信预定", "notify_url Page_Load", "支付失败", 1);
                        Response.Write("支付失败");
                    }
                    //回复服务器处理成功
                    Response.Write("success");
                }

                else
                {//SHA1签名失败
                    logBll.AddLog("微信预定", "【微支付】notify_url Page_Load", "fail -SHA1 failed", 0);
                    Response.Write("fail -SHA1 failed");
                    Response.Write(resHandler.getDebugInfo());
                }
            }
            else
            {//md5签名失败
                logBll.AddLog(wid, "微信预定", "【微支付】notify_url Page_Load", "fail -md5 failed", 0);
                Response.Write("fail -md5 failed");
                Response.Write(resHandler.getDebugInfo());
            }

        }
Exemple #16
0
        protected void btnAgreeRefund_Click(object sender, EventArgs e)
        {
            try
            {
                var refundBll    = new BLL.wx_diancai_tuidan_manage();
                var refundResult = refundBll.GetWeChatRefundParams(shopid, orderID, refundCode);

                //使用系统订单号退单
                if (refundResult != null && refundResult.Tables.Count > 0 && refundResult.Tables[0].Rows.Count > 0)
                {
                    var orderNumber    = refundResult.Tables[0].Rows[0]["orderNumber"].ToString();
                    var transaction_id = refundResult.Tables[0].Rows[0]["transaction_id"].ToString();
                    var refundAmount   = Convert.ToInt32(refundResult.Tables[0].Rows[0]["refundAmount"]);
                    var payAmount      = Convert.ToInt32(refundResult.Tables[0].Rows[0]["payAmount"]);

                    var shopInfo = new BLL.wx_diancai_shopinfo().GetModel(shopid);
                    var wxModel  = new BLL.wx_userweixin().GetModel((int)shopInfo.wid);
                    var payInfo  = new BLL.wx_payment_wxpay().GetModelByWid((int)shopInfo.wid);

                    var requestHandler = new RequestHandler(null);
                    requestHandler.SetParameter("out_trade_no", orderNumber);
                    //requestHandler.SetParameter("transaction_id", transaction_id);
                    requestHandler.SetParameter("out_refund_no", refundCode);
                    requestHandler.SetParameter("appid", wxModel.AppId);
                    requestHandler.SetParameter("mch_id", payInfo.mch_id);//商户号
                    requestHandler.SetParameter("nonce_str", Guid.NewGuid().ToString().Replace("-", ""));

                    //退款金额
                    if (PayHelper.IsDebug)
                    {
                        requestHandler.SetParameter("total_fee", (payAmount / 100).ToString());
                        requestHandler.SetParameter("refund_fee", (refundAmount / 100).ToString());
                    }
                    else
                    {
                        requestHandler.SetParameter("total_fee", payAmount.ToString());
                        requestHandler.SetParameter("refund_fee", refundAmount.ToString());
                    }

                    requestHandler.SetParameter("op_user_id", wxModel.AppId);
                    requestHandler.SetParameter("sign", requestHandler.CreateMd5Sign("key", payInfo.paykey));

                    var refundInfo          = TenPayV3Helper.Refund(requestHandler.ParseXML(), string.Format(@"{0}{1}", AppDomain.CurrentDomain.BaseDirectory, payInfo.certInfoPath), payInfo.cerInfoPwd);
                    var refundOrderResponse = new RefundOrderResponse(refundInfo);
                    if (refundOrderResponse.IsSuccess)
                    {
                        new BLL.wx_diancai_tuidan_manage().RefundComplete(refundCode, this.txtRefundReason.Value.Trim());
                        Response.Redirect("diancai_dingdanRefund_manage.aspx");
                    }
                    else
                    {
                        Response.Write(refundOrderResponse.return_msg);
                        List();
                    }
                }
            }
            catch (Exception exception)
            {
                Response.Write(exception.Message);
                Response.Write(exception.StackTrace);
                List();
            }
        }
Exemple #17
0
        private bool DoAdd(int _id)
        {
            Model.wx_userweixin weixin = GetWeiXinCode();

            bool result = false;
            BLL.payment bll = new BLL.payment();
            Model.payment model = new Model.payment();

            model.title = txtTitle.Text.Trim();
            if (cbIsLock.Checked == true)
            {
                model.is_lock = 0;
            }
            else
            {
                model.is_lock = 1;
            }
            model.sort_id = int.Parse(txtSortId.Text.Trim());
            model.poundage_type = int.Parse(rblPoundageType.SelectedValue);
            model.poundage_amount = decimal.Parse(txtPoundageAmount.Text.Trim());
            model.img_url = txtImgUrl.Text.Trim();
            model.remark = txtRemark.Text;
            model.pTypeId = _id;
            model.wid = weixin.id;
            model.api_path = hidApi_path.Value;
            if (_id==2)
            {
                //支付宝
                BLL.wx_payment_alipay aliBll = new BLL.wx_payment_alipay();
                Model.wx_payment_alipay alipay = new Model.wx_payment_alipay();
                alipay.ownerName = txtAlipaySellerEmail.Text.Trim();
                alipay.partner = txtAlipayPartner.Text.Trim();
                alipay.e_key = txtAlipayKey.Text.Trim();
                alipay.private_key = txtprivate_key.Text.Trim();
                alipay.public_key = txtpublic_key.Text.Trim();
                alipay.sign_type = "MD5";
                alipay.wid = weixin.id;
                alipay.createDate = DateTime.Now;
                aliBll.Add(alipay);
            }
            else if (_id==3)
            {
                //微支付
                BLL.wx_payment_wxpay wxpayBll = new BLL.wx_payment_wxpay();
                Model.wx_payment_wxpay wxpay = new Model.wx_payment_wxpay();
                wxpay.wid = weixin.id;

                //财付通--相关信息
                wxpay.partnerId = txtpartnerId.Text.Trim();
                wxpay.partnerKey = txtpartnerKey.Text.Trim();
                wxpay.CertInfoPath = txtCertInfoPath.Text.Trim();
                wxpay.partnerPwd = txtPartnerPwd.Text.Trim();

                //微信--相关配置
                wxpay.paySignKey = txtpaySignKey.Text.Trim();
                wxpay.appId = txtAppId.Text.Trim();
                wxpay.quicklyFH = rblQuicklyFH.SelectedItem.Value == "1" ? true : false;
                wxpay.createDate = DateTime.Now;
                wxpayBll.Add(wxpay);
            }

            if (bll.Add(model)>0)
            {
                AddAdminLog(MXEnums.ActionEnum.Edit.ToString(), "添加支付方式:" + model.title); //记录日志
                result = true;
            }

            return result;
        }
Exemple #18
0
        public void UnifiedOrder(string request)
        {
            try
            {
                var requestModel = JSONHelper.Deserialize <UnifiedOrderEntity>(request);

                //通过wid获取公众号的信息
                var wxModel   = new BLL.wx_userweixin().GetModel(requestModel.wid);
                var wxPayInfo = new BLL.wx_payment_wxpay().GetModelByWid(requestModel.wid);

                var packageReqHandler = new RequestHandler(null);
                //初始化
                packageReqHandler.Init();

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

                //设置package订单参数
                packageReqHandler.SetParameter("appid", wxModel.AppId);                        //公众账号ID
                packageReqHandler.SetParameter("mch_id", wxPayInfo.mch_id);                    //商户号
                packageReqHandler.SetParameter("nonce_str", nonceStr);                         //随机字符串
                packageReqHandler.SetParameter("body", requestModel.body);                     //商品描述
                packageReqHandler.SetParameter("attach", requestModel.PayModuleID.ToString()); //向微信传递系统支付模块ID
                packageReqHandler.SetParameter("out_trade_no", requestModel.out_trade_no);     //商家订单号

                //debug模式下,穿的单位为分
                packageReqHandler.SetParameter("total_fee", PayHelper.IsDebug ? requestModel.total_fee.ToString() : (requestModel.total_fee * 100).ToString());

                //packageReqHandler.SetParameter("spbill_create_ip", wxPayInfo);   //用户的公网ip,不是商户服务器IP

                packageReqHandler.SetParameter("notify_url", HttpContext.Current.Request.Url.ToString().ToLower().Replace("wechatservice.asmx", "PayNotify.aspx")); //接收财付通通知的URL
                packageReqHandler.SetParameter("trade_type", TenPayV3Type.JSAPI.ToString());                                                                        //交易类型
                packageReqHandler.SetParameter("openid", requestModel.openid);                                                                                      //用户的openId

                var sign = packageReqHandler.CreateMd5Sign("key", wxPayInfo.paykey);
                packageReqHandler.SetParameter("sign", sign);                       //签名

                var data = packageReqHandler.ParseXML();

                //同意下单,获取到预付订单号
                var unifiedOrderResult    = TenPayV3Helper.Unifiedorder(data);
                var rtnUnifiedOrderResult = new UnifiedOrderResponse(unifiedOrderResult);

                //下单成功,保存下单对象
                if (rtnUnifiedOrderResult.IsSuccess)
                {
                    var paymentInfo = new PaymentInfo
                    {
                        PaymentId   = Guid.NewGuid(),
                        Wid         = requestModel.wid,
                        CreateTime  = DateTime.Now,
                        Description = "无",
                        ShopName    = requestModel.body,
                        ModuleName  = ((PayModuleEnum)requestModel.PayModuleID).ToString(),
                        OrderCode   = requestModel.out_trade_no,
                        OrderId     = requestModel.OrderId,
                        Pid         = requestModel.openid,
                        PayAmount   = requestModel.total_fee,
                        WXOrderCode = rtnUnifiedOrderResult.prepay_id,
                        ModifyTime  = DateTime.Now,
                        Status      = 0
                    };

                    paymentInfo.Add();
                }

                //var jsApiParameters = rtnUnifiedOrderResult.GetJsApiParameters("4A5E7B87F3324A6DA22E55FDC12150B6");
                var jsApiParameters = rtnUnifiedOrderResult.GetJsApiParameters(wxPayInfo.paykey);

                HttpContext.Current.Response.Write(AjaxResult.Success(jsApiParameters));
            }
            catch (Exception exception)
            {
                HttpContext.Current.Response.Write(AjaxResult.Error(exception.Message));
            }
        }
Exemple #19
0
        protected void Page_Load(object sender, EventArgs e)
        {
            int orderId = MyCommFun.RequestInt("orderid");
            int wid     = MyCommFun.RequestInt("wid");

            getwid     = wid;
            getorderId = orderId;
            string code  = MyCommFun.RequestParam("code");
            string state = MyCommFun.RequestParam("state");

            BLL.wx_payment_wxpay   wxPayBll    = new BLL.wx_payment_wxpay();
            Model.wx_payment_wxpay paymentInfo = wxPayBll.GetModelByWid(wid);
            BLL.wx_userweixin      wx          = new BLL.wx_userweixin();
            Model.wx_userweixin    wxModel     = wx.GetModel(wid);
            BLL.orders             otBll       = new BLL.orders();

            Model.orders orderEntity = otBll.GetModel(orderId, wid);

            litout_trade_no = orderEntity.order_no;
            litMoney        = Decimal.ToInt32(orderEntity.order_amount);
            litDate         = orderEntity.add_time.ToString();



            if (string.IsNullOrEmpty(code))
            {
                Response.Write("您拒绝了授权!");
                return;
            }

            if (!state.Contains("|"))
            {
                //这里的state其实是会暴露给客户端的,验证能力很弱,这里只是演示一下
                //实际上可以存任何想传递的数据,比如用户ID,并且需要结合例如下面的Session["OAuthAccessToken"]进行验证
                Response.Write("验证失败!请从正规途径进入!1001");
                return;
            }

            ////获取产品信息
            //var stateData = state.Split('|');
            //int productId = 0;

            //if (int.TryParse(stateData[0], out productId))
            //{
            //    int hc = 0;
            //    if (int.TryParse(stateData[1], out hc))
            //    {
            //        var products = ProductModel.GetFakeProductList();
            //        product = products.FirstOrDefault(z => z.Id == productId);
            //        if (product == null || product.GetHashCode() != hc)
            //        {
            //            return Content("商品信息不存在,或非法进入!1002");
            //        }
            //        ViewData["product"] = product;
            //    }
            //}

            //通过,用code换取access_token
            var openIdResult = OAuthApi.GetAccessToken(PayV3Config.Mch_appId, PayV3Config.Mch_Secret, code);

            if (openIdResult.errcode != ReturnCode.请求成功)
            {
                Response.Write("错误:" + openIdResult.errmsg);
                return;
            }

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

            string sp_billno = Request["order_no"];
            //当前时间 yyyyMMdd
            string date = DateTime.Now.ToString("yyyyMMdd");

            if (null == sp_billno)
            {
                //生成订单10位序列号,此处用时间和随机数生成,商户根据自己调整,保证唯一
                sp_billno = DateTime.Now.ToString("HHmmss") + TenPayV3Util.BuildRandomStr(28);
            }
            else
            {
                sp_billno = Request["order_no"].ToString();
            }

            //创建支付应答对象
            Senparc.Weixin.MP.TenPayLibV3.RequestHandler packageReqHandler = new Senparc.Weixin.MP.TenPayLibV3.RequestHandler(null);
            //初始化
            packageReqHandler.Init();

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

            //设置package订单参数
            //  packageReqHandler.SetParameter("appid", paymentInfo.appId);		  //公众账号ID
            ///    packageReqHandler.SetParameter("mch_id", paymentInfo.partnerId);		  //商户号

            packageReqHandler.SetParameter("appid", PayV3Config.Mch_appId);               //公众账号ID
            packageReqHandler.SetParameter("mch_id", PayV3Config.Mch_mchid);              //商户号
            ////
            packageReqHandler.SetParameter("sub_appid", paymentInfo.appId);               //子商户公众账号ID
            packageReqHandler.SetParameter("sub_mch_id", paymentInfo.partnerId);          //子商户号mch_id
            ///


            packageReqHandler.SetParameter("nonce_str", nonceStr);                                                                          //随机字符串
            packageReqHandler.SetParameter("body", orderId.ToString());                                                                     //商品信息
            packageReqHandler.SetParameter("out_trade_no", litout_trade_no);                                                                //商家订单号
            packageReqHandler.SetParameter("total_fee", (litMoney * 100).ToString());                                                       //product == null ? "100" : (product.Price * 100).ToString()商品金额,以分为单位(money * 100).ToString()
            packageReqHandler.SetParameter("spbill_create_ip", Request.UserHostAddress);                                                    //用户的公网ip,不是商户服务器IP
            packageReqHandler.SetParameter("notify_url", MyCommFun.getWebSite() + "/api/wxpay/notify_url.aspx?wid=" + wid + "|" + orderId); //接收财付通通知的URL
            packageReqHandler.SetParameter("trade_type", TenPayV3Type.JSAPI.ToString());                                                    //交易类型
            packageReqHandler.SetParameter("openid", openIdResult.openid);                                                                  //用户的openId

            //   string sign = packageReqHandler.CreateMd5Sign("key", paymentInfo.paySignKey);
            string sign = packageReqHandler.CreateMd5Sign("key", PayV3Config.Mch_Key);

            packageReqHandler.SetParameter("sign", sign);                           //签名

            string data = packageReqHandler.ParseXML();

            var result = TenPayV3.Unifiedorder(data);

            var    res      = XDocument.Parse(result);
            string prepayId = res.Element("xml").Element("prepay_id").Value;

            //设置支付参数
            Senparc.Weixin.MP.TenPayLibV3.RequestHandler paySignReqHandler = new Senparc.Weixin.MP.TenPayLibV3.RequestHandler(null);
            paySignReqHandler.SetParameter("appId", PayV3Config.Mch_appId);
            paySignReqHandler.SetParameter("timeStamp", timeStamp);
            paySignReqHandler.SetParameter("nonceStr", nonceStr);
            paySignReqHandler.SetParameter("package", string.Format("prepay_id={0}", prepayId));
            paySignReqHandler.SetParameter("signType", "MD5");
            paySign = paySignReqHandler.CreateMd5Sign("key", PayV3Config.Mch_Key);



            payaddid        = PayV3Config.Mch_appId;
            paytimeStamp    = timeStamp;
            paynonceStr     = nonceStr;
            paypackageValue = string.Format("prepay_id={0}", prepayId);
            paypaySign      = paySign;
        }
Exemple #20
0
        private bool DoAdd(int _id)
        {
            Model.wx_userweixin weixin = GetWeiXinCode();

            bool result = false;

            BLL.payment   bll   = new BLL.payment();
            Model.payment model = new Model.payment();

            model.title = txtTitle.Text.Trim();
            if (cbIsLock.Checked == true)
            {
                model.is_lock = 0;
            }
            else
            {
                model.is_lock = 1;
            }
            model.sort_id         = int.Parse(txtSortId.Text.Trim());
            model.poundage_type   = int.Parse(rblPoundageType.SelectedValue);
            model.poundage_amount = decimal.Parse(txtPoundageAmount.Text.Trim());
            model.img_url         = txtImgUrl.Text.Trim();
            model.remark          = txtRemark.Text;
            model.pTypeId         = _id;
            model.wid             = weixin.id;
            model.api_path        = hidApi_path.Value;
            if (_id == 2)
            {
                //支付宝
                BLL.wx_payment_alipay   aliBll = new BLL.wx_payment_alipay();
                Model.wx_payment_alipay alipay = new Model.wx_payment_alipay();
                alipay.ownerName   = txtAlipaySellerEmail.Text.Trim();
                alipay.partner     = txtAlipayPartner.Text.Trim();
                alipay.e_key       = txtAlipayKey.Text.Trim();
                alipay.private_key = txtprivate_key.Text.Trim();
                alipay.public_key  = txtpublic_key.Text.Trim();
                alipay.sign_type   = "MD5";
                alipay.wid         = weixin.id;
                alipay.createDate  = DateTime.Now;
                aliBll.Add(alipay);
            }
            else if (_id == 3)
            {
                //微支付
                BLL.wx_payment_wxpay   wxpayBll = new BLL.wx_payment_wxpay();
                Model.wx_payment_wxpay wxpay    = new Model.wx_payment_wxpay();
                wxpay.wid = weixin.id;

                //财付通--相关信息
                wxpay.partnerId    = txtpartnerId.Text.Trim();
                wxpay.partnerKey   = txtpartnerKey.Text.Trim();
                wxpay.CertInfoPath = txtCertInfoPath.Text.Trim();
                wxpay.partnerPwd   = txtPartnerPwd.Text.Trim();

                //微信--相关配置
                wxpay.paySignKey = txtpaySignKey.Text.Trim();
                wxpay.appId      = txtAppId.Text.Trim();
                wxpay.quicklyFH  = rblQuicklyFH.SelectedItem.Value == "1" ? true : false;
                wxpay.createDate = DateTime.Now;
                wxpayBll.Add(wxpay);
            }


            if (bll.Add(model) > 0)
            {
                AddAdminLog(MXEnums.ActionEnum.Edit.ToString(), "添加支付方式:" + model.title); //记录日志
                result = true;
            }

            return(result);
        }
Exemple #21
0
        protected void Page_Load(object sender, EventArgs e)
        {
            //int wid = MyCommFun.RequestWid();
            int wid = 0;

            BLL.wx_logs logBll = new  BLL.wx_logs();
            logBll.AddLog("【微支付】微信预定", "notify_url Page_Load", "从微支付返回到notify_url.aspx页面", 1);
            BLL.wx_payment_wxpay payBll = new BLL.wx_payment_wxpay();



            ResponseHandler resHandler = new ResponseHandler(Context);

            resHandler.init();
            //取wid
            string attach = resHandler.getParameter("attach");

            string[] attachArr = attach.Split('|');
            wid = MyCommFun.Str2Int(attachArr[0]);
            int otid = MyCommFun.Str2Int(attachArr[1]);

            Model.wx_payment_wxpay paymentInfo = payBll.GetModelByWid(wid);
            logBll.AddLog(wid, "【微支付】微信预定", "notify_url Page_Load", "取到wid=" + wid, 1);
            resHandler.setKey(paymentInfo.partnerKey, paymentInfo.paySignKey);// TenpayUtil.key, TenpayUtil.appkey);
            //resHandler.setKey("huyuxianghuyuxianghuyuxiang12345", "nwRmqgvSG08pe3vU5qzBLb7Bvih0WOABGzUPvqgFqE0iSkJlJ8wh7JlLYy2cXFgFA3v1bM8eTDm1y1UcyeW9IGq2py2qei7J5xDoVR9lfO3cS6fMjFbMQeeqBRit0bKp");
            //判断签名
            if (resHandler.isTenpaySign())
            {
                logBll.AddLog(wid, "【微支付】微信预定", "notify_url Page_Load", "resHandler.isTenpaySign()", 1);
                if (resHandler.isWXsign())
                {
                    //商户在收到后台通知后根据通知ID向财付通发起验证确认,采用后台系统调用交互模式
                    string notify_id = resHandler.getParameter("notify_id");
                    //取结果参数做业务处理
                    string out_trade_no = resHandler.getParameter("out_trade_no");
                    //财付通订单号
                    string transaction_id = resHandler.getParameter("transaction_id");
                    //金额,以分为单位
                    string total_fee = resHandler.getParameter("total_fee");
                    //如果有使用折扣券,discount有值,total_fee+discount=原请求的total_fee
                    string discount = resHandler.getParameter("discount");
                    //支付结果
                    string trade_state = resHandler.getParameter("trade_state");


                    string pay_info = resHandler.getParameter("pay_info");


                    logBll.AddLog(wid, "【微支付】微信预定", "notify_url Page_Load", "notify_id=" + notify_id + " out_trade_no=" + out_trade_no + " transaction_id=" + transaction_id + " total_fee=" + total_fee + " trade_state=" + trade_state + " orderid=" + otid + " wid=" + wid + "  pay_info=" + pay_info, 1);

                    //即时到账,支付成功
                    if ("0".Equals(trade_state))
                    {
                        logBll.AddLog(wid, "【微支付】微信预定", "notify_url Page_Load", "支付成功了", 1);
                        //------------------------------
                        //处理业务开始
                        //------------------------------
                        wxOrderTmpMgr Totbll = wxOrderTmpMgr.instance();
                        string        ret    = Totbll.ProcessPaySuccess_wx("notify_url", notify_id, out_trade_no, transaction_id, pay_info, MyCommFun.Str2Int(total_fee), otid, wid);
                        ret = ret == "" ? "处理数据同步发送成功" : ret;
                        logBll.AddLog(wid, "微信预定", "【微支付】notify_url Page_Load", ret, 1);
                        //处理数据库逻辑
                        //注意交易单不要重复处理
                        //注意判断返回金额


                        //------------------------------
                        //处理业务完毕
                        //------------------------------

                        //给财付通系统发送成功信息,财付通系统收到此结果后不再进行后续通知
                        Response.Write("success");
                    }
                    else
                    {
                        logBll.AddLog(wid, "【微支付】微信预定", "notify_url Page_Load", "支付失败", 1);
                        Response.Write("支付失败");
                    }
                    //回复服务器处理成功
                    Response.Write("success");
                }

                else
                {//SHA1签名失败
                    logBll.AddLog("微信预定", "【微支付】notify_url Page_Load", "fail -SHA1 failed", 0);
                    Response.Write("fail -SHA1 failed");
                    Response.Write(resHandler.getDebugInfo());
                }
            }
            else
            {//md5签名失败
                logBll.AddLog(wid, "微信预定", "【微支付】notify_url Page_Load", "fail -md5 failed", 0);
                Response.Write("fail -md5 failed");
                Response.Write(resHandler.getDebugInfo());
            }
        }
Exemple #22
0
        /// <summary>
        /// 最新接口调用
        /// 2014-11-24
        /// </summary>
        /// <param name="ttFee">支付金额(单位元)</param>
        /// <param name="busiBody">订单内容</param>
        /// <param name="out_trade_no">订单号</param>
        /// <param name="code"></param>
        protected void WxPayDataV3(decimal ttFee, string busiBody, string out_trade_no, string code)
        {
            BLL.wx_payment_wxpay   wxPayBll    = new BLL.wx_payment_wxpay();
            Model.wx_payment_wxpay paymentInfo = wxPayBll.GetModelByWid(wid);

            BLL.wx_userweixin   uwBll    = new BLL.wx_userweixin();
            Model.wx_userweixin uwEntity = uwBll.GetModel(wid);

            // logBll.AddLog(wid,"【微支付】微信预定", "paypage.aspx WxPayDataV3", "211 wid:" + wid, 1);

            //先设置基本信息
            string MchId = paymentInfo.partnerId;       // "1218574001";//

            string partnerKey = paymentInfo.partnerKey; // 商户支付密钥Key。登录微信商户后台,进入栏目【账户设置】【密码安全】【API 安全】【API 密钥】

            string notify_url = "http://" + HttpContext.Current.Request.Url.Authority + "/api/payment/wxpay/notify_url.aspx";

            logBll.AddLog(wid, "【微支付】微信预定", "paypage.aspx WxPayDataV3", "uwEntity.AppId: " + uwEntity.AppId + "| uwEntity.AppSecret;" + uwEntity.AppSecret + "|code:" + code, 1);


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

            string sp_billno = out_trade_no;
            //当前时间 yyyyMMdd
            string date = DateTime.Now.ToString("yyyyMMdd");

            if (null == sp_billno)
            {
                //生成订单10位序列号,此处用时间和随机数生成,商户根据自己调整,保证唯一
                sp_billno = DateTime.Now.ToString("HHmmss") + TenPayUtil.BuildRandomStr(28);
            }


            //创建支付应答对象
            Senparc.Weixin.MP.TenPayLibV3.RequestHandler packageReqHandler = new Senparc.Weixin.MP.TenPayLibV3.RequestHandler(null);
            //初始化

            //packageReqHandler.SetKey(""/*TenPayV3Info.Key*/);

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

            //设置package订单参数
            packageReqHandler.SetParameter("appid", uwEntity.AppId);                      //公众账号ID
            packageReqHandler.SetParameter("mch_id", MchId);                              //商户号
            packageReqHandler.SetParameter("nonce_str", nonceStr);                        //随机字符串
            packageReqHandler.SetParameter("body", busiBody);                             //商品描述
            packageReqHandler.SetParameter("attach", wid + "|" + busiBody);
            packageReqHandler.SetParameter("out_trade_no", sp_billno);                    //商家订单号
            packageReqHandler.SetParameter("total_fee", ((int)(ttFee * 100)).ToString()); //商品金额,以分为单位(money * 100).ToString()
            packageReqHandler.SetParameter("spbill_create_ip", Request.UserHostAddress);  //用户的公网ip,不是商户服务器IP
            packageReqHandler.SetParameter("notify_url", notify_url);                     //接收财付通通知的URL
            packageReqHandler.SetParameter("trade_type", TenPayV3Type.JSAPI.ToString());  //交易类型
            packageReqHandler.SetParameter("openid", openid);                             //用户的openId

            string sign = packageReqHandler.CreateMd5Sign("key", partnerKey);

            packageReqHandler.SetParameter("sign", sign);                           //签名

            string data = packageReqHandler.ParseXML();

            var    result   = TenPayV3.Unifiedorder(data);
            var    res      = XDocument.Parse(result);
            string prepayId = res.Element("xml").Element("prepay_id").Value;



            //设置支付参数
            Senparc.Weixin.MP.TenPayLibV3.RequestHandler paySignReqHandler = new Senparc.Weixin.MP.TenPayLibV3.RequestHandler(null);
            paySignReqHandler.SetParameter("appId", uwEntity.AppId);
            paySignReqHandler.SetParameter("timeStamp", timeStamp);
            paySignReqHandler.SetParameter("nonceStr", nonceStr);
            paySignReqHandler.SetParameter("package", string.Format("prepay_id={0}", prepayId));
            paySignReqHandler.SetParameter("signType", "MD5");
            paySign = paySignReqHandler.CreateMd5Sign("key", partnerKey);

            packageValue  = "";
            packageValue += " \"appId\": \"" + uwEntity.AppId + "\", ";
            packageValue += " \"timeStamp\": \"" + timeStamp + "\", ";
            packageValue += " \"nonceStr\": \"" + nonceStr + "\", ";
            packageValue += " \"package\": \"" + string.Format("prepay_id={0}", prepayId) + "\", ";
            packageValue += " \"signType\": \"MD5\", ";
            packageValue += " \"paySign\": \"" + paySign + "\"";
        }
Exemple #23
0
        /// <summary>
        /// 处理发关注红包的逻辑
        /// </summary>
        /// <param name="openid"></param>
        /// <param name="wid"></param>
        /// <param name="actModel"></param>
        public int  proecssSendHB(string openid, int wid, Model.wx_xjhongbao_action actModel)
        {
            BLL.wx_xjhongbao_action actBll    = new BLL.wx_xjhongbao_action();
            BLL.wx_xjhongbao_base   baseBll   = new BLL.wx_xjhongbao_base();
            Model.wx_xjhongbao_base baseModel = baseBll.GetModelByWid(wid);

            BLL.wx_payment_wxpay   weixinPayBLL   = new BLL.wx_payment_wxpay();
            Model.wx_payment_wxpay weixinPayModel = weixinPayBLL.GetModelByWid(wid);

            if (baseModel == null || weixinPayModel == null || actModel == null)
            {
                return(0);
            }

            #region 取用户昵称--注释掉了
            //string error = "";
            //string accessToken=WeiXinCRMComm.getAccessToken(wid, out error);
            //if (error.Trim().Length > 0)
            //{
            //    WXLogs.AddErrLog(wid, "微信红包", actModel.act_name, "accessToken取值有错误error:"+error);
            //    return;
            //}
            //string nick = UserApi.Info(accessToken, openid).nickname;
            #endregion

            //用户此次获得的红包(单位分)
            int hongbaoFen = 0;
            if (actModel.totalLqMoney >= actModel.totalMoney)
            {
                //1 红包金额已经领取完了,记录到日志
                InsertToLQinfo(wid, actModel.id, openid, 0, DateTime.Parse("1970-1-1"), "", "", "", "", "红包余额不足,需要调整活动的金额");
                return(0);
            }
            //2 判断该用户是否已经领取了
            bool hasLQ = lqBll.ExistsOpenid(actModel.id, openid, actModel.lqType == 0 ? true : false);
            if (hasLQ)
            { //已经领取了
                return(0);
            }
            int leftMoney = actModel.totalMoney.Value - actModel.totalLqMoney.Value;//剩余金额
            //3 计算本次的红包
            if (actModel.moneyType == 0)
            { //定额
                hongbaoFen = actModel.min_value.Value;
            }
            else
            {  //随机
                Random rd = new Random();
                hongbaoFen = rd.Next(actModel.min_value.Value, actModel.max_value.Value);
            }

            if (hongbaoFen >= leftMoney)
            {
                hongbaoFen = leftMoney;
            }

            //4 给用户发红包
            string mchbillno = weixinPayModel.mch_id + DateTime.Now.ToString("yyyymmddHHmmss") + TenPayV3Util.BuildRandomStr(4);


            Model.wx_xjhongbao_lqinfo lqinfoEntity = new Model.wx_xjhongbao_lqinfo();
            lqinfoEntity.wid          = wid;
            lqinfoEntity.actionId     = actModel.id;
            lqinfoEntity.openid       = openid;
            lqinfoEntity.total_amount = hongbaoFen;
            lqinfoEntity.createDate   = DateTime.Now;

            XmlDocument doc = new XmlDocument();
            if (!SendHBBase(weixinPayModel, actModel, wid, openid, hongbaoFen, mchbillno, doc))
            {
                //发红包的方法出现问题
                WXLogs.AddErrLog(wid, "微信红包", actModel.act_name, "发现金红包底层方法报错。");

                lqinfoEntity.Send_time  = DateTime.Now;
                lqinfoEntity.mch_billno = mchbillno;
                lqinfoEntity.mch_id     = weixinPayModel.mch_id;
                lqinfoEntity.hbstatus   = "FAILED";
                lqinfoEntity.send_type  = "API";
                lqinfoEntity.hb_type    = "NORMAL";
                lqinfoEntity.reason     = "result_code:" + doc.InnerXml.ToString();

                lqBll.Add(lqinfoEntity);  //记录领取日志
                WXLogs.AddLog(wid, "微信红包", actModel.act_name, "现金红包领取失败:" + doc.InnerXml.ToString());
                return(0);
            }
            //5修改现金:1活动的领取金额增加;2用户的中奖记录增加
            actModel = actBll.GetModel(actModel.id);
            actModel.totalLqMoney += hongbaoFen;
            actBll.Update(actModel);
            //6修改配置文件的领取金额;
            baseModel.totalLQMoney += hongbaoFen;
            baseBll.Update(baseModel);

            WXLogs.AddLog(wid, "微信红包", actModel.act_name, "现金红包领取成功2:" + doc.InnerXml.ToString());

            lqinfoEntity.Send_time  = MyCommFun.Obj2DateTime(MyCommFun.GetXmlNode("send_time", doc), DateTime.Now);
            lqinfoEntity.mch_billno = mchbillno;
            lqinfoEntity.mch_id     = weixinPayModel.mch_id;
            lqinfoEntity.detail_id  = MyCommFun.GetXmlNode("send_listid", doc);
            lqinfoEntity.hbstatus   = "SUCCESS";
            lqinfoEntity.send_type  = "API";
            lqinfoEntity.hb_type    = "NORMAL";
            lqinfoEntity.reason     = "";
            lqinfoEntity.remark     = doc.InnerXml.ToString();
            lqBll.Add(lqinfoEntity);

            WXLogs.AddLog(wid, "微信红包", actModel.act_name, "现金红包成功领取3:" + doc.InnerXml.ToString());
            return(hongbaoFen);
        }
Exemple #24
0
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/json";
            BLL.wx_shop_cart            cartBll  = new BLL.wx_shop_cart();
            string                      _action  = MyCommFun.QueryString("myact");
            string                      openid   = MyCommFun.RequestOpenid(); //得到微信用户的openid
            Dictionary <string, string> jsonDict = new Dictionary <string, string>();

            if (_action == "addCart")
            {
                #region 添加购物车
                try
                {
                    int     wid        = MyCommFun.RequestInt("wid");
                    int     productId  = MyCommFun.RequestInt("productid");
                    int     skuId      = MyCommFun.RequestInt("mid");
                    string  skuInfo    = MyCommFun.QueryString("attr");
                    int     productNum = MyCommFun.RequestInt("bc");
                    decimal totalPrice = (decimal)MyCommFun.RequestFloat("totprice", 0);

                    Model.wx_shop_cart cart = new Model.wx_shop_cart();

                    IList <Model.wx_shop_cart> cartList = cartBll.GetModelList("productId=" + productId + " and openid='" + openid + "' and skuId=" + skuId);
                    bool isAdd = true;
                    if (cartList != null && cartList.Count > 0)
                    {
                        isAdd = false;
                        cart  = cartList[0];
                    }
                    if (isAdd)
                    {
                        cart.createDate = DateTime.Now;
                        cart.openid     = openid;
                        cart.productId  = productId;
                        cart.productNum = productNum;
                        cart.skuId      = skuId;
                        cart.skuInfo    = skuInfo;
                        cart.totPrice   = totalPrice * productNum;
                        cart.wid        = wid;
                        int ret = cartBll.Add(cart);
                        if (ret > 0)
                        {
                            jsonDict.Add("errCode", "false");
                        }
                        else
                        {
                            jsonDict.Add("errCode", "true");
                        }
                    }
                    else
                    {
                        cart.openid = openid;

                        cart.productNum += productNum;
                        cart.skuId       = skuId;
                        cart.skuInfo     = skuInfo;
                        cart.totPrice   += totalPrice * productNum;
                        cart.wid         = wid;
                        bool ret = cartBll.Update(cart);
                        if (ret)
                        {
                            jsonDict.Add("errCode", "false");
                        }
                        else
                        {
                            jsonDict.Add("errCode", "true");
                        }
                    }
                }
                catch (Exception ex)
                {
                    jsonDict.Add("errCode", "true");
                }
                finally
                {
                    context.Response.Write(MyCommFun.getJsonStr(jsonDict));
                }
                #endregion
            }
            else if (_action == "pcount")
            {
                #region 购物车商品数量
                jsonDict = new Dictionary <string, string>();
                int wid   = MyCommFun.RequestInt("wid");
                int count = cartBll.GetRecordCount("wid=" + wid + " and openid='" + openid + "'");
                jsonDict.Add("data", count.ToString());
                context.Response.Write(MyCommFun.getJsonStr(jsonDict));
                #endregion
            }
            else if (_action == "remove")
            {
                #region 移除购物车商品
                jsonDict = new Dictionary <string, string>();
                int cartId = MyCommFun.RequestInt("id");
                cartBll.Delete(cartId);
                jsonDict.Add("errCode", "false");
                context.Response.Write(MyCommFun.getJsonStr(jsonDict));
                #endregion
            }
            else if (_action == "modifyNum")
            {
                #region 修改购物车商品数量
                jsonDict = new Dictionary <string, string>();
                int cartId = MyCommFun.RequestInt("ic");
                int newNum = MyCommFun.RequestInt("bc");
                cartBll.UpdateNum(cartId, newNum);
                jsonDict.Add("errCode", "false");
                context.Response.Write(MyCommFun.getJsonStr(jsonDict));
                #endregion
            }
            else if (_action == "getCity")
            {
                #region  择省份,改变城市列表
                int privice = MyCommFun.RequestInt("pvid");
                BLL.pre_common_district           areaBll = new BLL.pre_common_district();
                IList <Model.pre_common_district> disList = areaBll.GetModelList("upid=" + privice + " and level=2");
                Model.pre_common_district         dis;
                StringBuilder jsonStr = new StringBuilder("{\"errCode\":0,\"retCode\":0,\"msgType\":0,\"errMsg\":\"\",\"data\":[");
                for (int i = 0; i < disList.Count; i++)
                {
                    dis = new Model.pre_common_district();
                    if (i != disList.Count - 1)
                    {
                        jsonStr.Append("{\"id\":" + disList[i].id + ",\"name\":\"" + disList[i].name + "\"},");
                    }
                    else
                    {
                        jsonStr.Append("{\"id\":" + disList[i].id + ",\"name\":\"" + disList[i].name + "\"}");
                    }
                }
                jsonStr.Append("]}");
                context.Response.Write(jsonStr);
                #endregion
            }
            else if (_action == "getArea")
            {
                #region  择城市,改变区域列表
                int ctid = MyCommFun.RequestInt("ctid");
                BLL.pre_common_district           areaBll = new BLL.pre_common_district();
                IList <Model.pre_common_district> disList = areaBll.GetModelList("upid=" + ctid + " and level=3");
                Model.pre_common_district         dis;
                StringBuilder jsonStr = new StringBuilder("{\"errCode\":0,\"retCode\":0,\"msgType\":0,\"errMsg\":\"\",\"data\":[");
                for (int i = 0; i < disList.Count; i++)
                {
                    dis = new Model.pre_common_district();
                    if (i != disList.Count - 1)
                    {
                        jsonStr.Append("{\"id\":" + disList[i].id + ",\"name\":\"" + disList[i].name + "\"},");
                    }
                    else
                    {
                        jsonStr.Append("{\"id\":" + disList[i].id + ",\"name\":\"" + disList[i].name + "\"}");
                    }
                }
                jsonStr.Append("]}");
                context.Response.Write(jsonStr);
                #endregion
            }
            else if (_action == "order_save")
            {
                #region 保存订单信息
                //获得传参信息
                int wid = MyCommFun.RequestInt("wid");

                int payment_id = MyCommFun.RequestInt("pc");    //支付方式:1货到付款;3微支付
                int express_id = MyCommFun.RequestInt("mtype"); //物流方式
                // string orderStrList = MyCommFun.QueryString("orderStrList");

                //检查物流方式
                if (express_id == 0)
                {
                    context.Response.Write("{\"errCode\":3, \"msg\":\"对不起,请选择配送方式!\"}");
                    return;
                }
                BLL.wx_shop_user_addr           uAddrBll  = new BLL.wx_shop_user_addr();
                IList <Model.wx_shop_user_addr> uaddrList = uAddrBll.GetOpenidAddrName(openid, wid);
                if (uaddrList == null || uaddrList.Count <= 0 || uaddrList[0].id <= 0)
                {
                    context.Response.Write("{\"errCode\":3, \"msg\":\"收货地址不存在,无法结算!\"}");
                    return;
                }


                //检查购物车商品
                IList <Model.cartProduct> cartList = cartBll.GetCartList(openid, wid);
                if (cartList == null)
                {
                    context.Response.Write("{\"errCode\":3, \"msg\":\"对不起,购物车为空,无法结算!\"}");
                    return;
                }
                //统计购物车
                decimal payable_amount = cartList.Sum(c => c.totPrice);
                //物流费用
                BLL.express   expressBll = new BLL.express();
                Model.express expModel   = expressBll.GetModel(express_id);
                //支付方式
                BLL.payment   pbll     = new BLL.payment();
                Model.payment payModel = pbll.GetModelBypTypeId(payment_id);
                //保存订单=======================================================================
                Model.orders model = new Model.orders();
                model.order_no = "b" + Utils.GetOrderNumber(); //订单号B开头为商品订单

                model.wid             = wid;
                model.openid          = openid;
                model.modelName       = "微商城";
                model.modelCode       = "shop";
                model.modelActionName = "";
                model.modelActionId   = 0;
                model.user_id         = 0;
                model.user_name       = "";
                model.payment_id      = payment_id;
                model.express_id      = express_id;
                model.accept_name     = uaddrList[0].contractPerson;
                model.post_code       = "";
                model.telphone        = uaddrList[0].tel;
                model.mobile          = uaddrList[0].tel;
                model.area            = uaddrList[0].province;
                model.city            = uaddrList[0].city;
                model.district        = uaddrList[0].area;
                model.address         = uaddrList[0].province + " " + uaddrList[0].city + " " + uaddrList[0].area + " " + uaddrList[0].addrDetail;
                model.message         = "";
                model.payable_amount  = payable_amount; //应付商品总金额
                model.real_amount     = payable_amount; //实际商品总金额,
                model.status          = 1;
                model.express_status  = 1;
                model.express_fee     = expModel.express_fee; //物流费用

                if (payment_id == 1)
                {                             //货到付款,需要确认订单
                    model.payment_status = 0; //标记未付款
                }
                else
                {                             //先款后货
                    model.payment_status = 1; //标记未付款
                }
                bool quicklyFH = false;
                //如果是先款后货的话
                if (payment_id == 3)
                {
                    if (payModel.poundage_type == 1) //百分比
                    {
                        model.payment_fee = model.real_amount * payModel.poundage_amount / 100;
                    }
                    else //固定金额
                    {
                        model.payment_fee = payModel.poundage_amount;
                    }
                    BLL.wx_payment_wxpay   wxBll = new BLL.wx_payment_wxpay();
                    Model.wx_payment_wxpay wxpay = wxBll.GetModelByWid(wid);
                    quicklyFH = wxpay.quicklyFH;
                }
                if (quicklyFH)
                {
                    model.express_status = 0;
                }
                //订单总金额=实付商品金额+运费+支付手续费
                model.order_amount = model.real_amount + model.express_fee + model.payment_fee;
                //购物积分,可为负数
                model.point    = 0;
                model.add_time = DateTime.Now;
                //商品详细列表
                List <Model.order_goods> gls = new List <Model.order_goods>();
                foreach (Model.cartProduct item in cartList)
                {
                    gls.Add(new Model.order_goods {
                        goods_id = item.productId, goods_title = item.productName, goods_price = item.avgPrice, real_price = item.avgPrice, quantity = item.productNum, point = 0
                    });
                }
                model.order_goods = gls;
                int result = new BLL.orders().Add(model);
                if (result < 1)
                {
                    context.Response.Write("{\"errCode\":3, \"msg\":\"订单保存过程中发生错误,请重新提交!\"}");
                    return;
                }

                //清空购物车,此步骤移到确认支付页面
                //
                //提交成功,返回URL  order_no
                context.Response.Write("{\"errCode\":true,\"payType\":\"" + payment_id + "\", \"order_no\":\"" + model.order_no + "\",\"orderid\":\"" + result + "\",\"wid\":\"" + wid + "\",\"openid\":\"" + openid + "\",\"payable_amount\":\"" + payable_amount + "\", \"msg\":\"恭喜您,订单已成功提交!\"}");
                return;

                #endregion
            }
            else if (_action == "order_canel")
            {
                #region  //取消订单
                int        orderid = MyCommFun.RequestInt("order_id");
                BLL.orders oBll    = new BLL.orders();
                oBll.UpdateField(orderid, "status=4");
                context.Response.Write("{\"errCode\":true, \"msg\":\"订单已取消!\"}");
                #endregion
            }
            else if (_action == "shouhuo")
            {
                #region  //确认收货
                int          orderid = MyCommFun.RequestInt("order_id");
                BLL.orders   oBll    = new BLL.orders();
                Model.orders order   = oBll.GetModel(orderid);
                if (order.payment_id == 1)
                {
                    //货到付款
                    oBll.UpdateField(orderid, "express_status=2,payment_status=2 , status=3");
                }
                else
                {
                    //在线支付
                    oBll.UpdateField(orderid, "express_status=2,payment_status=2 , status=3");
                }

                context.Response.Write("{\"errCode\":true, \"msg\":\"确认收货!\"}");
                #endregion
            }
            else if (_action == "clearMyOrder")
            {
                #region 清空我的购物车订单,在支付页面,支付成功后执行此功能
                int wid = MyCommFun.RequestInt("wid");
                cartBll.RemoveCartInfo(wid, openid);
                #endregion
            }
        }
Exemple #25
0
        public string Apply_refund()
        {
            int    orderId = MyCommFun.RequestInt("orderid");
            int    wid     = MyCommFun.RequestInt("wid");
            string code    = MyCommFun.RequestParam("code");
            string state   = MyCommFun.RequestParam("state");

            BLL.wx_payment_wxpay   wxPayBll    = new BLL.wx_payment_wxpay();
            Model.wx_payment_wxpay paymentInfo = wxPayBll.GetModelByWid(wid);
            BLL.wx_userweixin      wx          = new BLL.wx_userweixin();
            Model.wx_userweixin    wxModel     = wx.GetModel(wid);
            BLL.orders             otBll       = new BLL.orders();
            Model.orders           orderEntity = otBll.GetModel(orderId, wid);
            litout_trade_no = orderEntity.order_no;
            amount          = orderEntity.order_amount.ToString();
            string         nonceStr          = TenPayV3Util.GetNoncestr();
            RequestHandler packageReqHandler = new RequestHandler(null);

            //设置package订单参数
            packageReqHandler.SetParameter("appid", paymentInfo.appId);            //公众账号ID
            packageReqHandler.SetParameter("mch_id", paymentInfo.partnerId);       //商户号
            packageReqHandler.SetParameter("out_trade_no", orderEntity.order_no);  //填入商家订单号
            packageReqHandler.SetParameter("out_refund_no", orderEntity.order_no); //填入退款订单号
            packageReqHandler.SetParameter("total_fee", amount);                   //填入总金额
            packageReqHandler.SetParameter("refund_fee", amount);                  //填入退款金额
            packageReqHandler.SetParameter("op_user_id", paymentInfo.partnerId);   //操作员Id,默认就是商户号
            packageReqHandler.SetParameter("nonce_str", nonceStr);                 //随机字符串
            string sign = packageReqHandler.CreateMd5Sign("key", paymentInfo.paySignKey);

            packageReqHandler.SetParameter("sign", sign);                           //签名
            //退款需要post的数据
            string data = packageReqHandler.ParseXML();


            //退款接口地址
            string url = "https://api.mch.weixin.qq.com/secapi/pay/refund";
            //本地或者服务器的证书位置(证书在微信支付申请成功发来的通知邮件中)
            string cert = MyCommFun.GetRootPath() + paymentInfo.CertInfoPath;

            //私钥(在安装证书时设置)
            string password = paymentInfo.partnerPwd;

            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            //调用证书
            X509Certificate2 cer = new X509Certificate2(cert, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);

            #region 发起post请求
            HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(url);
            webrequest.ClientCertificates.Add(cer);
            webrequest.Method = "post";

            byte[] postdatabyte = Encoding.UTF8.GetBytes(data);
            webrequest.ContentLength = postdatabyte.Length;
            Stream stream;
            stream = webrequest.GetRequestStream();
            stream.Write(postdatabyte, 0, postdatabyte.Length);
            stream.Close();

            HttpWebResponse httpWebResponse = (HttpWebResponse)webrequest.GetResponse();
            StreamReader    streamReader    = new StreamReader(httpWebResponse.GetResponseStream());
            string          responseContent = streamReader.ReadToEnd();
            #endregion

            var    res    = XDocument.Parse(responseContent);
            string openid = res.Element("xml").Element("out_refund_no").Value;

            return(openid);
        }