/// <summary>
        /// 取消未发货未付款订单
        /// </summary>
        /// <param name="orderCancelModel">
        /// The order cancel model.
        /// </param>
        /// <returns>
        /// The <see cref="ActionResult"/>.
        /// </returns>
        public ActionResult CancelOrder(OrderCancelModel orderCancelModel)
        {
            var response = new AjaxResponse();
            if (orderCancelModel == null || orderCancelModel.OrderID < 1 || orderCancelModel.OrderCancelCauseID < 1)
            {
                response.State = -1;
                response.Message = "参数错误";
                return this.Json(response, JsonRequestBehavior.AllowGet);
            }

            try
            {
                var orderCancel = DataTransfer.Transfer<Order_Cancel>(orderCancelModel, typeof(OrderCancelModel));
                orderCancel.EmployeeID = this.SystemUserSession.EmployeeID;
                int state = new OrderService(this.SystemUserSession.EmployeeID).OrderCancelByBackstage(orderCancel);

                // 0-订单状态异常,1-操作成功,2-已发货,3-订单已取消、损失或者作废
                if (state == 0)
                {
                    response.State = 0;
                    response.Message = "订单状态异常";
                }
                else if (state == 1)
                {
                    response.State = 1;
                    response.Message = "订单取消成功";
                }
                else if (state == 2)
                {
                    response.State = 2;
                    response.Message = "已发货,取消订单操作取消";
                }
                else if (state == 3)
                {
                    response.State = 3;
                    response.Message = "订单已取消、已损失或者已作废";
                }
                else if (state == 4)
                {
                    response.State = 4;
                    response.Message = "订单已付款";
                }

                return this.Json(response, JsonRequestBehavior.AllowGet);
            }
            catch (Exception exception)
            {
                TextLogger.Instance.Log("订单取消操作发生错误", Category.Error, exception);

                response.State = -2;
                response.Message = exception.Message;
                return this.Json(response, JsonRequestBehavior.AllowGet);
            }
        }
Пример #2
0
        /// <summary>
        /// 后台手动完成订单
        /// </summary>
        /// <param name="id">订单编码</param>
        /// <returns>返回结果</returns>
        public ActionResult CompleteOrder(int id)
        {
            string message;
            var result = new OrderService(this.SystemUserSession.SystemUserID, true).CompleteOrder(id, out message);

            if (result)
            {
                return this.Json(new AjaxResponse(1, "签收完成"));
            }
            return this.Json(new AjaxResponse(0, message));
        }
Пример #3
0
        public ActionResult DoEvaluate(string code)
        {
            if (string.IsNullOrWhiteSpace(code))
            {
                return this.View();
            }

            var order = new OrderService(this.UserSession.UserID, false);

            return this.View();
        }
Пример #4
0
        public ActionResult Index(string ono)
        {
            #region 参数定义
            //人民币网关账户号
            ///请登录快钱系统获取用户编号,用户编号后加01即为人民币网关账户号。
             string merchantAcctId = "";

            //字符集.固定选择值。可为空。
            ///只能选择1、2、3.
            ///1代表UTF-8; 2代表GBK; 3代表gb2312
            ///默认值为1
             string inputCharset = "";

            //接受支付结果的页面地址.与[bgUrl]不能同时为空。必须是绝对地址。
            ///如果[bgUrl]为空,快钱将支付结果Post到[pageUrl]对应的地址。
            ///如果[bgUrl]不为空,并且[bgUrl]页面指定的<redirecturl>地址不为空,则转向到<redirecturl>对应的地址
             string pageUrl = "";

            //服务器接受支付结果的后台地址.与[pageUrl]不能同时为空。必须是绝对地址。
            ///快钱通过服务器连接的方式将交易结果发送到[bgUrl]对应的页面地址,在商户处理完成后输出的<result>如果为1,页面会转向到<redirecturl>对应的地址。
            ///如果快钱未接收到<redirecturl>对应的地址,快钱将把支付结果post到[pageUrl]对应的页面。
             string bgUrl = "";

            //网关版本.固定值
            ///快钱会根据版本号来调用对应的接口处理程序。
            ///本代码版本号固定为v2.0
             string version = "";

            //语言种类.固定选择值。
            ///只能选择1、2、3
            ///1代表中文;2代表英文
            ///默认值为1
             string language = "";

            //签名类型.固定值
            ///1代表MD5签名
            ///当前版本固定为1
             string signType = "";

            //支付人姓名
            ///可为中文或英文字符
             string payerName = "";

            //支付人联系方式类型.固定选择值
            ///只能选择1
            ///1代表Email
             string payerContactType = "";

            //支付人联系方式
            ///只能选择Email或手机号
             string payerContact = "";

            //商户订单号
            ///由字母、数字、或[-][_]组成
             string orderId = "";

            //订单金额
            ///以分为单位,必须是整型数字
            ///比方2,代表0.02元
             string orderAmount = "";

            //订单提交时间
            ///14位数字。年[4位]月[2位]日[2位]时[2位]分[2位]秒[2位]
            ///如;20080101010101
             string orderTime = "";

            //订单提交时间
            ///14位数字。年[4位]月[2位]日[2位]时[2位]分[2位]秒[2位]
            ///如;20080101010101
             string stringorderTime = "";

            //商品名称
            ///可为中文或英文字符
             string productName = "";

            //商品数量
            ///可为空,非空时必须为数字
             string productNum = "";

            //商品代码
            ///可为字符或者数字
             string productId = "";

            //商品描述
             string productDesc = "";

            //扩展字段1
            ///在支付结束后原样返回给商户
             string ext1 = "";

            //扩展字段2
            ///在支付结束后原样返回给商户
             string ext2 = "";

            //支付方式.固定选择值
            ///只能选择00、10、11、12、13、14
            ///00:组合支付(网关支付页面显示快钱支持的各种支付方式,推荐使用)10:银行卡支付(网关支付页面只显示银行卡支付).11:电话银行支付(网关支付页面只显示电话支付).12:快钱账户支付(网关支付页面只显示快钱账户支付).13:线下支付(网关支付页面只显示线下支付方式).14:B2B支付(网关支付页面只显示B2B支付,但需要向快钱申请开通才能使用)
             string payType = "00";

            //银行代码
            ///实现直接跳转到银行页面去支付,只在payType=10时才需设置参数
            ///具体代码参见 接口文档银行代码列表
             string bankId = "";

            //同一订单禁止重复提交标志
            ///固定选择值: 1、0
            ///1代表同一订单号只允许提交1次;0表示同一订单号在没有支付成功的前提下可重复提交多次。默认为0建议实物购物车结算类商户采用0;虚拟产品类商户采用1
             string redoFlag = "0";

            //快钱的合作伙伴的账户号
            ///如未和快钱签订代理合作协议,不需要填写本参数
             string pid = "";

            //签名串
            ///
             string signMsg = "";

            #endregion

            try
            {
                merchantAcctId = "1002135542801";

                inputCharset = "1";

                pageUrl = ConstantParams.SiteUrl + "_99Bill/ReceivePki";

                bgUrl = ConstantParams.SiteUrl + "_99Bill/ReceivePki";

                version = "v2.0";

                language = "1";

                signType = "4";

                payerName = "购酒网";

                payerContactType = "1";

                payerContact = "";

                //验证订单是否为空
                if (string.IsNullOrWhiteSpace(ono))
                {
                    LogUtils.Log("快钱支付错误:订单编号为空", "快钱支付--验证订单编号", Category.Warn, this.Session.SessionID, this.UserSession.UserID, "Tenpay/DoPay");
                    return this.Content("<script type='text/javascript'>alert('对不起,订单编号错误,无法完成支付!');window.location='" + ConstantParams.SiteUrl + "User/MyOrder';" + "</script>");
                }

                //验证订单信息
                var order = new OrderService(this.UserSession.UserID, false).QueryByOrderCode(ono);
                if (order == null || order.UserID != this.UserSession.UserID)
                {
                    LogUtils.Log("快钱支付错误:订单编号异常(" + ono + ")", "快钱支付--验证订单编号", Category.Warn, this.Session.SessionID, this.UserSession.UserID, "Tenpay/DoPay");
                    return this.Content("<script type='text/javascript'>alert('对不起,订单编号错误,无法完成支付!');window.location='" + ConstantParams.SiteUrl + "User/MyOrder';" + "</script>");
                }

                orderId = ono;

                //todo:测试环境使用1分作为支付金额
                orderAmount = (Math.Round(order.DeliveryCost + order.TotalMoney, 2) * 100).ToString();
                //orderAmount = "1";

                orderTime = DateTime.Now.ToString("yyyyMMddHHmmss");

                productName = "购酒网酒水购买";

                productNum = "1";

                productId = "";

                productDesc = "购酒网在线下单(酒类或饮料)";

                ext1 = "";

                ext2 = "";

                payType = "00";

                bankId = "";
                if (!string.IsNullOrEmpty(Request.QueryString["bankId"]))
                {
                    payType = "10";
                    bankId = Request.QueryString["bankId"];
                }

                redoFlag = "0";

                pid = "";

                //生成加密签名串
                //请务必按照如下顺序和规则组成加密串!
                string signMsgVal = "";
                signMsgVal = appendParam(signMsgVal, "inputCharset", inputCharset);
                signMsgVal = appendParam(signMsgVal, "pageUrl", pageUrl);
                signMsgVal = appendParam(signMsgVal, "bgUrl", bgUrl);
                signMsgVal = appendParam(signMsgVal, "version", version);
                signMsgVal = appendParam(signMsgVal, "language", language);
                signMsgVal = appendParam(signMsgVal, "signType", signType);
                signMsgVal = appendParam(signMsgVal, "merchantAcctId", merchantAcctId);
                signMsgVal = appendParam(signMsgVal, "payerName", payerName);
                signMsgVal = appendParam(signMsgVal, "payerContactType", payerContactType);
                signMsgVal = appendParam(signMsgVal, "payerContact", payerContact);
                signMsgVal = appendParam(signMsgVal, "orderId", orderId);
                signMsgVal = appendParam(signMsgVal, "orderAmount", orderAmount);
                signMsgVal = appendParam(signMsgVal, "orderTime", orderTime);
                signMsgVal = appendParam(signMsgVal, "productName", productName);
                signMsgVal = appendParam(signMsgVal, "productNum", productNum);
                signMsgVal = appendParam(signMsgVal, "productId", productId);
                signMsgVal = appendParam(signMsgVal, "productDesc", productDesc);
                signMsgVal = appendParam(signMsgVal, "ext1", ext1);
                signMsgVal = appendParam(signMsgVal, "ext2", ext2);
                signMsgVal = appendParam(signMsgVal, "payType", payType);
                signMsgVal = appendParam(signMsgVal, "bankId", bankId);
                signMsgVal = appendParam(signMsgVal, "redoFlag", redoFlag);
                signMsgVal = appendParam(signMsgVal, "pid", pid);

                //Response.Write(signMsgVal);

                string prikey_path = this.Server.MapPath(@"/99bill/goujiuwang-rsa.pfx");//商户私钥证书路径
                string CertificatePW = "gou19jiu19wang19";//商户私钥密钥
                signMsg = CerRSASignature(signMsgVal, prikey_path, CertificatePW, 2);

                ViewBag.signMsg = signMsg;
                ViewBag.inputCharset = inputCharset;
                ViewBag.pageUrl = pageUrl;
                ViewBag.bgUrl = bgUrl;
                ViewBag.version = version;
                ViewBag.language = language;
                ViewBag.signType = signType;
                ViewBag.merchantAcctId = merchantAcctId;
                ViewBag.payerName = payerName;
                ViewBag.payerContactType = payerContactType;
                ViewBag.payerContact = payerContact;
                ViewBag.orderId = orderId;
                ViewBag.orderAmount = orderAmount;
                ViewBag.orderTime = orderTime;
                ViewBag.productName = productName;
                ViewBag.productNum = productNum;
                ViewBag.productId = productId;
                ViewBag.productDesc = productDesc;
                ViewBag.ext1 = ext1;
                ViewBag.ext2 = ext2;
                ViewBag.payType = payType;
                ViewBag.bankId = bankId;
                ViewBag.redoFlag = redoFlag;
                ViewBag.pid = pid;
            }
            catch (Exception ex)
            {
                string reval = ex.ToString();
                //Response.Redirect(Common.Constant.SiteUrl + "/user/MyOrder.htm");
                return this.Redirect("/User/MyOrder");
            }

            return View("Index");
        }
Пример #5
0
        /// <summary>
        /// 通知
        /// </summary>
        /// 01. 多次支付问题:在未取得支付宝确认支付消息之前,须控制再次支付情况。
        /// 02. 大额支付问题:支付宝存在支付限额,在此情况下,大单支付须拆分到多次支付单中。
        /// <returns></returns>
        public ActionResult Notify()
        {
            LogUtils.Log(
                    string.Format("支付宝支付--接收到支付宝异步通知。准备处理订单支付信息"),
                    "支付宝通知",
                    Category.Info,
                    this.Session.SessionID,
                    this.UserSession.UserID,
                    "Alipay");

            ArrayList sArrary = GetRequestPost();
            string partner = "2088301856479212";		//合作身份者ID
            string key = "sji2sos0koz072vl07sg5xvtctvq6hfp";			//安全检验码
            string input_charset = "utf-8";                     //字符编码格式 目前支持 gb2312 或 utf-8
            string sign_type = "MD5";                           //加密方式 不需修改
            string transport = "http";                         //访问模式,根据自己的服务器是否支持ssl访问,若支持请选择https;若不支持请选择http

            if (sArrary.Count > 0)//判断是否有带返回参数
            {
                AlipayClass.AlipayNotify aliNotify = new AlipayClass.AlipayNotify(sArrary, Request.Form["notify_id"], partner, key, input_charset, sign_type, transport);
                string responseTxt = aliNotify.ResponseTxt; //获取远程服务器ATN结果,验证是否是支付宝服务器发来的请求
                string sign = Request.Form["sign"];         //获取支付宝反馈回来的sign结果
                string mysign = aliNotify.Mysign;           //获取通知返回后计算后(验证)的加密结果

                //写日志记录(若要调试,请取消下面两行注释)
                //string sWord = "responseTxt=" + responseTxt + "\n notify_url_log:sign=" + Request.Form["sign"] + "&mysign=" + mysign + "\n notify回来的参数:" + AlipayFunction.Create_linkstring(sArrary);
                //AlipayFunction.log_result(Server.MapPath("log/" + DateTime.Now.ToString().Replace(":", "")) + ".txt", sWord);

                //判断responsetTxt是否为ture,生成的签名结果mysign与获得的签名结果sign是否一致
                //responsetTxt的结果不是true,与服务器设置问题、合作身份者ID、notify_id一分钟失效有关
                //mysign与sign不等,与安全校验码、请求时的参数格式(如:带自定义参数等)、编码格式有关
                string order_code = Request.Form["out_trade_no"];     //获取订单号
                if (responseTxt == "true" && sign == mysign)//验证成功
                {
                    //获取支付宝的通知返回参数
                    string trade_no = Request.Form["trade_no"];         //支付宝交易号
                    string total_fee = Request.Form["total_fee"];       //获取总金额
                    string subject = Request.Form["subject"];           //商品名称、订单名称
                    string body = Request.Form["body"];                 //商品描述、订单备注、描述
                    string buyer_email = Request.Form["buyer_email"];   //买家支付宝账号
                    string trade_status = Request.Form["trade_status"]; //交易状态
                    //int sOld_trade_status = 0;						//获取商户数据库中查询得到该笔交易当前的交易状态

                    //检查此交易在我系统是否已处理,若是,则不进行其他处理
                    var paymentList = new OrderPaymentService().QueryByTradeNo(trade_no);

                    if (paymentList != null && paymentList.Count > 0)
                    {
                        this.ViewBag.Message = "支付成功,订单号:" + trade_no;
                        return this.Content("Success");
                    }

                    if (Request.Form["trade_status"] == "TRADE_FINISHED" || Request.Form["trade_status"] == "TRADE_SUCCESS")
                    {
                        //放入订单交易完成后的数据库更新程序代码,请务必保证response.Write出来的信息只有success
                        //为了保证不被重复调用,或重复执行数据库更新程序,请判断该笔交易状态是否是订单未处理状态
                        double totalFee = 0;
                        var orderSevice = new OrderService(this.UserSession.UserID, false);
                        var order = orderSevice.QueryByOrderCode(order_code);
                        if (!double.TryParse(total_fee, out totalFee))
                        {
                            LogUtils.Log(
                                string.Format(
                                    "支付宝支付返回支付金额异常,支付宝交易号{0},购酒网订单号{1},支付金额{2},买家支付宝账号{3},交易状态{4}",
                                    trade_no,
                                    order_code,
                                    total_fee,
                                    buyer_email,
                                    trade_status),
                                "支付宝交易通知",
                                Category.Error,
                                this.UserSession.SessionId);
                            return this.Content("failed");
                        }

                        if (order == null)
                        {
                            LogUtils.Log(
                                string.Format(
                                    "支付宝支付返回时获取订单信息异常,支付宝交易号{0},购酒网订单号{1},支付金额{2},买家支付宝账号{3},交易状态{4}",
                                    trade_no,
                                    order_code,
                                    total_fee,
                                    buyer_email,
                                    trade_status),
                                "支付宝交易通知",
                                Category.Error,
                                this.UserSession.SessionId);
                            return this.Content("Success"); //作为成功信息进行返回,防止支付宝服务器反复请求
                        }

                        //测试使用0.01作为支付金额
                        if (totalFee != (order.TotalMoney + order.DeliveryCost))
                        //if (totalFee != 0.01)
                        {
                            LogUtils.Log(
                                string.Format(
                                    "支付宝支付返回支付金额异常,支付宝交易号{0},购酒网订单号{1},支付金额{2},买家支付宝账号{3},交易状态{4}",
                                    trade_no,
                                    order_code,
                                    total_fee,
                                    buyer_email,
                                    trade_status),
                                "支付宝交易通知",
                                Category.Error,
                                this.UserSession.SessionId);
                            return this.Content("failed");
                        }

                        //支付成功,改写数据库订单信息
                        //添加支付记录信息
                        //添加订单状态跟踪信息
                        order.PaymentStatus = 1;
                        order.Status = order.Status == 255 ? 0 : order.Status;
                        if (orderSevice.OrderOnLinePayment(order, totalFee, 4, trade_no))
                        {
                            return this.Content("Success");
                        }
                        else
                        {
                            return this.Content("Fail");
                        }

                        //Response.Redirect(Common.Constant.SiteUrl + "/purchase/Success-Number-" + order_no + "-Msg-1.htm");
                    }
                    else
                    {
                        return this.Content("Success");  //其他状态判断。普通即时到帐中,其他状态不用判断,直接打印success。
                        //logpay = new BLL.AdminLog();
                        //logpay.AddLog("odr_order", 0, "(Page:notify支付宝支付异常)交易状态:" + Request.Form["trade_status"].ToString());
                        //Response.Redirect(Common.Constant.SiteUrl + "/purchase/Success-Number-" + order_no + "-Msg-1.htm");
                    }
                }
                else//验证失败
                {
                    return this.Content("fail");
                    //logpay = new BLL.AdminLog();
                    //string strMsg = string.Format("(Page:notify支付宝支付异常)验证失败(responseTxt:{0},sign:{1},mysign:{2},number:{3})", responseTxt, sign, mysign, order_no);
                    //logpay.AddLog("odr_order", 0, strMsg);
                    //Response.Redirect(Common.Constant.SiteUrl + "/purchase/Success-Number-" + Request.Form["out_trade_no"] + "-Msg-1.htm");
                }
            }
            else
            {
                LogUtils.Log("支付宝支付异步通知无返回参数");
                return this.Content("无通知参数");
                //logpay = new BLL.AdminLog();
                //logpay.AddLog("odr_order", 0, "(Page:notify支付宝支付异常)无通知参数");
            }
        }
Пример #6
0
        /// <summary>
        /// 分页查询所有订单数据
        /// </summary>
        /// <param name="request">请求对象</param>
        /// <param name="OrderCode">订单编号</param>
        /// <param name="Status">订单状态</param>
        /// <param name="PaymentMethodID">支付方式</param>
        /// <param name="UserName">会员名称</param>
        /// <param name="Consignee">收货人</param>
        /// <param name="CpsID">订单来源</param>
        /// <param name="StartDateTime">起始时间</param>
        /// <param name="EndDateTime">结束时间</param>
        /// <param name="MinTotalMoney">最小金额</param>
        /// <param name="MaxTotalMoney">最大金额</param>
        /// <returns></returns>
        public ActionResult QueryOrders(
            [DataSourceRequest] DataSourceRequest request,
            string OrderCode,
            string Status,
            string PaymentMethodID,
            string UserName,
            string Consignee,
            string CpsID,
            string StartDateTime,
            string EndDateTime,
            string MinTotalMoney,
			string MaxTotalMoney, string ReceiveMoblie)
        {
            int pageCount, rowCount;

            string condition = this.BuildOrderSearchCondition(
                OrderCode,
                Status,
                PaymentMethodID,
                UserName,
                Consignee,
                CpsID,
                StartDateTime,
                EndDateTime,
                MinTotalMoney,
                MaxTotalMoney,ReceiveMoblie);

            var paging = new Paging(null, null, "ID", condition, request.Page, request.PageSize, "CreateTime", 1);
            var service = new OrderService(this.SystemUserSession.EmployeeID);

            var list = service.Query(paging, out pageCount, out rowCount);
            if (list == null || list.Count <= 0)
            {
                return Json(null, JsonRequestBehavior.AllowGet);
            }

            var modelList = new List<OrderModel>();
            foreach (var item in list)
            {
                var order = DataTransfer.Transfer<OrderModel>(item, typeof(Order));
                modelList.Add(order);
            }

            var dataSource = new DataSource { Data = modelList, Total = rowCount, Page = pageCount };

            return Json(dataSource, JsonRequestBehavior.AllowGet);
        }
Пример #7
0
        public ActionResult ModifyOrderDescription(int id, string description)
        {
            if (id > 0)
            {
                var service = new OrderService(this.SystemUserSession.EmployeeID);
                service.ModifyOrderDescription(id, description);
            }

            return null;
        }
Пример #8
0
 /// <summary>
 /// 设置订单为废单
 /// </summary>
 /// <param name="orderId">
 /// 订单编码
 /// </param>
 /// <param name="reason">
 /// The reason.
 /// </param>
 /// <returns>
 /// The <see cref="ActionResult"/>.
 /// </returns>
 public ActionResult SetOrderToInvalid(int orderId, string reason)
 {
     var result = new AjaxResponse();
     try
     {
         var orderService = new OrderService(this.SystemUserSession.EmployeeID);
         orderService.SetInvalidByGJW(orderId, reason);
         result.State = 1;
         result.Message = "修改成功!";
         return this.Json(result, JsonRequestBehavior.AllowGet);
     }
     catch (Exception ex)
     {
         result.State = -1;
         result.Message = ex.Message;
         LogUtils.Log("将订单作废操作失败(订单编码:" + orderId + "),错误消息:"+ex.Message+";"+ex.InnerException+";"+ex.StackTrace, "后台作废订单", Category.Error, this.SystemUserSession.SessionID, 0, "Order/SetOrderToInvalid");
         return this.Json(result, JsonRequestBehavior.AllowGet);
     }
 }
 public ActionResult OrderCancelWithRefundView(int orderId, string orderCode)
 {
     var order = new OrderService().QueryById(orderId);
     return this.PartialView(
         "Order/OrderCancelWithRefundTemplate",
         new AftersaleRefundModel
             {
                 OrderID = orderId,
                 TotalMoney = order.TotalMoney,
                 PaymentMoney = new OrderService().GetOrderActualPayment(orderId),
                 OrderCode = orderCode
             });
 }
        /// <summary>
        /// 检查订单状态
        /// </summary>
        /// <param name="orderId">
        /// 订单编码
        /// </param>
        /// <returns>
        /// The <see cref="ActionResult"/>.
        /// </returns>
        public ActionResult CheckOrderStatus(int orderId)
        {
            // 检查订单是否已经发货
            // 未付款未发货:1,已付款未发货:2,已发货:-1,已取消或是废单:-2,订单不存在:-3, 服务器出错:-4
            try
            {
                var order = new OrderService(this.SystemUserSession.EmployeeID).QueryById(orderId);
                if (order == null)
                {
                    return this.Json(new AjaxResponse(3, "订单不存在"), JsonRequestBehavior.AllowGet);
                }

                // 已发货
                if (order.Status == 2 || order.Status == 3)
                {
                    return this.Json(new AjaxResponse(-1, "订单已发货或者签收"), JsonRequestBehavior.AllowGet);
                }

                // 未付款未发货
                if (order.PaymentStatus == 0 && (order.Status == 0 || order.Status == 1 || order.Status == 100))
                {
                    return this.Json(new AjaxResponse(1, "未付款未发货"), JsonRequestBehavior.AllowGet);
                }

                // 已付款未发货
                if (order.PaymentStatus == 1 && (order.Status == 0 || order.Status == 1 || order.Status == 100))
                {
                    return this.Json(new AjaxResponse(2, "已付款未发货"), JsonRequestBehavior.AllowGet);
                }

                // 已取消或是废单
                if (order.Status == 4 || order.Status == 5 || order.Status == 6 || order.Status == 8)
                {
                    return this.Json(new AjaxResponse(-2, "已取消或是废单"), JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception exception)
            {
                TextLogger.Instance.Log("取消订单--查询订单状态出错", Category.Error, exception);
                return this.Json(new AjaxResponse(-4, "服务器出错"), JsonRequestBehavior.AllowGet);
            }

            return this.Json(null, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// The cancel order with refund.
        /// </summary>
        /// <param name="orderCancelCauseID">
        /// The order Cancel Cause ID.
        /// </param>
        /// <param name="orderCancelDescription">
        /// The order Cancel Description.
        /// </param>
        /// <param name="refundModel">
        /// The refund model.
        /// </param>
        /// <returns>
        /// The <see cref="ActionResult"/>.
        /// </returns>
        public ActionResult CancelOrderRefund(int orderCancelCauseID, string Description, AftersaleRefundModel refundModel, int type)
        {
            if (type == 0)
            {
                return
                    this.CancelOrder(
                        new OrderCancelModel()
                            {
                                OrderID = refundModel.OrderID,
                                OrderCancelCauseID = orderCancelCauseID,
                                Description = Description
                            });
            }

            var response = new AjaxResponse();
            if (orderCancelCauseID < 1 || refundModel == null || refundModel.OrderID < 1
                || refundModel.ActualRefundMoney < 0 || refundModel.RefundMethodID < 1)
            {
                response.State = -1;
                response.Message = "参数错误";
                return this.Json(response, JsonRequestBehavior.AllowGet);
            }

            var orderService = new OrderService(this.SystemUserSession.EmployeeID);

            var actualPayment = orderService.GetOrderActualPayment(refundModel.OrderID);
            if (refundModel.ActualRefundMoney > actualPayment)
            {
                response.State = -2;
                response.Message = "退款金额不能大于已支付金额";
                return this.Json(response, JsonRequestBehavior.AllowGet);
            }

            try
            {
                refundModel.EmployeeID = this.SystemUserSession.EmployeeID;
                int state = orderService.OrderCancelRefundByBackstage(
                    orderCancelCauseID,
                    Description,
                    DataTransfer.Transfer<Aftersale_Refund>(refundModel, typeof(AftersaleRefundModel)));

                // 0-订单状态异常,1-操作成功,2-已发货,3-订单已取消、损失或者作废,4-订单未付款
                if (state == 0)
                {
                    response.State = 0;
                    response.Message = "订单状态异常";
                }
                else if (state == 1)
                {
                    response.State = 1;
                    response.Message = "订单取消成功";
                }
                else if (state == 2)
                {
                    response.State = 2;
                    response.Message = "已发货,操作取消";
                }
                else if (state == 3)
                {
                    response.State = 3;
                    response.Message = "订单已取消、已损失或者已作废";
                }
                else if (state == 4)
                {
                    response.State = 4;
                    response.Message = "订单未付款";
                }

                return this.Json(response, JsonRequestBehavior.AllowGet);
            }
            catch (Exception exception)
            {
                TextLogger.Instance.Log("订单取消操作发生错误", Category.Error, exception);

                response.State = -2;
                response.Message = exception.Message;
                return this.Json(response, JsonRequestBehavior.AllowGet);
            }
        }
Пример #12
0
        public ActionResult AddOrder(
            List<ProductModel> products,
            int userID,
            int receiveAddressID,
            int paymentMethodID,
            bool isRequireInvoice,
            OrderInvoiceModel invoiceInfo,
            string description = null)
        {
            try
            {
                if (products == null || products.Count < 1)
                {
                    var data = new AjaxResponse(-1, "订单商品为空!");
                    return this.Json(data);
                }

                if (userID < 1)
                {
                    var data = new AjaxResponse(-1, "用户编码错误!");
                    return this.Json(data);
                }

                if (receiveAddressID < 1)
                {
                    var data = new AjaxResponse(-1, "收货信息地址编码错误!");
                    return this.Json(data);
                }

                if (paymentMethodID < 0)
                {
                    var data = new AjaxResponse(-1, "支付地址错误!");
                    return this.Json(data);
                }

                Order_Invoice invoice = null;
                if (isRequireInvoice)
                {
                    if (invoiceInfo.InvoiceContentID < 0)
                    {
                        var data = new AjaxResponse(-1, "发票消费类别错误!");
                        return this.Json(data);
                    }
                    else if (string.IsNullOrWhiteSpace(invoiceInfo.InvoiceTitle))
                    {
                        var data = new AjaxResponse(-1, "发票抬头为空!");
                        return this.Json(data);
                    }
                    else if (invoiceInfo.InvoiceCost < 0)
                    {
                        var data = new AjaxResponse(-1, "开票金额不能小于或等于0!");
                        return this.Json(data);
                    }

                    invoice = DataTransfer.Transfer<Order_Invoice>(invoiceInfo, typeof(OrderInvoiceModel));
                }

                DateTime createTime;
                var orderCode = MadeCodeService.GetOrderCode(out createTime);

                var orderService = new OrderService(this.SystemUserSession.EmployeeID);
                var order = new Order
                                {
                                    UserID = userID,
                                    RecieveAddressID = receiveAddressID,
                                    CpsID = 0,
                                    PaymentMethodID = paymentMethodID,
                                    OrderCode = orderCode,
                                    OrderNumber = MadeCodeService.ReverseOrderCode(orderCode, createTime),
                                    TotalMoney = 0,
                                    TotalIntegral = 0,
                                    PaymentStatus = 0,
                                    IsRequireInvoice = isRequireInvoice,
                                    Status = paymentMethodID == 0 ? 100 : 0,
                                    Description = string.IsNullOrWhiteSpace(description) ? "后台添加订单" : description,
                                    CreateTime = createTime
                                };

                var orderProducts = new List<Order_Product>();

                foreach (var productModel in products)
                {
                    if (productModel.Quantity > 0)
                    {
                        orderProducts.Add(
                            new Order_Product
                                {
                                    ProductID = productModel.ID,
                                    Quantity = productModel.Quantity,
                                    ProductName = productModel.Name,
                                    TransactPrice = productModel.GoujiuPrice,
                                    CreateTime = DateTime.Now
                                });
                    }
                }

                // 判断是否能够由系统自动确认订单,若能,则自动确认。
                orderService.Add(order, orderProducts, invoice);

                if (orderService.ValidateConfirmOrderBySystem(order))
                {
                    orderService.ConfirmOrderBySystem(order);
                }

                return this.Json(new AjaxResponse(1, "执行成功"));
            }
            catch (Exception exception)
            {
                var data = new AjaxResponse(-1, exception.Message);
                TextLogger.Instance.Log("后台添加订单发生错误", Category.Error, exception);
                return this.Json(data);
            }
        }
Пример #13
0
 public ActionResult AddUser(UserModel userModel)
 {
     try
     {
         var orderService = new OrderService(this.SystemUserSession.EmployeeID);
         var user = new User
                        {
                            UserLevelID = 1,
                            Email = userModel.Email ?? userModel.Mobile,  // 优先使用邮箱作为登录用户名,其次使用手机号。
                            EmailValidate = false,
                            Name = userModel.Name,
                            LoginName = userModel.Email ?? "*****@*****.**", // 后台客户添加用户信息时,若用户没有邮箱,则设置默认值“[email protected]”
                            Mobile = userModel.Mobile,
                            MobileValidate = false,
                            Tel = userModel.Tel,
                            NickName = userModel.Name,
                            Address = userModel.Address,
                            LoginPassword = Encrypt.HashByMD5("123456"),  // 对会员密码进行加密
                            Birthday = null,
                            LastLoginTime = null,
                            Integral = 0,
                            Status = 1,
                            CreateTime = DateTime.Now,
                            CountyID = userModel.CountyID
                        };
         orderService.AddUserInfo(user);
         var addressModel = new UserReceiveAddressModel { CountyID = user.CountyID };
         return
             this.Json(
                 new AjaxResponse(
                     1,
                     new { UserID = user.ID, CountyId = user.CountyID, CountyInfo = addressModel.CountyName }));
         //this.Content(
         //    "{State:'Ok',UserID:'" + user.ID + "',CountyInfo:'" + addressModel.CountyName + "'}");
     }
     catch
     {
         return this.Content("{State:'Error'}");
     }
 }
Пример #14
0
        public JsonResult GetOrderData(int pageIndex, int pageSize, string search)
        {
            var userID = this.GetUserID();
            var condition = "[UserID] = " + userID + " and " +
                            (string.IsNullOrEmpty(search) ? "1=1" : "productName like '%" + search + "%'");
            var paging = new Paging("[view_Orders]", null, "ID", condition, pageIndex, pageSize, "CreateTime", 1);
            int pageCount, rowCount, totalCount;
            var Orders = new OrderService(userID, false).Query(paging, out pageCount, out rowCount);
            if (Orders == null || Orders.Count < 1)
            {
                return this.Json(new { data = Orders, rowsCount = rowCount });
            }

            // 查找订单商品信息
            string orderIDs = "";
            foreach (var order in Orders)
            {
                orderIDs += order.ID + ",";
            }

            orderIDs = orderIDs.Remove(orderIDs.Length - 1, 1);
            paging = new Paging("[view_Order_Products]", null, "ID", "[OrderID] in (" + orderIDs + ")", 1, 1000);
            var orderProducts = new SqlServer().Paging<Order_Product>(paging, out pageCount, out totalCount, null);

            for (var i = 0; i < Orders.Count; i++)
            {
                Orders[i].Products = new List<Order_Product>();
                foreach (var orderProduct in orderProducts)
                {
                    if (orderProduct.OrderID == Orders[i].ID)
                    {
                        orderProduct.Path = Utils.GetProductImage(orderProduct.Path, "1");
                        Orders[i].Products.Add(orderProduct);
                    }
                }
            }

            return this.Json(new { data = Orders, rowsCount = rowCount });
        }
Пример #15
0
        public ActionResult Return()
        {
            LogUtils.Log("接收财付通支付通知消息,订单","财付通支付--支付通知", Category.Info, this.Session.SessionID, this.UserSession.UserID, "Tenpay/Return");

            //密钥
            string key = "f24967df0075851d22411c36b04899ac";

            //创建PayResponseHandler实例
            PayResponseHandler resHandler = new PayResponseHandler(System.Web.HttpContext.Current);

            resHandler.setKey(key);

            string order_code = resHandler.getParameter("sp_billno");

            //判断签名
            if (resHandler.isTenpaySign())
            {
                LogUtils.Log("判断签名合法", "财付通支付--支付通知", Category.Info, this.Session.SessionID, this.UserSession.UserID, "Tenpay/Return");

                //交易单号
                string transaction_id = resHandler.getParameter("transaction_id");

                //支付金额,以分为单位
                string total_fee = resHandler.getParameter("total_fee");

                //支付结果
                string pay_result = resHandler.getParameter("pay_result");

                if (pay_result == "0") //0-已支付,1-未支付,其他为支付错误
                {
                    LogUtils.Log("订单支付成功"+string.Format("订单号:{0},财付通交易号:{1},支付金额:{2}",order_code,transaction_id,total_fee), "财付通支付--支付通知", Category.Info, this.Session.SessionID, this.UserSession.UserID, "Tenpay/Return");
                    //------------------------------
                    //处理业务开始
                    //------------------------------

                    //注意交易单不要重复处理
                    //注意判断返回金额

                    //Common.DataContext ctx = new Common.DataContext();
                    //Model.odr_Order_S os = new Model.odr_Order_S();
                    //os.Action = 14;
                    //os.Number = strNumber;
                    //BLL.Order od = new BLL.Order();
                    //DataTable dt = od.GetOrderInfo(ctx, os);

                    //double totalFee = 0;
                    var orderSevice = new OrderService(this.UserSession.UserID, false);
                    var order = orderSevice.QueryByOrderCode(order_code);

                    //todo:此处应验证订单支付金额是否正确,测试使用1分
                    //if (double.Parse(total_fee) == 1)
                    if (double.Parse(total_fee) == (Math.Round(order.DeliveryCost + order.TotalMoney, 2) * 100))
                    {
                        ViewBag.Message = "财富通--支付成功,"
                                          + string.Format(
                                              "订单号:{0},财付通交易号:{1},支付金额:{2}",
                                              order.OrderCode,
                                              transaction_id,
                                              total_fee);

                        if (order.PaymentStatus != 1)
                        {
                            order.PaymentStatus = 1;
                            order.Status = order.Status == 255 ? 0 : order.Status;
                            //默认5为财富通
                            if (orderSevice.OrderOnLinePayment(order, Math.Round(double.Parse(total_fee)/100,2), 5, transaction_id))
                            {
                                LogUtils.Log(
                                    string.Format(
                                        "订单支付成功,订单状态更新成功,订单号:{0},财付通交易号:{1},支付金额:{2}",
                                        order.OrderCode,
                                        transaction_id,
                                        total_fee),
                                    "财付通支付--支付通知",
                                    Category.Info,
                                    this.Session.SessionID,
                                    this.UserSession.UserID,
                                    "Tenpay/Return");
                            }
                            else
                            {
                                ViewBag.Message = "财富通--支付成功,"
                                                  + string.Format(
                                                      "订单状态更新失败,为了保护您的权益,请立即与客服人员联系。订单号:{0},财付通交易号:{1},支付金额:{2}",
                                                      order.OrderCode,
                                                      transaction_id,
                                                      total_fee);
                                LogUtils.Log(
                                    string.Format(
                                        "订单支付成功,订单状态更新失败,订单号:{0},财付通交易号:{1},支付金额:{2}",
                                        order.OrderCode,
                                        transaction_id,
                                        total_fee),
                                    "财付通支付--支付通知",
                                    Category.Info,
                                    this.Session.SessionID,
                                    this.UserSession.UserID,
                                    "Tenpay/Return");
                            }
                        }
                        ViewBag.Money = total_fee;
                        ViewBag.Url = ConstantParams.SiteUrl + "Tenpay/Success";
                    }
                }
                else
                {
                    LogUtils.Log("订单支付失败(参数指示未支付),"+string.Format("订单号:{0},财付通交易号:{1},支付金额:{2}",order_code,transaction_id,total_fee), "财付通支付--支付通知", Category.Info, this.Session.SessionID, this.UserSession.UserID, "Tenpay/Return");

                    //当做不成功处理
                    ViewBag.Message = "订单支付失败,"
                                      + string.Format(
                                          "订单号:{0},财付通交易号:{1},支付金额:{2}",
                                          order_code,
                                          transaction_id,
                                          total_fee);

                    //Response.Redirect(CONST.Url + "/purchase/PayFinish-Number-" + strNumber + "-Msg-1.htm");
                }

                if (ViewBag.Url == null)
                {
                    ViewBag.Url = ConstantParams.SiteUrl + "Tenpay/Fail";
                }

                return this.View("Return");
            }
            else
            {
                LogUtils.Log("认证签名失败,订单编号:"+order_code, "财付通支付--支付通知", Category.Info, this.Session.SessionID, this.UserSession.UserID, "Tenpay/Return");

                //当做不成功处理
                ViewBag.Message = "订单支付失败," + string.Format("订单号:{0}", order_code);

                return null; //不处理,等待下一次通知
                //Response.Redirect(CONST.Url + "/purchase/PayFinish-Number-" + strNumber + "-Msg-1.htm");
                //string debugInfo = resHandler.getDebugInfo();
                //Response.Write("<br/>debugInfo:" + debugInfo);
            }
        }
Пример #16
0
        public ActionResult DoPay(string ono)
        {
            //商户号
            string bargainor_id = "1211288901";

            //密钥
            string key = "f24967df0075851d22411c36b04899ac";

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

            if (string.IsNullOrWhiteSpace(ono))
            {
                LogUtils.Log("财付通支付错误:订单编号为空", "财付通支付--验证订单编号", Category.Warn, this.Session.SessionID, this.UserSession.UserID, "Tenpay/DoPay");
                return this.Content("<script type='text/javascript'>alert('对不起,订单编号错误,无法完成支付!');window.location='" + ConstantParams.SiteUrl + "User/MyOrder';" + "</script>");
            }

            //验证订单信息
            var order = new OrderService(this.UserSession.UserID, false).QueryByOrderCode(ono);
            if (order == null || order.UserID != this.UserSession.UserID)
            {
                LogUtils.Log("财付通支付错误:订单编号异常(" + ono + ")", "财付通支付--验证订单编号", Category.Warn, this.Session.SessionID, this.UserSession.UserID, "Tenpay/DoPay");
                return this.Content("<script type='text/javascript'>alert('对不起,订单编号错误,无法完成支付!');window.location='" + ConstantParams.SiteUrl + "User/MyOrder';" + "</script>");
            }

            //生成订单10位序列号,此处用时间和随机数生成,商户根据自己调整,保证唯一
            string strReq = ono;
            //if (strReq.Length > 9)
            //    strReq = Session["Number"].ToString().Substring(3);// "" + DateTime.Now.ToString("HHmmss") + TenpayUtil.BuildRandomStr(4);
            //else
            //    strReq = "0" + Session["Number"].ToString();

            //商户订单号,不超过32位,财付通只做记录,不保证唯一性
            string sp_billno = strReq;

            //财付通订单号,10位商户号+8位日期+10位序列号,需保证全局唯一
            string transaction_id = bargainor_id + date + DateTime.Now.ToString("HHmmss") + TenpayUtil.BuildRandomStr(4); //todo:生成唯一的10位系列号,目前用时间和随机数生成
            string return_url = ConstantParams.SiteUrl + "Tenpay/Return";

            //创建PayRequestHandler实例
            PayRequestHandler reqHandler = new PayRequestHandler(System.Web.HttpContext.Current);

            //设置密钥
            reqHandler.setKey(key);

            //初始化
            reqHandler.init();

            //-----------------------------
            //设置支付参数
            //-----------------------------
            reqHandler.setParameter("bargainor_id", bargainor_id);			//商户号
            reqHandler.setParameter("sp_billno", sp_billno);				//商家订单号
            reqHandler.setParameter("transaction_id", transaction_id);		//财付通交易单号
            reqHandler.setParameter("return_url", return_url);				//支付通知url
            reqHandler.setParameter("desc", "购酒网酒水购买 ");	//商品名称

            double total_fee = Math.Round(order.TotalMoney + order.DeliveryCost, 2) * 100;
            string totalfee = total_fee.ToString();
            reqHandler.setParameter("total_fee", totalfee);			//商品金额,以分为单位

            //用户ip,测试环境时不要加这个ip参数,正式环境再加此参数
            reqHandler.setParameter("spbill_create_ip", Request.UserHostAddress);

            //获取请求带参数的url
            string requestUrl = reqHandler.getRequestURL();

            return this.Redirect(requestUrl);

            //string a_link = "<a target=\"_blank\" href=\"" + requestUrl + "\">" + "财付通支付" + "</a>";
            //Response.Write(a_link);

            //post实现方式

            //reqHandler.getRequestURL();
            //Response.Write("<form method=\"post\" action=\""+ reqHandler.getGateUrl() + "\" >\n");
            //Hashtable ht = reqHandler.getAllParameters();
            //foreach(DictionaryEntry de in ht)
            //{
            //    Response.Write("<input type=\"hidden\" name=\"" + de.Key + "\" value=\"" + de.Value + "\" >\n");
            //}
            //Response.Write("<input type=\"submit\" value=\"财付通支付\" >\n</form>\n");

            //获取debug信息
            //string debuginfo = reqHandler.getDebugInfo();
            //Response.Write("<br/>" + debuginfo + "<br/>");

            //Session.Remove("Number");
            //Session.Remove("SumMoney");
            //Session.Remove("PaywayChildID");
            //Session.Remove("BankName");

            //重定向到财付通支付
            //reqHandler.doSend();
        }
Пример #17
0
 /// <summary>
 /// 检查订单是否重复
 /// </summary>
 /// <param name="orderCode">订单编号</param>
 /// <returns></returns>
 private static bool CheckOrderCodeIsOnly(string orderCode)
 {
     orderService = new OrderService();
     var order = orderService.QueryByOrderCode(orderCode);
     if (order != null)
     {
         if (order.OrderCode == orderCode)
         {
             return false;
         }
     }
     return true;
 }
Пример #18
0
 /// <summary>
 /// 根据编码查询订单信息
 /// </summary>
 /// <param name="orderId">
 /// 订单编码
 /// </param>
 /// <returns>
 /// 返回Json结果
 /// </returns>
 public ActionResult GetOrderInfoByID(int orderId)
 {
     var order = new OrderService(this.SystemUserSession.EmployeeID).QueryById(orderId);
     return Json(
         DataTransfer.Transfer<OrderModel>(order, typeof(Order)),
         JsonRequestBehavior.AllowGet);
 }
Пример #19
0
 public ActionResult Payment(string ono)
 {
     var order = new OrderService().QueryByOrderCode(ono);
     if (order.UserID != this.UserSession.UserID || order.Status != 100)
     {
         order = null;
     }
     return this.View(order);
 }
Пример #20
0
        /// <summary>
        /// 查询订单详情
        /// </summary>
        /// <param name="orderID">
        /// 订单编码
        /// </param>
        /// <returns>
        /// The <see cref="ActionResult"/>.
        /// </returns>
        public ActionResult QueryOrderDetails(int orderID)
        {
            var orderDetailModel = new OrderDetailModel();

            if (orderID > 0)
            {
                var order = new OrderService().QueryById(orderID);
                orderDetailModel.OrderInfo = DataTransfer.Transfer<OrderModel>(order, typeof(Order));
                var orderStatusTrackings = new OrderStatusTrackingService().QueryByOrderID(orderID);

                #region 订单状态信息

                var orderState = new OrderState { PaymentMethod = order.PaymentMethodID };
                switch (order.Status)
                {
                    case 0:
                    case 1:
                        orderState.Status = order.PaymentMethodID == 0 ? 1 : 0;
                        break;
                    case 2:
                        orderState.Status = 2;
                        break;
                    case 3:
                        orderState.Status = 4;
                        break;
                    case 100:
                        if (order.PaymentMethodID == 0)
                        {
                            orderState.Status = 0;
                        }

                        break;
                }

                if (orderStatusTrackings != null)
                {
                    orderState.ProcessDatetimes = new List<string>();
                    foreach (var orderStatusTracking in orderStatusTrackings)
                    {
                        if (orderState.Status == 0 && orderStatusTracking.Status == 0)
                        {
                            orderState.ProcessDatetimes.Add(
                                orderStatusTracking.CreateTime.ToString("yyyy-MM-dd hh:mm:ss"));
                        }

                        if (order.PaymentMethodID == 0 && orderState.Status == 1
                            && (orderStatusTracking.Status == 0 || orderStatusTracking.Status == 1))
                        {
                            orderState.ProcessDatetimes.Add(
                                orderStatusTracking.CreateTime.ToString("yyyy-MM-dd hh:mm:ss"));
                        }

                        if (orderState.Status == 2
                            && (orderStatusTracking.Status == 0 || orderStatusTracking.Status == 1
                                || orderStatusTracking.Status == 2))
                        {
                            orderState.ProcessDatetimes.Add(
                                orderStatusTracking.CreateTime.ToString("yyyy-MM-dd hh:mm:ss"));
                        }

                        if (orderState.Status == 4
                            && (orderStatusTracking.Status == 0 || orderStatusTracking.Status == 1
                                || orderStatusTracking.Status == 2 || orderStatusTracking.Status == 3))
                        {
                            orderState.ProcessDatetimes.Add(
                                orderStatusTracking.CreateTime.ToString("yyyy-MM-dd hh:mm:ss"));
                        }
                    }
                }

                orderDetailModel.CurrentOrderState = orderState;

                #endregion

                #region 订单发票信息

                if (order.IsRequireInvoice)
                {
                    orderDetailModel.InvoiceInfo =
                        DataTransfer.Transfer<OrderInvoiceModel>(
                            new OrderInvoiceService().SelectByOrderID(orderID),
                            typeof(Order_Invoice));
                }

                #endregion

                #region 订单变化追踪记录

                orderDetailModel.OrderTrackDetails = new List<OrderTrackDetailModel>();

                if (orderStatusTrackings != null)
                {
                    foreach (var orderStatusTracking in orderStatusTrackings)
                    {
                        System_Employee systemUser = null;

                        if (orderStatusTracking.EmployeeID > 0) systemUser = new SystemEmployeeService().QueryByID(orderStatusTracking.EmployeeID);

                        orderDetailModel.OrderTrackDetails.Add(
                            new OrderTrackDetailModel()
                            {
                                Operator =
                                    orderStatusTracking.EmployeeID > 0
                                        ? systemUser==null?"客服":"客服:"+systemUser.Name
                                        : (orderStatusTracking.UserID > 0) ? "客户" : "系统",
                                OperateSummary = orderStatusTracking.Remark,
                                OperateTime = orderStatusTracking.CreateTime
                            });

                        if (orderStatusTracking.Status == 2)
                        {
                            // 若产品已发货,则获取快递跟踪信息
                            var orderDeliverTrackDetail =
                                new OrderDeliveryTrackDetailService().QueryOrderDeliveryTrackDetailsByOrderID(orderID);
                            if (orderDeliverTrackDetail != null && !string.IsNullOrWhiteSpace(orderDeliverTrackDetail.Steps))
                            {
                                var details = orderDeliverTrackDetail.Steps.Split(';');

                                foreach (var orderDeliveryTrackingDetail in details)
                                {
                                    if (!string.IsNullOrWhiteSpace(orderDeliveryTrackingDetail))
                                    {
                                        var di = orderDeliveryTrackingDetail.Split('|');
                                        if (di.Length >= 2)
                                        {
                                            var tracking = new OrderTrackDetailModel { OperateSummary = di[1], Operator = "快递公司" };

                                            DateTime dt;
                                            if (DateTime.TryParse(di[0], out dt))
                                            {
                                                tracking.OperateTime = dt;
                                            }
                                            orderDetailModel.OrderTrackDetails.Add(tracking);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                #region 老的方法

                /*
                string summary = string.Empty;
                if (order.PaymentMethodID == 0)
                {
                    summary = order.PaymentStatus == 0 ? "您提交了订单,等待付款。" : "您提交了订单,商品准备出库。";
                }
                else if (order.PaymentMethodID == 1)
                {
                    summary = "您提交了订单,请等待确认。";
                }

                orderDetailModel.OrderDeliveryTrackDetails.Add(
                       new OrderDeliveryTrackDetailModel
                       {
                           OperateSummary = summary,
                           Operator = "客户",
                           OperateTime = order.CreateTime
                       });

                if (order.Status == 6)
                {
                    orderDetailModel.OrderDeliveryTrackDetails.Add(
                       new OrderDeliveryTrackDetailModel
                       {
                           OperateSummary = "订单已取消",
                           Operator = "客户",
                           OperateTime = order.CreateTime
                       });
                }
                else if (order.Status == 4 || order.Status == 8)
                {
                    orderDetailModel.OrderDeliveryTrackDetails.Add(
                        new OrderDeliveryTrackDetailModel
                            {
                                OperateSummary = "订单已作废",
                                Operator = "系统",
                                OperateTime = order.CreateTime
                            });
                }
                else
                {
                    if (orderStatusLogs != null)
                    {
                        foreach (var orderStatusLog in orderStatusLogs)
                        {
                            if (orderStatusLog.Status == 1)
                            {
                                summary = "您的订单已确认,准备出库";
                            }

                            if (orderStatusLog.Status == 2)
                            {
                                summary = "您的订单已出库"; // todo: 添加快递单号,快递公司名称
                            }

                            orderDetailModel.OrderDeliveryTrackDetails.Add(
                            new OrderDeliveryTrackDetailModel
                            {
                                OperateSummary = summary,
                                Operator = new SystemEmployeeService().QueryByID(orderStatusLog.EmployeeID).Name,  // todo: 添加操作员工名称
                                OperateTime = order.CreateTime
                            });
                        }
                    }
                }

                // 若订单已发货或已签收,则有物流流转信息
                if (order.Status == 3 || order.Status == 2)
                {
                    var orderDeliverTrackDetails =
                        new OrderDeliveryTrackDetailService().QueryOrderDeliveryTrackDetailsByOrderID(orderID);
                    foreach (var orderDeliveryTrackingDetail in orderDeliverTrackDetails)
                    {
                        orderDetailModel.OrderDeliveryTrackDetails.Add(
                            DataTransfer.Transfer<OrderDeliveryTrackDetailModel>(
                                orderDeliveryTrackingDetail,
                                typeof(Order_Delivery_Tracking_Details)));
                    }
                }
                */

                #endregion

                #endregion

                #region 订单收货信息

                orderDetailModel.ReceiverInfo =
                    DataTransfer.Transfer<UserReceiveAddressModel>(
                        new UserReceiveAddressService().QueryByID(order.RecieveAddressID),
                        typeof(User_RecieveAddress));

                #endregion

                #region 订单商品信息

                orderDetailModel.OrderProducts = new List<OrderProductModel>();

                var orderProducts = new OrderProductService().QueryByOrderId(orderID);
                if (orderProducts != null)
                {
                    foreach (var orderProduct in orderProducts)
                    {
                        orderDetailModel.OrderProducts.Add(
                            DataTransfer.Transfer<OrderProductModel>(orderProduct, typeof(Order_Product)));
                    }
                }

                #endregion

                #region 订单支付信息

                orderDetailModel.PaymentInfo = new PaymentInfoModel
                                                   {
                                                       OrderID = orderID,
                                                       PaymentMethodID = order.PaymentMethodID,
                                                       TotalMoney = order.TotalMoney,
                                                       DeliveryCost = order.DeliveryCost,
                                                       ActualPaid =
                                                           order.PaymentStatus == 1
                                                               ? order.TotalMoney + order.DeliveryCost
                                                               : 0,
                                                       ActualMoney =
                                                           order.TotalMoney + order.DeliveryCost
                                                   };

                #endregion
            }

            return this.View("Order/OrderDetail", orderDetailModel);
        }
Пример #21
0
        public ActionResult Success(string ono, int payType)
        {
            var order = new OrderService().QueryByOrderCode(ono);
            if (order.UserID != this.UserSession.UserID)
            {
                return this.View(new Order());
            }

            this.ViewBag.PayType = payType;
            return this.View(order);
        }
Пример #22
0
        /// <summary>
        /// 确认并修改订单
        /// </summary>
        /// <param name="orderDetail">
        /// 订单详情对象
        /// </param>
        /// <param name="products">
        /// 订单商品列表
        /// </param>
        /// <returns>
        /// The <see cref="ActionResult"/>.
        /// </returns>
        public ActionResult ConfirmAndEditOrderDetail(OrderDetailModel orderDetail, List<OrderProductModel> products)
        {
            try
            {
                if (orderDetail.OrderInfo.IsRequireInvoice
                    && (orderDetail.InvoiceInfo == null
                        || string.IsNullOrWhiteSpace(orderDetail.InvoiceInfo.InvoiceTitle)
                        || orderDetail.InvoiceInfo.InvoiceCost <= 0
                        || orderDetail.InvoiceInfo.InvoiceTypeID < 1))
                {
                    return this.Json(new AjaxResponse() { State = -1, Message = "要求开发票,但发票信息不全!!" });
                }

                if (products == null || products.Count < 0)
                {
                    return this.Json(new AjaxResponse { State = -1, Message = "订单商品不能为空!!" });
                }

                var orderService = new OrderService(this.SystemUserSession.EmployeeID);
                List<Order_Product> productList;
                Order order = ResetOrderInfo(orderDetail, products,out productList);

                orderService.ManualConfirmOrder(
                    order,
                    productList,
                    DataTransfer.Transfer<Order_Invoice>(orderDetail.InvoiceInfo, typeof(OrderInvoiceModel)),
                    DataTransfer.Transfer<User_RecieveAddress>(orderDetail.ReceiverInfo, typeof(UserReceiveAddressModel)));

                return this.Json(new AjaxResponse { State = 1, Message = "操作成功" });
            }
            catch (Exception ex)
            {
                return this.Json(new AjaxResponse { State = -1, Message = ex.Message });
            }
        }
Пример #23
0
        public ActionResult Add(int addressID, int payMethod, string productIds, string intro, 
            int isRequireInvoice, string invoiceTitle, int invoiceContent, int ctype, int cId, double account)
        {
            /***************
             * 前台添加订单流程:
             * 1.检查是否用券,若用,则检查券是否存在,是否符合使用条件。
             * 2.检查是否用余额抵扣,若用,则检查用户是否有足够余额。
             * 3.检查用户是否开发票,若是,检查发票内容是否填写。
             * 4.检查用户收货地址ID是否填写正确
             * 5.检查商品ID列表是否正确
             * todo:下单时检查商品库存
             * ********************/

            #region 检查是否用券
            //todo:券检查
            #endregion

            #region 余额抵用检查

            if (account > 0)
            {
                if (!CheckAccountBalance(account))
                {
                    return this.Json(new AjaxResponse(-1, "账户余额不足"));
                }
            }

            #endregion

            #region 检查发票信息

            if (isRequireInvoice > 0)
            {
                if (invoiceContent < 0)
                {
                    return this.Json(new AjaxResponse(-1, "发票内容错误"));
                }
            }

            #endregion

            #region 检查收货地址ID是否填写正确

            if (addressID <= 0)
            {
                return this.Json(new AjaxResponse(-1, "收货地址错误"));
            }

            var address = new UserReceiveAddressService().QueryByID(addressID);

            //收货地址必须与用户对应
            if (address == null || address.UserID != this.UserSession.UserID)
            {
                return this.Json(new AjaxResponse(-1, "收货地址错误"));
            }

            var addressModel = DataTransfer.Transfer<UserReceiveAddressModel>(address, typeof(User_RecieveAddress));

            if (!new UtilityController().ValidSupportRegion(addressModel.ProvinceID))
            {
                return this.Json(new AjaxResponse(-1, "对不起," + addressModel.CountyName("-") + "暂不支持。"));
            }

            #endregion

            var orderService = new OrderService(this.UserSession.UserID, false);
            try
            {
                var cart = MongoDBHelper.GetModel<UserCartModel>(u => u.VisitorKey == this.UserSession.VisitorKey);
                if (cart == null || cart.BuyList == null || cart.BuyList.Count < 1)
                {
                    return this.Json(new AjaxResponse(-1, "商品不存在或已下架。"));
                }

                string message;

                #region 检查商品列表信息

                if (!CheckBuyProducts(cart.BuyList, out message))
                {
                    LogUtils.Log(
                        message,
                        "前台提交订单:Add",
                        Category.Info,
                        this.UserSession.SessionId,
                        this.UserSession.UserID,
                        "Order/Add");
                    return this.Json(new AjaxResponse(0, message));
                }

                #endregion

                //获取促销相关信息
                var productDictionary = new Dictionary<int, int>();

                foreach (var orderProduct in cart.BuyList)
                {
                    productDictionary.Add(orderProduct.ProductID, orderProduct.Quantity);
                }

                var orderBill = this.GetOrderBill(productDictionary); //new OrderBillServices().QueryOrderBill(productDictionary, this.UserSession.UserID);

                if (orderBill == null
                    || ((orderBill.Products == null || orderBill.Products.Count < 1)
                        && (orderBill.SuitPromoteInfos == null || orderBill.SuitPromoteInfos.Count < 1)))
                {
                    LogUtils.Log("没有获取订单促销信息", "Add", Category.Warn);
                    return this.Json(new AjaxResponse(-1, "商品不存在或者已下架。"));
                }

                #region 检查促销活动

                //限购验证
                foreach (var cartProduct in orderBill.Products)
                {
                    //验证是否有多选一情况
                    if (cartProduct.DenyFlag > 0)
                    {
                        switch (cartProduct.DenyFlag)
                        {
                            case 1:
                                return this.Json(new AjaxResponse(0, string.Format("对不起,{0} 只允许新会员购买!", cartProduct.ProductName)));
                            case 2:
                                return this.Json(new AjaxResponse(0, string.Format("对不起,{0} 只允许老会员购买!", cartProduct.ProductName)));
                            case 3:
                                return
                                    this.Json(new AjaxResponse(0, string.Format("对不起,{0} 只允许通过手机验证会员购买!", cartProduct.ProductName)));
                            case 4:
                                return
                                    this.Json(new AjaxResponse(0, string.Format("对不起,{0} 只允许通过邮箱验证会员购买。", cartProduct.ProductName)));
                            case 5:
                                return this.Json(new AjaxResponse(0, string.Format("对不起,{0} 请先登录。", cartProduct.ProductName)));
                            default:
                                return
                                    this.Json(new AjaxResponse(0, string.Format("对不起,{0} 您不满足此商品的购买条件。", cartProduct.ProductName)));
                        }
                    }

                    //验证多选一互斥促销
                    if (cartProduct.Promotes!=null&&cartProduct.Promotes.FirstOrDefault(p => p.PromoteType == 4) != null && !string.IsNullOrWhiteSpace(cartProduct.Exclude))
                    {
                        var userCart = MongoDBHelper.GetModel<UserCartModel>(u => u.VisitorKey == this.UserSession.VisitorKey);
                        if (userCart != null && userCart.ProductItems.Count > 0)
                        {
                            var excludes = cartProduct.Exclude.Split(',');
                            if (excludes.Length > 0)
                            {
                                foreach (var item in userCart.ProductItems)
                                {
                                    if (item.ProductID != cartProduct.ProductID && excludes.Contains(item.ProductID.ToString()))
                                    {
                                        return
                                            this.Json(
                                                new AjaxResponse(
                                                    0,
                                                    string.Format(
                                                        "对不起,【{0}】与【{1}】不能同时购买。",
                                                        item.ProductName,
                                                        cartProduct.ProductName)));
                                    }
                                }
                            }
                        }
                    }

                    //判断是否是限时抢购,且是否超出了限制量。
                    if (cartProduct.LimitedBuyQuantity > 0 && cartProduct.MaxBuyQuantity < cartProduct.Quantity)
                    {
                        LogUtils.Log("用户订单商品数量超出了限时抢购数量", "Add", Category.Info);
                        return
                            this.Json(
                                new AjaxResponse(
                                    0,
                                    string.Format(
                                        "对不起,{0} 每人限购{1}件,你还可以购买{2}件。",
                                        cartProduct.ProductName,
                                        cartProduct.LimitedBuyQuantity,
                                        cartProduct.MaxBuyQuantity)));
                    }

                    //若是限时抢购,判断是否还有活动库存
                    if (cartProduct.LimitedBuyQuantity > 0 && cartProduct.PromoteResidueQuantity < cartProduct.Quantity)
                    {
                        LogUtils.Log(
                            string.Format(
                                "{0} 活动库存不满足,库存仅剩 {1},用户下单{2}",
                                cartProduct.ProductName,
                                cartProduct.PromoteResidueQuantity,
                                cartProduct.Quantity),
                            "Add",
                            Category.Info);

                        return
                            this.Json(
                                new AjaxResponse(
                                    0,
                                    string.Format(
                                        "对不起,{0} 活动库存不满足,库存仅剩 {1}件。",
                                        cartProduct.ProductName,
                                        cartProduct.PromoteResidueQuantity)));
                    }
                }

                //检查组合促销商品限购情况
                if (orderBill.SuitPromoteInfos != null)
                {
                    foreach (var suitPromoteInfo in orderBill.SuitPromoteInfos)
                    {
                        if (suitPromoteInfo.Products != null)
                        {
                            foreach (var cartProduct in suitPromoteInfo.Products)
                            {
                                //判断是否是限时抢购,且是否超出了限制量。
                                if (cartProduct.LimitedBuyQuantity > 0 && cartProduct.MaxBuyQuantity < cartProduct.Quantity)
                                {
                                    LogUtils.Log("用户订单商品数量超出了限时抢购数量", "Add", Category.Info);
                                    return
                                        this.Json(
                                            new AjaxResponse(
                                                0,
                                                string.Format(
                                                    "对不起,{0} 每人限购{1}件,你还可以购买{2}件。",
                                                    cartProduct.ProductName,
                                                    cartProduct.LimitedBuyQuantity,
                                                    cartProduct.MaxBuyQuantity)));
                                }

                                //若是限时抢购,判断是否还有活动库存
                                if (cartProduct.LimitedBuyQuantity > 0 && cartProduct.PromoteResidueQuantity < cartProduct.Quantity)
                                {
                                    LogUtils.Log(
                                        string.Format(
                                            "{0} 活动库存不满足,库存仅剩 {1},用户下单{2}",
                                            cartProduct.ProductName,
                                            cartProduct.PromoteResidueQuantity,
                                            cartProduct.Quantity),
                                        "Add",
                                        Category.Info);

                                    return
                                        this.Json(
                                            new AjaxResponse(
                                                0,
                                                string.Format(
                                                    "对不起,{0} 活动库存不满足,库存仅剩 {1}件。",
                                                    cartProduct.ProductName,
                                                    cartProduct.PromoteResidueQuantity)));
                                }
                            }
                        }
                    }
                }
                #endregion

                DateTime createTime;
                var orderCode = MadeCodeService.GetOrderCode(out createTime);
                var order = new Order
                                {
                                    UserID = this.UserSession.UserID,
                                    RecieveAddressID = addressID,
                                    CpsID = 0,
                                    PaymentMethodID = payMethod,
                                    OrderCode = orderCode,
                                    OrderNumber = MadeCodeService.ReverseOrderCode(orderCode, createTime),
                                    TotalMoney = 0,
                                    TotalIntegral = 0,
                                    PaymentStatus = 0,
                                    IsRequireInvoice = isRequireInvoice != 0,
                                    Status = payMethod == 0 ? 100 : 0, // 若是在线支付,则设置为等待付款,否则设置为等待确认
                                    Remark = intro,
                                    CreateTime = createTime
                                };

                //获取CPS信息
                order.CpsID = this.GetCpsID();

                Order_Invoice invoice = null;

                if (isRequireInvoice!=0) //需要开发票
                {
                    invoice = new Order_Invoice
                                  {
                                      InvoiceContentID = invoiceContent,
                                      InvoiceTitle =
                                          string.IsNullOrWhiteSpace(invoiceTitle) ? "个人" : invoiceTitle,
                                      InvoiceTypeID = 0
                                  };
                }

                var promoteList = new List<Order_Product_Promote>();
                var buyProducts=new List<Order_Product>();
                var giftCoupons = new List<Gift_Coupon>();

                double totalAmount = 0, totalDiscount = 0, tempDiscount = 0;

                totalAmount += SetBuyList(order.ID, orderBill.Products, ref buyProducts, ref promoteList, out tempDiscount);
                totalDiscount += tempDiscount;

                //组合促销商品
                if (orderBill.SuitPromoteInfos != null)
                {
                    foreach (var suitPromote in orderBill.SuitPromoteInfos)
                    {
                        totalDiscount += suitPromote.PromoteDiscount;

                        totalAmount += SetBuyList(
                            order.ID,
                            suitPromote.Products,
                            ref buyProducts,
                            ref promoteList,
                            out tempDiscount);

                        totalDiscount += tempDiscount;

                        //成交价 = 单品成交价 - 组合优惠摊牌金额
                        if (suitPromote.PromoteDiscount > 0)
                        {
                            for (var i = 0; i < buyProducts.Count; i++)
                            {
                                if (suitPromote.Products.Exists(p => p.ProductID == buyProducts[i].ProductID))
                                {
                                    buyProducts[i].TransactPrice -= buyProducts[i].TransactPrice / suitPromote.TotalPrice
                                                                    * suitPromote.PromoteDiscount;

                                    //组合促销信息
                                    promoteList.Add(
                                        new Order_Product_Promote
                                        {
                                            ProductID = buyProducts[i].ProductID,
                                            PromoteID = suitPromote.PromoteID,
                                            PromoteDiscount =
                                                Math.Round(
                                                    buyProducts[i].TransactPrice / suitPromote.TotalPrice
                                                    * suitPromote.PromoteDiscount,
                                                    2),
                                            PromoteType = suitPromote.PromoteType
                                        });
                                }
                            }
                        }

                        //赠品
                        if (suitPromote.GiftProducts != null)
                        {
                            foreach (var giftProduct in suitPromote.GiftProducts)
                            {
                                var product = new Order_Product
                                                  {
                                                      ProductID = giftProduct.ProductID,
                                                      ProductName = "【赠品】" + giftProduct.ProductName,
                                                      Quantity = giftProduct.Quantity,
                                                      PromotionID = giftProduct.PromotID,
                                                      PromotionType = giftProduct.PromotType,
                                                      TransactPrice = 0,
                                                      PromotionResult = 1,
                                                      Integral = 0,
                                                      RebateRate = 0,
                                                      Commission = 0,
                                                      CreateTime = DateTime.Now
                                                  };
                                buyProducts.Add(product);

                                promoteList.Add(
                                    new Order_Product_Promote
                                        {
                                            OrderID = order.ID,
                                            ProductID = giftProduct.ProductID,
                                            PromoteID = giftProduct.PromotID,
                                            PromoteType = giftProduct.PromotType,
                                            ExtField = "赠品"
                                        });
                            }
                        }

                        if (suitPromote.GiftCoupons != null)
                        {
                            giftCoupons.AddRange(suitPromote.GiftCoupons);
                        }
                    }
                }

                order.TotalMoney = orderBill.TotalPrice - orderBill.TotalDiscount;

                //todo:特殊促销处理,此处为了快速开发,硬编码
                foreach (var cartProduct in buyProducts)
                {
                    if (cartProduct.ProductID == 4153)
                    {
                        order.TotalMoney = order.TotalMoney - cartProduct.TransactPrice;
                        cartProduct.TransactPrice = 0;
                        cartProduct.Quantity = 1;
                    }
                }

                order.DeliveryCost = order.TotalMoney >= 100 ? 0 : 10; //todo:需要改掉
                order.Discount = totalDiscount;
                var orderId = orderService.Add(order, buyProducts, invoice, giftCoupons, promoteList);
                this.ResetUserCart(cart, buyProducts);

                //更新特殊活动
                foreach (var orderProduct in buyProducts)
                {
                    var specialPromotes = MongoDBHelper.GetModels<SpecialPromote>(p => p.GiftProductID == orderProduct.ProductID && p.ID > 0);

                    if (specialPromotes != null && specialPromotes.Count > 0) //若不是,则直接跳过
                    {
                        var specialPromote = specialPromotes[0]; //一个赠品只能参加一个活动

                        var userPromote = specialPromote.UserPromotes.FirstOrDefault(u => u.UserID == this.UserSession.UserID);

                        //即使找不到参加活动的记录,但领取了商品,我们依然认为此用户已经参加了活动
                        if (userPromote == null)
                        {
                            userPromote = new UserPromote { UserID = this.UserSession.UserID };
                        }

                        userPromote.OrderID = order.ID;
                        userPromote.HasGetGift=true;
                        userPromote.GetGiftTime = DateTime.Now;
                        userPromote.GiftID = orderProduct.ProductID;

                        specialPromote.UserPromotes.Remove(u => u.UserID == userPromote.UserID);
                        specialPromote.UserPromotes.Add(userPromote);

                        MongoDBHelper.UpdateModel<SpecialPromote>(specialPromote, sp => sp.ID == specialPromote.ID);
                    }
                }

                LogUtils.Log(
                    "前台添加订单成功,订单编码:" + orderId + "\n\r",
                    "Order.Add",
                    Category.Info,
                    this.UserSession.SessionId,
                    this.UserSession.UserID);

                return this.Json(new AjaxResponse(1, "订单提交成功", order.OrderCode));
            }
            catch (Exception ex)
            {
                LogUtils.Log(
                    "前台添加订单出错了,错误信息:"+ex.Message+"\n\r"+ex.StackTrace,
                    "Order.Add",
                    Category.Error,
                    this.UserSession.SessionId,
                    this.UserSession.UserID);
                return this.Json(new AjaxResponse(-2, "对不起,提交订单出错了。"));
            }
        }
Пример #24
0
        //
        // GET: /Alipay/
        //public ActionResult Index()
        //{
        //    return View("Alipay");
        //}
        public ActionResult Alipay(string ono)
        {
            LogUtils.Log(
                string.Format("支付宝支付流程开始。用户UserID:{0},支付订单编号:{1}", this.UserSession.UserID, ono),
                "进入支付宝支付",
                Category.Info,
                this.Session.SessionID,
                this.UserSession.UserID,
                "Alipay");

            string partner = "2088301856479212";		//合作身份者ID
            string key = "sji2sos0koz072vl07sg5xvtctvq6hfp";			//安全检验码
            string seller_email = "*****@*****.**";	//签约支付宝账号或卖家支付宝帐户
            string input_charset = "utf-8";						//字符编码格式 目前支持 gb2312 或 utf-8
            string show_url = "";				//网站商品的展示地址,不允许加?id=123这类自定义参数
            string sign_type = "MD5";							//加密方式 不需修改
            string out_trade_no = ono; 	//订单号
            string subject = "酒水";			//订单名称,显示在支付宝收银台里的“商品名称”里,显示在支付宝的交易管理的“商品名称”的列表里。
            string body = "购酒网在线下单(酒类或饮料)";			//订单描述、订单详细、订单备注,显示在支付宝收银台里的“商品描述”里

            var order = new OrderService(this.UserSession.UserID, false).QueryByOrderCode(out_trade_no);
            if (order == null || order.UserID != this.UserSession.UserID)
            {
                LogUtils.Log("支付宝支付错误:订单编号异常("+out_trade_no+")", "支付宝支付--验证订单编号", Category.Warn, this.Session.SessionID, this.UserSession.UserID, "Alipay/Alipay");
                return this.Content("<script type='text/javascript'>alert('对不起,订单编号错误,无法完成支付!');window.location='"+ConstantParams.SiteUrl+"User/MyOrder';"+"</script>");
            }

            if (true)//即时到账
            {
                #region 即时到账

                string notify_url = ConstantParams.SiteUrl+ "Alipay/Notify";	//交易过程中服务器通知的页面 要用 http://格式的完整路径,不允许加?id=123这类自定义参数
                string return_url = ConstantParams.SiteUrl + "Alipay/Return";	//付完款后跳转的页面 要用 http://格式的完整路径,不允许加?id=123这类自定义参数

                string antiphishing = "0";							//防钓鱼功能开关,'0'表示该功能关闭,'1'表示该功能开启。默认为关闭

                //string total_fee = (Convert.ToDouble(dt.Rows[0]["SumMoney"]) + Convert.ToDouble(dt.Rows[0]["Freight"])).ToString();	//需要支付的金额

                //扩展功能参数——网银提前
                string paymethod = "directPay";						//默认支付方式,四个值可选:bankPay(网银); cartoon(卡通); directPay(余额); CASH(网点支付)
                string defaultbank = "";							//默认网银代号,代号列表见http://club.alipay.com/read.php?tid=8681379

                if (!string.IsNullOrEmpty(Request.QueryString["paymethod"]))
                {
                    paymethod = "bankPay"; 	//默认支付方式,四个值可选:bankPay(网银); cartoon(卡通); directPay(余额); CASH(网点支付)
                    defaultbank = Request.QueryString["defaultbank"];		//默认网银代号,代号列表见http://club.alipay.com/read.php?tid=8681379
                }
                //扩展功能参数——防钓鱼
                string encrypt_key = "";							//防钓鱼时间戳,初始值
                string exter_invoke_ip = "";						//客户端的IP地址,初始值
                if (antiphishing == "1")
                {
                    encrypt_key = AlipayClass.AlipayFunction.Query_timestamp(partner);
                    exter_invoke_ip = "";							//获取客户端的IP地址,建议:编写获取客户端IP地址的程序
                }

                //扩展功能参数——其他
                string extra_common_param = "";						//自定义参数,可存放任何内容(除=、&等特殊字符外),不会显示在页面上
                string buyer_email = "";							//默认买家支付宝账号

                //扩展功能参数——分润(若要使用,请按照注释要求的格式赋值)
                string royalty_type = "";							//提成类型,该值为固定值:10,不需要修改
                string royalty_parameters = "";
                //提成信息集,与需要结合商户网站自身情况动态获取每笔交易的各分润收款账号、各分润金额、各分润说明。最多只能设置10条
                //提成信息集格式为:收款方Email_1^金额1^备注1|收款方Email_2^金额2^备注2
                //如:
                //royalty_type = "10";
                //royalty_parameters = "[email protected]^0.01^分润备注一|[email protected]^0.01^分润备注二";

                //扩展功能参数——自定义超时(若要使用,请按照注释要求的格式赋值)
                //该功能默认不开通,需联系客户经理咨询
                string it_b_pay = "";								//超时时间,不填默认是15天。八个值可选:1h(1小时),2h(2小时),3h(3小时),1d(1天),3d(3天),7d(7天),15d(15天),1c(当天)
                double total_fee = Math.Round(order.TotalMoney + order.DeliveryCost, 2);
                //total_fee = 0.01; //todo:此处使用0.01用于测试

                //构造请求函数
                AlipayClass.AlipayService aliService;
                if (Session["token"] == null)
                {
                    aliService = new AlipayClass.AlipayService
                        (partner,
                        seller_email,
                        return_url,
                        notify_url,
                        show_url,
                        out_trade_no,
                        subject,
                        body,
                        total_fee.ToString(),
                        paymethod,
                        defaultbank,
                        encrypt_key,
                        exter_invoke_ip,
                        extra_common_param,
                        buyer_email,
                        royalty_type,
                        royalty_parameters,
                        it_b_pay,
                        key,
                        input_charset,
                        sign_type
                        );
                }
                else
                {
                    string token = Session["token"].ToString();
                    aliService = new AlipayClass.AlipayService
                        (partner,
                        seller_email,
                        return_url,
                        notify_url,
                        show_url,
                        out_trade_no,
                        subject,
                        body,
                        total_fee.ToString(),
                        paymethod,
                        defaultbank,
                        encrypt_key,
                        exter_invoke_ip,
                        extra_common_param,
                        buyer_email,
                        royalty_type,
                        royalty_parameters,
                        it_b_pay,
                        key,
                        input_charset,
                        sign_type,
                        token
                        );
                    Session.Remove("token");
                }
                //GET方式传递
                LogUtils.Log(
                    string.Format("支付宝支付--创建支付链接。"),
                    "进入支付宝支付",
                    Category.Info,
                    this.Session.SessionID,
                    this.UserSession.UserID,
                    "Alipay");

                string url = aliService.Create_url();

                LogUtils.Log(
                    string.Format("支付宝支付--创建支付链接完成。链接:{0}",url),
                    "进入支付宝支付",
                    Category.Info,
                    this.Session.SessionID,
                    this.UserSession.UserID,
                    "Alipay");

                //Session.Remove("OrderID");
                //Session.Remove("Number");
                //Session.Remove("SumMoney");
                //Session.Remove("SendDays");
                //Response.Redirect(url);
                return this.Redirect(url);

                #endregion
            }
        }
Пример #25
0
        /// <summary>
        /// 取消订单
        /// </summary>
        /// <param name="ono"></param>
        /// <param name="orderCancelCauseID"></param>
        /// <returns></returns>
        public ActionResult Cancel(string ono, int orderCancelCauseID)
        {
            var response = new AjaxResponse();
            //if (orderID < 1 || orderCancelCauseID < 1)
            //{
            //    response.State = -1;
            //    response.Message = "参数错误";
            //    return this.Json(response, JsonRequestBehavior.AllowGet);
            //}

            var order = new OrderService(this.UserSession.UserID, false).QueryByOrderCode(ono);
            if (order == null || order.UserID != this.UserSession.UserID)
            {
                response.State = -1;
                response.Message = "订单编号错误";
                LogUtils.Log(
                    "用户取消订单时订单编号(" + ono + ")错误或者获取对应订单数据为空",
                    "前台取消订单",
                    Category.Error,
                    this.UserSession.SessionId,
                    this.UserSession.UserID,
                    "/Order/Cancel");
                return this.Json(response, JsonRequestBehavior.AllowGet);
            }

            //可取消条件:
            // 1.只有在线支付且未支付
            // 2.订单货到付款且未确认
            if (order.Status != 100 && (order.Status == 0 && order.PaymentMethodID == 0))
            {
                LogUtils.Log(
                    "前台尝试取消不符合取消条件的订单(订单号:" + ono + ")",
                    "前台取消订单",
                    Category.Warn,
                    this.UserSession.SessionId,
                    this.UserSession.UserID,
                    "/Order/Cancel");
                TextLogger.Instance.Log("前台尝试取消不符合取消条件的订单(订单号:" + ono + ",用户名:"+this.UserSession.UserID+")", Category.Warn, null);

                response.State = -1;
                response.Message = "此订单不符合取消条件";
                return this.Json(response);
            }

            try
            {
                var orderCancel = new Order_Cancel
                                      {
                                          OrderID = order.ID,
                                          CreateTime = DateTime.Now,
                                          OrderCancelCauseID = orderCancelCauseID,
                                          UserID = this.UserSession.UserID
                                      };

                int state = new OrderService(this.UserSession.UserID,false).OrderCancelByBackstage(orderCancel);

                // 0-订单状态异常,1-操作成功,2-已发货,3-订单已取消、损失或者作废
                if (state == 0)
                {
                    response.State = 0;
                    response.Message = "订单状态异常";
                }
                else if (state == 1)
                {
                    response.State = 1;
                    response.Message = "订单取消成功";
                }
                else if (state == 2)
                {
                    response.State = 2;
                    response.Message = "已发货,取消订单操作取消";
                }
                else if (state == 3)
                {
                    response.State = 3;
                    response.Message = "订单已取消、已损失或者已作废";
                }
                else if (state == 4)
                {
                    response.State = 4;
                    response.Message = "订单已付款";
                }
                else
                {
                    response.State = 0;
                    response.Message = "订单状态异常";
                }

                LogUtils.Log(
                    "前台尝试取消订单(订单号:" + ono + "),结果:(状态:" + response.State + ";消息:" + response.Message + ")",
                    "前台取消订单",
                    Category.Info,
                    this.UserSession.SessionId,
                    this.UserSession.UserID,
                    "/Order/Cancel");

                return this.Json(response, JsonRequestBehavior.AllowGet);
            }
            catch (Exception exception)
            {
                TextLogger.Instance.Log("订单取消操作发生错误", Category.Error, exception);

                response.State = -2;
                response.Message = exception.Message;
                return this.Json(response, JsonRequestBehavior.AllowGet);
            }
        }
Пример #26
0
        public ActionResult Return()
        {
            try
            {
                ArrayList sArrary = GetRequestGet();
                ///////////////////////以下参数是需要设置的相关配置参数,设置后不会更改的//////////////////////
                string partner = "2088301856479212"; //合作身份者ID
                string key = "sji2sos0koz072vl07sg5xvtctvq6hfp"; //安全检验码
                string input_charset = "utf-8"; //字符编码格式 目前支持 gb2312 或 utf-8
                string sign_type = "MD5"; //加密方式 不需修改
                string transport = "http"; //访问模式,根据自己的服务器是否支持ssl访问,若支持请选择https;若不支持请选择http
                //////////////////////////////////////////////////////////////////////////////////////////////

                if (sArrary.Count > 0) //判断是否有带返回参数
                {
                    AlipayClass.AlipayNotify aliNotify = new AlipayClass.AlipayNotify(
                        sArrary,
                        Request.QueryString["notify_id"],
                        partner,
                        key,
                        input_charset,
                        sign_type,
                        transport);

                    string responseTxt = aliNotify.ResponseTxt; //获取远程服务器ATN结果,验证是否是支付宝服务器发来的请求
                    string sign = Request.QueryString["sign"]; //获取支付宝反馈回来的sign结果
                    string mysign = aliNotify.Mysign; //获取通知返回后计算后(验证)的加密结果

                    //写日志记录(若要调试,请取消下面两行注释)
                    //string sWord = "responseTxt=" + responseTxt + "\n return_url_log:sign=" + Request.QueryString["sign"] + "&mysign=" + mysign + "\n return回来的参数:" + AlipayFunction.Create_linkstring(sArrary);
                    //AlipayFunction.log_result(Server.MapPath("log/" + DateTime.Now.ToString().Replace(":", "")) + ".txt", sWord);

                    //判断responsetTxt是否为ture,生成的签名结果mysign与获得的签名结果sign是否一致
                    //responsetTxt的结果不是true,与服务器设置问题、合作身份者ID、notify_id一分钟失效有关
                    //mysign与sign不等,与安全校验码、请求时的参数格式(如:带自定义参数等)、编码格式有关
                    string order_code = Request.QueryString["out_trade_no"]; //获取订单号
                    if (responseTxt == "true" && sign == mysign) //验证成功
                    {
                        //获取支付宝的通知返回参数
                        string trade_no = Request.QueryString["trade_no"]; //支付宝交易号
                        string total_fee = Request.QueryString["total_fee"]; //获取总金额
                        string subject = Request.QueryString["subject"]; //商品名称、订单名称
                        string body = Request.QueryString["body"]; //商品描述、订单备注、描述
                        string buyer_email = Request.QueryString["buyer_email"]; //买家支付宝账号
                        string trade_status = Request.QueryString["trade_status"]; //交易状态
                        int sOld_trade_status = 0; //获取商户数据库中查询得到该笔交易当前的交易状态

                        //验证此第三方交易是否已经处理,若是,则不进行重复处理,否则,更新订单信息

                        var paymentList = new OrderPaymentService().QueryByTradeNo(trade_no);
                        if (paymentList != null && paymentList.Count > 0)
                        {
                            this.ViewBag.Message = "支付成功,订单号:" + order_code;
                            this.ViewBag.Money = paymentList.Sum(p => p.PaymentMoney);
                            return this.View("Success");
                        }

                        double totalFee = 0;
                        var orderSevice = new OrderService(this.UserSession.UserID, false);
                        var order = orderSevice.QueryByOrderCode(order_code);
                        if (!double.TryParse(total_fee, out totalFee))
                        {
                            LogUtils.Log(
                                string.Format(
                                    "支付宝支付返回支付金额异常,支付宝交易号{0},购酒网订单号{1},支付金额{2},买家支付宝账号{3},交易状态{4}",
                                    trade_no,
                                    order_code,
                                    total_fee,
                                    buyer_email,
                                    trade_status),
                                "支付宝交易通知",
                                Category.Error,
                                this.UserSession.SessionId);
                            this.ViewBag.Message = "支付异常,请速与我司客服联系处理。订单号:" + order_code;
                            return this.View("Success");
                        }

                        if (order == null)
                        {
                            LogUtils.Log(
                                string.Format(
                                    "支付宝支付返回时获取订单信息异常,支付宝交易号{0},购酒网订单号{1},支付金额{2},买家支付宝账号{3},交易状态{4}",
                                    trade_no,
                                    order_code,
                                    total_fee,
                                    buyer_email,
                                    trade_status),
                                "支付宝交易通知",
                                Category.Error,
                                this.UserSession.SessionId);
                            this.ViewBag.Message = "支付异常,请速与我司客服联系处理。订单号:" + order_code;
                            return this.View("Success");
                        }

                        //if (totalFee != 0.01)
                        if (totalFee != (order.TotalMoney + order.DeliveryCost))
                        {
                            LogUtils.Log(
                                string.Format(
                                    "支付宝支付返回支付金额异常,支付宝交易号{0},购酒网订单号{1},已支付金额{2},订单应支付金额{3},买家支付宝账号{4},交易状态{5}",
                                    trade_no,
                                    order_code,
                                    total_fee,
                                    order.TotalMoney + order.DeliveryCost,
                                    buyer_email,
                                    trade_status),
                                "支付宝交易通知",
                                Category.Error,
                                this.UserSession.SessionId);

                            this.ViewBag.Message = "支付异常,请速与我司客服联系,确认订单状态。订单号:" + order_code;
                            return this.View("Success");
                        }

                        //支付成功,改写数据库订单信息
                        //添加支付记录信息
                        //添加订单状态跟踪信息
                        order.PaymentStatus = 1;
                        order.Status = order.Status == 255 ? 0 : order.Status;
                        orderSevice.OrderOnLinePayment(order, totalFee, 4, trade_no);
                        this.ViewBag.Money = totalFee;
                        this.ViewBag.Message = "订单支付成功,订单号:" + order_code;
                        return this.View("Success");

                    }
                    else //验证失败
                    {
                        //lbVerify.Text = "验证失败";
                        //logpay = new BLL.AdminLog();
                        string strMsg =
                            string.Format(
                                "(Page:Return支付宝支付异常)验证失败(responseTxt:{0},sign:{1},mysign:{2},number:{3})",
                                responseTxt,
                                sign,
                                mysign,
                                order_code);
                        //logpay.AddLog("odr_order", 0, strMsg);
                        //Response.Redirect(
                        //    Common.Constant.SiteUrl + "/purchase/Success-Number-" + Request.QueryString["out_trade_no"]
                        //    + "-Msg-1.htm");
                        this.ViewBag.Message = strMsg;
                        return this.View("Success");
                    }
                }
                else
                {
                    //在处理你的请求时出错
                    //lbVerify.Text = "无返回参数";
                    //logpay = new BLL.AdminLog();
                    //logpay.AddLog("odr_order", 0, "(Page:Return支付宝支付异常)" + lbVerify.Text);
                    //Response.Redirect(
                    //    Common.Constant.SiteUrl + "/purchase/Success-Number-" + Request.QueryString["out_trade_no"]
                    //    + "-Msg-1.htm");
                    this.ViewBag.Message = "支付失败,无返回参数";
                    return this.View("Success");
                }
            }
            catch (Exception exception)
            {
                LogUtils.Log(
                    "支付宝支付完成跳转回时产生异常,异常消息:" + exception.Message + ",InnerException:" + exception.InnerException + ",堆栈:"
                    + exception.StackTrace,
                    "[Order] 订单支付宝支付",
                    Category.Error);
                return this.View("Success");
            }
        }
Пример #27
0
 public ActionResult MyOrder()
 {
     var orders = new OrderService(this.UserSession.UserID, false).QueryByUserID(this.UserSession.UserID);
     return this.View("MyOrder", orders);
 }
Пример #28
0
        //功能函数。将变量值不为空的参数组成字符串。结束
        /// <summary>
        /// 接收返回的信息
        /// </summary>
        /// <returns></returns>
        public ActionResult ReceivePki()
        {
            // payState & strPayMsg & strNumber 记录快钱支付结果
            bool payState = false;              // 快钱支付状态
            string strPayMsg = string.Empty;    // 支付结果
            string strNumber = string.Empty;    // 订单号
            try
            {
                //获取人民币网关账户号
                string merchantAcctId = Request["merchantAcctId"].ToString().Trim();

                //获取网关版本.固定值
                ///快钱会根据版本号来调用对应的接口处理程序。
                ///本代码版本号固定为v2.0
                string version = Request["version"].ToString().Trim();

                //获取语言种类.固定选择值。
                ///只能选择1、2、3
                ///1代表中文;2代表英文
                ///默认值为1
                string language = Request["language"].ToString().Trim();

                //签名类型.固定值
                ///1代表MD5签名
                ///当前版本固定为1
                string signType = Request["signType"].ToString().Trim();

                //获取支付方式
                ///值为:10、11、12、13、14
                ///00:组合支付(网关支付页面显示快钱支持的各种支付方式,推荐使用)10:银行卡支付(网关支付页面只显示银行卡支付).11:电话银行支付(网关支付页面只显示电话支付).12:快钱账户支付(网关支付页面只显示快钱账户支付).13:线下支付(网关支付页面只显示线下支付方式).14:B2B支付(网关支付页面只显示B2B支付,但需要向快钱申请开通才能使用)
                string payType = Request["payType"].ToString().Trim();

                //获取银行代码
                ///参见银行代码列表
                string bankId = Request["bankId"].ToString().Trim();

                //获取商户订单号
                string orderId = Request["orderId"].ToString().Trim();

                //获取订单提交时间
                ///获取商户提交订单时的时间.14位数字。年[4位]月[2位]日[2位]时[2位]分[2位]秒[2位]
                ///如:20080101010101
                string orderTime = Request["orderTime"].ToString().Trim();

                //获取原始订单金额
                ///订单提交到快钱时的金额,单位为分。
                ///比方2 ,代表0.02元
                string orderAmount = Request["orderAmount"].ToString().Trim();

                //获取快钱交易号
                ///获取该交易在快钱的交易号
                string dealId = Request["dealId"].ToString().Trim();

                //获取银行交易号
                ///如果使用银行卡支付时,在银行的交易号。如不是通过银行支付,则为空
                string bankDealId = Request["bankDealId"].ToString().Trim();

                //获取在快钱交易时间
                ///14位数字。年[4位]月[2位]日[2位]时[2位]分[2位]秒[2位]
                ///如;20080101010101
                string dealTime = Request["dealTime"].ToString().Trim();

                //获取实际支付金额
                ///单位为分
                ///比方 2 ,代表0.02元
                string payAmount = Request["payAmount"].ToString().Trim();

                //获取交易手续费
                ///单位为分
                ///比方 2 ,代表0.02元
                string fee = Request["fee"].ToString().Trim();

                //获取扩展字段1
                string ext1 = Request["ext1"].ToString().Trim();

                //获取扩展字段2
                string ext2 = Request["ext2"].ToString().Trim();

                //获取处理结果
                ///10代表 成功; 11代表 失败
                string payResult = Request["payResult"].ToString().Trim();

                //获取错误代码
                ///详细见文档错误代码列表
                string errCode = Request["errCode"].ToString().Trim();

                //获取加密签名串
                string signMsg = Request["signMsg"].ToString().Trim();

                //生成加密串。必须保持如下顺序。
                string merchantSignMsgVal = "";
                merchantSignMsgVal = appendParam(merchantSignMsgVal, "merchantAcctId", merchantAcctId);
                merchantSignMsgVal = appendParam(merchantSignMsgVal, "version", version);
                merchantSignMsgVal = appendParam(merchantSignMsgVal, "language", language);
                merchantSignMsgVal = appendParam(merchantSignMsgVal, "signType", signType);
                merchantSignMsgVal = appendParam(merchantSignMsgVal, "payType", payType);
                merchantSignMsgVal = appendParam(merchantSignMsgVal, "bankId", bankId);
                merchantSignMsgVal = appendParam(merchantSignMsgVal, "orderId", orderId);
                merchantSignMsgVal = appendParam(merchantSignMsgVal, "orderTime", orderTime);
                merchantSignMsgVal = appendParam(merchantSignMsgVal, "orderAmount", orderAmount);
                merchantSignMsgVal = appendParam(merchantSignMsgVal, "dealId", dealId);
                merchantSignMsgVal = appendParam(merchantSignMsgVal, "bankDealId", bankDealId);
                merchantSignMsgVal = appendParam(merchantSignMsgVal, "dealTime", dealTime);
                merchantSignMsgVal = appendParam(merchantSignMsgVal, "payAmount", payAmount);
                merchantSignMsgVal = appendParam(merchantSignMsgVal, "fee", fee);
                merchantSignMsgVal = appendParam(merchantSignMsgVal, "ext1", ext1);
                merchantSignMsgVal = appendParam(merchantSignMsgVal, "ext2", ext2);
                merchantSignMsgVal = appendParam(merchantSignMsgVal, "payResult", payResult);
                merchantSignMsgVal = appendParam(merchantSignMsgVal, "errCode", errCode);

                strNumber = orderId;
                //商家进行数据处理,并跳转会商家显示支付结果的页面
                ///首先进行签名字符串验证

                string pubkey_path = this.Server.MapPath(@"/99bill/99bill.cert.rsa.20140728.cer");//快钱公钥证书路径
                string CertificatePW = "gou19jiu19wang19";//存放公钥的证书密码
                if (CerRSAVerifySignature(merchantSignMsgVal, signMsg, pubkey_path, CertificatePW, 2))
                {
                    switch (payResult)
                    {
                        case "10":
                            /*
                             ' 商户网站逻辑处理,比方更新订单支付状态为成功
                            ' 特别注意:只有signMsg.ToUpper() == merchantSignMsg.ToUpper(),且payResult=10,才表示支付成功!
                             * 因为快钱会重复通知这个页面,首先判断订单是否已经更新,没有更新做更新有则不做更新,
                             * 同时将返回的付款金额payamount与提交订单前的订单金额进行对比校验,如果一致则更新订单。
                            */

                            //报告给快钱处理结果,并提供将要重定向的地址。

                            //Common.DataContext ctx = new Common.DataContext();
                            //Model.odr_Order_S os = new Model.odr_Order_S();
                            //os.Action = 14;
                            //os.Number = orderId;
                            //BLL.Order od = new BLL.Order();
                            //DataTable dt = od.GetOrderInfo(ctx, os);
                            //double totalFee = 0;
                            var orderSevice = new OrderService(this.UserSession.UserID, false);
                            var order = orderSevice.QueryByOrderCode(orderId);

                            //todo:此处应验证订单支付金额是否正确,测试使用1分
                            //if (double.Parse(payAmount) == 1)
                            double payMoney = 0.00;
                            if (!double.TryParse(payAmount, out payMoney))
                            {
                                LogUtils.Log("快钱返回支付金额异常,异常金额为:"+payAmount);
                            }
                            else if (payMoney == Math.Round(order.DeliveryCost + order.TotalMoney, 2) * 100)
                            {
                                if (order.PaymentStatus != 1) //需要更新订单状态信息
                                {
                                    ViewBag.Message = "快钱--支付成功,"
                                                      + string.Format(
                                                          "订单号:{0},快钱交易号:{1},支付金额:{2}",
                                                          order.OrderCode,
                                                          dealId,
                                                          payAmount);

                                    if (order.PaymentStatus != 1)
                                    {
                                        order.PaymentStatus = 1;
                                        order.Status = order.Status == 255 ? 0 : order.Status;
                                        if (orderSevice.OrderOnLinePayment(
                                            order,
                                            Math.Round(payMoney/100,2), //转为元单位
                                            7,
                                            dealId))
                                        {
                                            LogUtils.Log(
                                                string.Format(
                                                    "订单支付成功,订单状态更新成功,订单号:{0},快钱交易号:{1},支付金额:{2}",
                                                    order.OrderCode,
                                                    dealId,
                                                    payAmount),
                                                "快钱支付--支付通知",
                                                Category.Info,
                                                this.Session.SessionID,
                                                this.UserSession.UserID,
                                                "Tenpay/Return");
                                        }
                                        else
                                        {
                                            ViewBag.Message = "快钱通--支付成功,"
                                                              + string.Format(
                                                                  "订单状态更新失败,为了保护您的权益,请立即与客服人员联系。订单号:{0},快钱交易号:{1},支付金额:{2}",
                                                                  order.OrderCode,
                                                                  dealId,
                                                                  payAmount);
                                            LogUtils.Log(
                                                string.Format(
                                                    "订单支付成功,订单状态更新失败,订单号:{0},快钱交易号:{1},支付金额:{2}",
                                                    order.OrderCode,
                                                    dealId,
                                                    payAmount),
                                                "快钱支付--支付通知",
                                                Category.Info,
                                                this.Session.SessionID,
                                                this.UserSession.UserID,
                                                "Tenpay/Return");
                                        }
                                    }

                                    //判断是否以插入流程
                                    //bool isExists = Controllers.Logic.CartCircuit.IsExists(oc.Id, 1);
                                    //if (isExists)
                                    //{
                                    //    Controllers.Logic.Cart.SetPayWay(oc.Number);
                                    //}
                                }
                                payState = true;

                                //报告给快钱处理结果,并提供将要重定向的地址。
                                rtnOk = "1";
                                rtnUrl = ConstantParams.SiteUrl + "_99Bill/Success";
                            }
                            else
                            {
                                strPayMsg = "支付金额不匹配(" + double.Parse(payAmount).ToString() + "!=" + Math.Round((order.TotalMoney + order.DeliveryCost) * 100, 0).
                                            ToString() + "),订单号:" + orderId + ",快钱交易号:" + dealId + ",银行交易号:" + bankDealId;
                                LogUtils.Log(strPayMsg,"快钱支付通知",Category.Error,this.Session.SessionID,this.UserSession.UserID,"_99Bill/ReceivePki");
                                ViewBag.Message = "订单支付金额异常,为了保护您的权益,请立即与客服人员联系。"
                                                  + string.Format(
                                                      "订单号:{0},快钱交易号:{1},已支付金额:{2},应支付金额{3}",
                                                      orderId,
                                                      dealId,
                                                      Math.Round(Convert.ToDouble(payAmount) / (double)100, 2),
                                                      order.DeliveryCost + order.TotalMoney);

                                rtnUrl = ConstantParams.SiteUrl + "_99Bill/Fail";
                            }
                            break;
                        default:
                            strPayMsg = "支付结果:支付失败";
                            rtnOk = "1";
                            rtnUrl = ConstantParams.SiteUrl + "_99Bill/Fail"; //Common.Constant.SiteUrl + "/purchase/Success-Number-" + orderId + "-Msg-1.htm";
                            break;
                    }
                }
                else//验签失败
                {
                    strPayMsg = "验签失败";
                    rtnOk = "0";
                    rtnUrl = ConstantParams.SiteUrl + "_99Bill/Fail";//Common.Constant.SiteUrl + "/purchase/Success-Number-" + orderId + "-Msg-1.htm";
                }
            }
            catch (Exception ex)
            {
                strPayMsg = strPayMsg + ex.Message;
                rtnOk = "0";
                rtnUrl = ConstantParams.SiteUrl + "_99Bill/Fail";
            }
            finally
            {
                if (!payState)
                {
                    if (!string.IsNullOrEmpty(strNumber))
                    {
                        strPayMsg = "(Number:" + strNumber + ")" + strPayMsg;
                    }
                    strPayMsg = "快钱支付异常," + strPayMsg;
                    if (strPayMsg.Length > 200)
                    {
                        strPayMsg = strPayMsg.Substring(0, 200);
                    }
                    //log.AddLog("odr_order", 0, strPayMsg);
                    LogUtils.Log(
                        strPayMsg,
                        "快钱支付--支付通知",
                        Category.Info,
                        this.Session.SessionID,
                        this.UserSession.UserID,
                        "Tenpay/Return");
                }
            }

            ViewBag.rtnOk = rtnOk;
            ViewBag.rtnUrl = rtnUrl;
            return this.View("ReceivePki");
        }
Пример #29
0
        public ActionResult API()
        {
            string orderCode = Server.UrlDecode(Request.QueryString["orderid"]);//订单编号
            string strMsg = "";
            SqlTransaction transaction = null;

            try
            {
                string username = Server.UrlDecode(Request.QueryString["username"]);//ERP昵称
                string password = Server.UrlDecode(Request.QueryString["password"]);//ERP密码
                string key = Server.UrlDecode(Request.QueryString["key"]);//公钥
                string sign = Server.UrlDecode(Request.QueryString["sign"]);//检验码
                string method = Server.UrlDecode(Request.QueryString["method"]);//调用接口

                #region 访问日志

                try
                {
                    new OrderERPLogService().AddHwLog(new Hw_Log { Content = Request.Url.ToString(), Number = orderCode }, null);
                    LogUtils.Log(string.Format("成功写入ERP系统访问日志,订单编号:{0},日志信息:{1}", orderCode, Request.Url.ToString()), "ERP订单回写", Category.Error);
                }
                catch (Exception exception)
                {
                    LogUtils.Log(string.Format("写入ERP系统访问日志失败,订单编号:{0},日志信息:{1},错误信息:{2}", orderCode, Request.Url.ToString(), exception.Message + "/" + exception.InnerException), "ERP订单回写", Category.Error);
                }

                #endregion

                #region 基本参数验证
                if (string.IsNullOrEmpty(username))
                {
                    strMsg = SetMsg("0", "昵称不能为空", orderCode);
                    //Response.Write(strMsg);
                    return this.Content(strMsg);
                }
                if (string.IsNullOrEmpty(orderCode))
                {
                    strMsg = SetMsg("0", "订单不正确", orderCode);
                    //Response.Write(strMsg);
                    return this.Content(strMsg);
                }
                if (username != "hongware")
                {
                    strMsg = SetMsg("0", "昵称不正确", orderCode);
                    //Response.Write(strMsg);
                    return this.Content(strMsg);
                }
                if (string.IsNullOrEmpty(password))
                {
                    strMsg = SetMsg("0", "密码不能为空", orderCode);
                    //Response.Write(strMsg);
                    return this.Content(strMsg);
                }
                if (password != "bir19ming19ham")
                {
                    strMsg = SetMsg("0", "密码不正确", orderCode);
                    //Response.Write(strMsg);
                    return this.Content(strMsg);
                }
                if (string.IsNullOrEmpty(key))
                {
                    strMsg = SetMsg("0", "公钥不能为空", orderCode);
                    //Response.Write(strMsg);
                    return this.Content(strMsg);
                }
                if (key != "g1w9j1r9w")
                {
                    strMsg = SetMsg("0", "公钥不正确", orderCode);
                    //Response.Write(strMsg);
                    return this.Content(strMsg);
                }
                if (string.IsNullOrEmpty(sign))
                {
                    strMsg = SetMsg("0", "检验码不能为空", orderCode);
                    //Response.Write(strMsg);
                    return this.Content(strMsg);
                }
                if (string.IsNullOrEmpty(orderCode))
                {
                    strMsg = SetMsg("0", "订单编号不能为空", orderCode);
                    //Response.Write(strMsg);
                    return this.Content(strMsg);
                }
                string sign_Md5 = Encrypt.HwErpMd5(username + password + orderCode + key);
                if (sign != sign_Md5)
                {
                    strMsg = SetMsg("0", "检验码不正确", orderCode);
                    //Response.Write(strMsg);
                    return this.Content(strMsg);
                }
                if (string.IsNullOrEmpty(method))
                {
                    strMsg = SetMsg("0", "调用方法名不能为空", orderCode);
                    //Response.Write(strMsg);
                    return this.Content(strMsg);
                }
                method = method.ToLower();
                #endregion

                #region 订单当前状态

                var orderService = new OrderService();
                var orderTracking = new OrderStatusTrackingService();

                var order = orderService.QueryByOrderCode(orderCode);

                if (order == null || order.ID < 1)
                {
                    strMsg = SetMsg("0", "未查到此订单号,请核实", orderCode);
                    //Response.Write(strMsg);
                    return this.Content(strMsg);
                }
                int OrderID = order.ID;
                int State = order.Status;
                #endregion

                if (method == "api.order.send")
                {
                    #region 订单发货
                    if (State == 0)
                    {
                        strMsg = SetMsg("0", "订单还未确认", orderCode);
                        //Response.Write(strMsg);
                        return this.Content(strMsg);
                    }
                    else if (State == 2)
                    {
                        strMsg = SetMsg("0", "订单已发货", orderCode);
                        //Response.Write(strMsg);
                        return this.Content(strMsg);
                    }
                    else if (State == 3)
                    {
                        strMsg = SetMsg("0", "订单已签收", orderCode);
                        //Response.Write(strMsg);
                        return this.Content(strMsg);
                    }
                    else if (State == 4 || State == 5 || State == 8)
                    {
                        strMsg = SetMsg("0", "订单已取消", orderCode);
                        //Response.Write(strMsg);
                        return this.Content(strMsg);
                    }

                    string expressno = string.Empty;
                    expressno = Server.UrlDecode(Request.QueryString["expressno"]);//快递代码
                    string expressnum = Server.UrlDecode(Request.QueryString["expressnum"]);//快递单号
                    string deliverydate = Server.UrlDecode(Request.QueryString["deliverydate"]);//发货日期

                    #region 参数验证
                    if (string.IsNullOrEmpty(expressno))
                    {
                        strMsg = SetMsg("0", "快递代码不能为空", orderCode);
                        //Response.Write(strMsg);
                        return this.Content(strMsg);
                    }
                    if (string.IsNullOrEmpty(expressnum))
                    {
                        strMsg = SetMsg("0", "快递单号不能为空", orderCode);
                        //Response.Write(strMsg);
                        return this.Content(strMsg);
                    }
                    if (string.IsNullOrEmpty(deliverydate))
                    {
                        strMsg = SetMsg("0", "发货日期不能为空", orderCode);
                        //Response.Write(strMsg);
                        return this.Content(strMsg);
                    }
                    #endregion

                    Config_Delivery_Corporation deliveryCorporation = null;

                    #region 更新订单发货状态
                    /*
                     订单发货:
                     * 1.更改订单状态,
                     * 2.更改订单跟踪状态
                     */
                    try
                    {
                        var deliveryCorporations = new ConfigDeliveryCorporationService().QueryAllConfigDeliveryCorporations();

                        if (deliveryCorporations != null && deliveryCorporations.Count > 1)
                        {
                            deliveryCorporation =
                                deliveryCorporations.Find(dc => expressno.Equals(dc.Number, StringComparison.OrdinalIgnoreCase));

                        }

                        if (deliveryCorporation == null)
                        {
                            deliveryCorporation = new Config_Delivery_Corporation();
                            LogUtils.Log("没有获取到代号为:" + expressno.ToUpper() + "的配送公司", "API", Category.Warn);
                        }

                        var tracking = new Order_Status_Tracking();

                        tracking.MailNo = expressnum;
                        tracking.ExpressNumber = expressno.ToUpper();
                        tracking.OrderID = OrderID;
                        tracking.Status = 2;
                        tracking.EmployeeID = 0;
                        tracking.UserID = 0;
                        tracking.Remark = string.Format(
                            "订单已发货,配送单位:{0} {1}; 快递单号:{2}",
                            deliveryCorporation.Name,
                            deliveryCorporation.URL,
                            expressnum);

                        tracking.CreateTime = Convert.ToDateTime(deliverydate);

                        orderService.SqlServer.BeginTransaction();
                        transaction = orderService.SqlServer.Transaction;

                        orderTracking.Add(tracking, transaction);

                        order.Status = 2;
                        order.DeliveryCorporationID = deliveryCorporation.ID;
                        orderService.Edit(order, transaction);

                        transaction.Commit();
                    }
                    catch (Exception exception)
                    {
                        if (transaction != null)
                        {
                            transaction.Rollback();
                        }

                        LogUtils.Log(
                            string.Format(
                                "[Order_ERP]ERP回写发货订单时发生错误,订单编号:{0},错误消息:{1}",
                                orderCode,
                                exception.Message + "/" + exception.InnerException),
                            "[Order_ERP]ERP订单发货回写官网",
                            Category.Error);

                        strMsg = SetMsg("0", "更新订单发货状态发生异常", orderCode);
                        //Response.Write(strMsg);
                        return this.Content(strMsg);
                    }
                    finally
                    {
                        if (transaction != null && transaction.Connection != null
                            && transaction.Connection.State != ConnectionState.Closed)
                        {
                            transaction.Connection.Close();
                        }
                    }
                    #endregion

                    #region 短信发送

                    try
                    {
                        var orderReceiver = new UserReceiveAddressService().QueryByID(order.UserID);

                        if (orderReceiver != null && orderReceiver.Mobile != null)
                        {
                            var moList = new List<string>();
                            moList.Add(orderReceiver.Mobile);

                            var sm = new ShortMessage
                            {
                                ReceiveMobiles = moList,
                                Content =
                                    string.Format(
                                        "亲爱的购酒网会员,您的订单(订单号:{0})支付方式为:{1},已经发货,配送公司:{2}, 单号:{3}。请注意保持手机畅通。",
                                        orderCode,
                                        order.PaymentMethodName,
                                        deliveryCorporation.Name,
                                        deliveryCorporation.Number)
                            };
                            sm.Send();
                            LogUtils.Log(
                                "用户:" + orderReceiver.Consignee + "电话:" + orderReceiver.Mobile + "成功发送短信",
                                "SendSms",
                                Category.Info,
                                Session.SessionID);

                        }
                        else
                        {
                            LogUtils.Log("[Order_ERP]由于没有获取到订单收货人或收货人的手机号不存在,因此订单(" + order.OrderCode + ")发货,未发送通知短信", "[Order_ERP]订单发货回写发送短信SendSms", Category.Error);
                        }
                    }
                    catch (Exception ex)
                    {
                        LogUtils.Log("[Order_ERP]ERP订单发货发送短信发生错误,错误消息:" + ex.Message + "/" + ex.InnerException, "[Order_ERP]订单发货回写发送短信SendSms", Category.Error);
                    }

                    #endregion

                    strMsg = SetMsg("1", "订单状态更新成功", orderCode);
                    //Response.Write(strMsg);
                    return this.Content(strMsg);

                    #endregion
                }
                else if (method == "api.order.cancel")
                {
                    #region 订单取
                    if (State == 0)
                    {
                        strMsg = SetMsg("0", "订单还未确认", orderCode);
                        //Response.Write(strMsg);
                        return this.Content(strMsg);
                    }
                    else if (State == 2)
                    {
                        strMsg = SetMsg("0", "订单已发货", orderCode);
                        //Response.Write(strMsg);
                        return this.Content(strMsg);
                    }
                    else if (State == 3)
                    {
                        strMsg = SetMsg("0", "订单已确认收货", orderCode);
                        //Response.Write(strMsg);
                        return this.Content(strMsg);
                    }
                    else if (State == 4 || State == 5 || State == 8)
                    {
                        strMsg = SetMsg("0", "订单已取消", orderCode);
                        //Response.Write(strMsg);
                        return this.Content(strMsg);
                    }

                    try
                    {
                        orderService.SetInvalidByERP(order.ID, "订单作废");
                    }
                    catch (Exception exception)
                    {

                        LogUtils.Log(
                            string.Format(
                                "[Order_ERP]ERP订单取消回写发生错误,订单号:{0},错误消息:{1}",
                                orderCode,
                                exception.Message + "/" + exception.InnerException),
                            "[Order_ERP]ERP订单取消回写",
                            Category.Error);

                        strMsg = SetMsg("0", "订单作废发生错误", orderCode);
                        //Response.Write(strMsg);
                        return this.Content(strMsg);
                    }

                    strMsg = SetMsg("1", "订单作废成功", orderCode);
                    //Response.Write(strMsg);
                    return this.Content(strMsg);

                    #endregion
                }

                strMsg = SetMsg("0", "调用方法名不正确", orderCode);
                //Response.Write(strMsg);
                return this.Content(strMsg);
            }
            catch (Exception)
            {
                strMsg = SetMsg("0", "订单回写发生异常", orderCode);
                //Response.Write(strMsg);
                return this.Content(strMsg);
            }
        }