Ejemplo n.º 1
0
 public static OrderLogDto ToOrderLogDto(this OrderLog p)
 {
     return(Mapper.Map <OrderLog, OrderLogDto>(p));
 }
Ejemplo n.º 2
0
        internal static List <OrderLog> Convert(string[] htmlLogs)
        {
            var orderLogs = new List <OrderLog>();

            bool isNewOrder   = true;
            bool isFirstOrder = true;
            var  orderLog     = new OrderLog();

            for (int i = 1; i < htmlLogs.Length; i++)
            {
                var logsArray = htmlLogs[i].Replace("<td>", "").Split("</td>");


                //if Order filled, to sozdaju novyj OrderLog i poka ne budet Order submitted
                // pishu vse komissii v etot objekt, kogda submitted,
                if (logsArray[1] == "Order filled")
                {
                    isNewOrder        = false;
                    orderLog.OpenDate = logsArray[0].ToDateTime();
                    //Order[IVF20150128_03595926306857, USD / JPY, BUY, 20414.0 at 118.144] filled
                    var   currentLog = logsArray[2].Replace(" ", string.Empty);
                    Regex pattern    = new Regex(@".+\[(.+)\,.+\].+");
                    Match match      = pattern.Match(logsArray[2]);
                    var   label      = match.Groups[1].Value.Split(',').First();
                    orderLog.Label = label;
                }

                if (!isNewOrder)
                {
                    if (logsArray[1] == "Commissions")
                    {
                        double comission = GetComission(logsArray);
                        if (comission != 0)
                        {
                            orderLog.Comisions.Add(comission);
                        }
                    }
                }
                if (logsArray[1] == "Order submitted" || i == htmlLogs.Length - 1) // or this is last item
                {
                    isNewOrder = true;
                    if (isFirstOrder)
                    {
                        isFirstOrder = false;
                    }
                    else
                    {
                        orderLogs.Add(orderLog);
                    }

                    orderLog = new OrderLog();
                }
            }
            var strBuilder = new StringBuilder();

            foreach (var log in orderLogs)
            {
                if (log.Comisions.Count == 0)
                {
                    strBuilder.Append($"{log.OpenDate},{log.Label},0\n");
                }
                if (log.Comisions.Count == 1)
                {
                    strBuilder.Append($"{log.OpenDate},{log.Label},{log.Comisions.First()}\n");
                }
                if (log.Comisions.Count == 2)
                {
                    strBuilder.Append($"{log.OpenDate},{log.Label},{log.Comisions.First()},{log.Comisions[1]}\n");
                }
            }
            string path = @"C:\Users\ASUS\Documents\FX\sample_reports\ordersWithCommissions.csv";

            File.WriteAllText(path, strBuilder.ToString());

            return(orderLogs);
        }
Ejemplo n.º 3
0
        public string OrderStatusUpdate(int OrderID, string Status)
        {
            Order ostatus = db.Order.Find(OrderID);

            ostatus.TransactStatus = Status.ToString();
            db.SaveChanges();
            string          value     = Status;
            int             custid    = ostatus.CustomerID;
            string          _sub      = string.Empty;
            CustomerDetails custemail = db.CustomerDetails.Where(x => x.CustID == custid).FirstOrDefault();

            System.Text.RegularExpressions.Regex expr = new Regex(@"^\d{10}$");
            if (!expr.IsMatch(custemail.CustEmail))
            {
                if (custemail.CustEmail != null || custemail.CustEmail != "")
                {
                    if (value == "Order Placed")
                    {
                        _sub = "Order Placed";
                    }
                    if (value == "Order InProgress")
                    {
                        _sub = "Order InProgress";
                    }
                    if (value == "Order shipped")
                    {
                        _sub = "Order Shipped";
                    }
                    if (value == "Order Delivered")
                    {
                        _sub = "Order Delivered";
                    }
                    if (value == "Order Cancel")
                    {
                        _sub = "Order Cancel";
                    }
                    string Emailtext  = System.IO.File.ReadAllText(@"" + Server.MapPath("~/Template/Emailtemp.txt"));
                    string Emailtext1 = "";
                    string Emailtext2 = "";
                    Emailtext  = Emailtext.Replace("@custname", custemail.CustFName + " " + custemail.CustLName);
                    Emailtext1 = Emailtext.Replace("@Orderno", OrderID.ToString());
                    Emailtext2 = Emailtext1.Replace("@Status", Status);

                    OTPEmailOder(custemail.CustEmail, Emailtext2, "LivingSTUD.com : #" + OrderID + " " + _sub);
                }
            }
            else
            {
                OTPMobileOrder(custemail.CustEmail, "Your #" + OrderID + " " + Status + " ,\r\n Track your order on http://livingstud.com/OrderTrack/" + OrderID + "\r\n Get Order details at  http://www.livingstud.com/orders/Paymentsuccessfull?orderid=" + OrderID + " \r\n continue shopping with us on http://www.livingstud.com  \r\n LivingStud.com team", "LivingSTUD.com " + Status + " : #" + OrderID);
            }
            OrderLog ol = new OrderLog();

            ol.OID        = OrderID;
            ol.CustId     = custemail.CustID.ToString();
            ol.Status     = Status;
            ol.InsertDate = DateTime.Now;
            ol.Owner      = "Kaustubh";
            if (Status == "Order InProgress")
            {
                ol.Owner = "Vishu";
            }
            if (Status == "Order shipped")
            {
                ol.Owner = "Onkar";
            }
            db.OrderLogs.Add(ol);
            db.SaveChanges();
            return("Order ID : " + OrderID + " Status Changed To : " + Status);
        }
Ejemplo n.º 4
0
        public int MakePayment()
        {
            int orderid = 0;

            if (Session["CustId"] != "" || Session["CustId"] != null)
            {
                CustomerDetails cd         = db.CustomerDetails.Find(Convert.ToInt32(Session["CustId"]));
                int             custid     = Convert.ToInt32(Session["CustId"].ToString());
                int             twopercent = 0;
                List <Order>    or         = db.Order.Where(x => x.CustomerID == custid).ToList();
                if (or.Count == 0)
                {
                    twopercent         = Convert.ToInt32(TempData["pTotalCost"]) * 2 / 100;
                    cd.WalletMoney     = twopercent;
                    db.Entry(cd).State = System.Data.Entity.EntityState.Modified;
                    db.SaveChanges();
                }
                Order NewOrder = new Order();
                NewOrder.CustomerID     = cd.CustID;
                NewOrder.ProducID       = 0;
                NewOrder.ColorID        = 0;
                NewOrder.SizeID         = 0;
                NewOrder.Quantity       = 0;
                NewOrder.CompanyName    = cd.CustFName ?? "";
                NewOrder.ContactFName   = cd.CustFName ?? "";
                NewOrder.ContactLName   = cd.CustLName ?? "";
                NewOrder.ContactTitle   = "";
                NewOrder.Address1       = cd.CustAddress1;
                NewOrder.Address2       = cd.CustAddress2 ?? "";
                NewOrder.Order_City     = cd.CustCity ?? 0;
                NewOrder.Order_State    = cd.CustState ?? 0;
                NewOrder.PostalCode     = cd.CustPostalCode;
                NewOrder.Country        = cd.CustCountry ?? 0;
                NewOrder.Phone          = cd.CustPhone ?? "";
                NewOrder.Fax            = cd.CustFax ?? "";
                NewOrder.Email          = cd.CustEmail;
                NewOrder.WebSite        = cd.CustWebSite ?? "";
                NewOrder.PaymentMethods = "ONLINE";
                NewOrder.TranactionID   = 0;
                NewOrder.OrderDate      = DateTime.Now;
                NewOrder.RequiredDate   = DateTime.Now.AddDays(7);
                NewOrder.ShipedDate     = DateTime.Now;
                NewOrder.TransactStatus = "Order Placed";
                NewOrder.ErrMsg         = "NA";
                NewOrder.PaymentAmount  = Convert.ToDecimal(TempData["pTotalCost"]);
                NewOrder.PaidAount      = 0;
                NewOrder.PaymentDate    = DateTime.Now;
                NewOrder.IsActive       = true;
                NewOrder.IsDelete       = false;
                NewOrder.IsUpdate       = false;
                NewOrder.InsertDate     = DateTime.Now;
                NewOrder.LMDDate        = DateTime.Now;
                db.Order.Add(NewOrder);
                db.SaveChanges();
                orderid = NewOrder.OrderID;
                if (orderid > 0)
                {
                    List <Order> sessionProductList = (List <Order>)Session["CartLst"];
                    if (sessionProductList != null)
                    {
                        for (int i = 0; i < Convert.ToInt32(sessionProductList.Count); i++)
                        {
                            OrderedItems   oi       = new OrderedItems();
                            ProductDetails pdetails = db.ProductDetails.Find(Convert.ToInt32(sessionProductList[i].ProducID));
                            ProductDetails pds      = db.ProductDetails.Find(Convert.ToInt32(sessionProductList[i].ProducID));

                            oi.OrderID            = orderid;
                            oi.ProductID          = Convert.ToInt32(sessionProductList[i].ProducID);
                            oi.ProductCode        = pdetails.ProductCode;
                            oi.ProductName        = pdetails.ProductName;
                            oi.ProductCategory    = pdetails.ProductCategory ?? 0;
                            oi.ProductSubCategory = pdetails.ProductSubCategory ?? 0;
                            oi.ProductSize        = sessionProductList[i].SizeID.ToString();
                            oi.ProductColor       = sessionProductList[i].ColorID.ToString();
                            oi.ProductQuantity    = Convert.ToInt32(sessionProductList[i].Quantity);
                            oi.ProductPrice       = sessionProductList[i].VAT;
                            oi.VAT           = pdetails.VAT ?? 0;
                            oi.ProductWeight = pdetails.ProductWeight ?? 0;
                            oi.IsActive      = true;
                            oi.IsDelete      = false;
                            oi.IsUpdate      = false;
                            oi.InsertDate    = DateTime.Now;
                            oi.LMDDate       = DateTime.Now;
                            db.OrderedItems.Add(oi);
                            db.SaveChanges();
                            //int remainingqty = qytnp[0] - oi.ProductQuantity;
                            //pds.ProductQuantity = remainingqty;
                            //db.Entry(pds).State = EntityState.Modified;
                            //db.SaveChanges();
                            Session["MyCartval"] = 0;
                        }
                    }
                }

                if (cd.CustPhone != null)
                {
                    //Your authentication key
                    string authKey = "144054A8Is1H8TDV58be6289";
                    //Multiple mobiles numbers separated by comma
                    string mobileNumber = cd.CustPhone;
                    //Sender ID,While using route4 sender id should be 6 characters long.
                    string senderId = "SHPLOL";
                    //Your message to send, Add URL encoding here.
                    int    _min    = 1000;
                    int    _max    = 9999;
                    Random _rdm    = new Random();
                    int    rnum    = _rdm.Next(_min, _max);
                    string message = HttpUtility.UrlEncode("livingstud.com : Order Thank you " + cd.CustPhone + " For livingstud with us . Your Order id is  " + orderid + ", Track Order http://livingstud.com/Orders/OrderTrack , Please Continue Shopping with us http://www.livingstud.com");

                    //Prepare you post parameters
                    StringBuilder sbPostData = new StringBuilder();
                    sbPostData.AppendFormat("authkey={0}", authKey);
                    sbPostData.AppendFormat("&mobiles={0}", mobileNumber);
                    sbPostData.AppendFormat("&message={0}", message);
                    sbPostData.AppendFormat("&sender={0}", senderId);
                    sbPostData.AppendFormat("&route={0}", "4");

                    try
                    {
                        //Call Send SMS API
                        string sendSMSUri = "http://api.msg91.com/api/sendhttp.php";
                        //Create HTTPWebrequest
                        HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create(sendSMSUri);
                        //Prepare and Add URL Encoded data
                        UTF8Encoding encoding = new UTF8Encoding();
                        byte[]       data     = encoding.GetBytes(sbPostData.ToString());
                        //Specify post method
                        httpWReq.Method        = "POST";
                        httpWReq.ContentType   = "application/x-www-form-urlencoded";
                        httpWReq.ContentLength = data.Length;
                        using (Stream stream = httpWReq.GetRequestStream())
                        {
                            stream.Write(data, 0, data.Length);
                        }
                        //Get the response
                        HttpWebResponse response       = (HttpWebResponse)httpWReq.GetResponse();
                        StreamReader    reader         = new StreamReader(response.GetResponseStream());
                        string          responseString = reader.ReadToEnd();

                        //Close the response
                        reader.Close();
                        response.Close();
                    }
                    catch (SystemException ex)
                    {
                    }
                }
                if (cd.CustEmail != null)
                {
                    try
                    {
                        using (MailMessage mail = new MailMessage())
                        {
                            mail.From = new MailAddress("*****@*****.**");//[email protected]
                            mail.To.Add(cd.CustEmail);
                            mail.Subject = "livingstud.com : Thank you " + cd.CustFName + " For Shopping with us";
                            string ifmurl = "http://www.livingstud.com/orders/Paymentsuccessfull?orderid=" + orderid;
                            //mail.Body = "ShopLootle.com : Thank you " + cd.CustFName + " For Shopping with us . Your Order id is  " + orderid + ", Track Order http://livingstud.com/Orders/OrderTrack , Please Continue Shopping with us http://wwwLivingstud.com <br><iframe src=" + ifmurl + ">Sorry your browser does not support inline frames.<a href="+ifmurl+" target='_blank'>Click here for Purchase Receipt</a> </iframe>";
                            Order or1 = db.Order.Find(orderid);
                            if (or1.OrderID > 0)
                            {
                                List <OrderedItems> oi = db.OrderedItems.Where(n => n.OrderID == orderid).ToList();
                                ViewBag.Items = oi;
                            }
                            string mybodyforloop = "";
                            string mybody        = "<html><head><link href='http://livingstud.com/css/bootstrap.css' type='text/css' rel='stylesheet' media='all'><link href='http://livingstud.com/css/style.css' type='text/css' rel='stylesheet' media='all'></head><body>Dear " + cd.CustFName + ",<br><br>Thank you for Shopping with us !<br> Your Order id is  " + orderid + ", Track Order http://livingstud.com/Orders/OrderTrack , <br>Please Continue Shopping with us http://www.Livingstud.com <br><div id='myinvoice'><div class='container'><div class='row'><div class='well col-xs-10 col-sm-10 col-md-6 col-xs-offset-1 col-sm-offset-1 col-md-offset-3'><div class='row'><center><h1>Receipt</h1></center><div class='col-xs-6 col-sm-6 col-md-6'><address><h4>Livingstud.com</h4>Email : [email protected]<br><abbr title='Phone'>P:</abbr> +918097471959</address></div><div class='col-xs-6 col-sm-6 col-md-6 text-right'><p><em>order Date: " + or1.InsertDate + "</em></p><p><em>Receipt #: " + orderid + "</em></p></div></div><div class='row'><div class='text-center'></div><table class='table table-hover'><thead><tr><th>Product</th><th>Qty</th><th class='text-center'>Price</th><th class='text-center'>Total</th></tr></thead><tbody>";
                            foreach (var items in ViewBag.Items)
                            {
                                mybodyforloop += mybodyforloop + "<tr><td class='col-md-9'><em>" + items.ProductName + "</em></td><td class='col-md-1' style='text-align: center'> " + items.ProductQuantity + " </td><td class='col-md-1 text-center'>₹ " + items.ProductPrice + "</td><td class='col-md-1 text-center'>₹ " + items.ProductPrice + "</td></tr>";
                            }
                            mybody          = mybody + mybodyforloop + "<tr><td></td><td></td><td class='text-right'><h4><strong>Total: </strong></h4></td><td class='text-center text-danger'><h4><strong>₹ " + or1.PaymentAmount + "</strong></h4></td></tr></tbody></table></div><div class='row'><div class='text-center'><h1>Delivery Details</h1></div><table class='table table-hover'><thead><tr><th>Contact Details</th></tr></thead><tbody><tr><td class='col-md-9'><em>" + or1.ContactFName + "</em><em>" + or1.ContactLName + "</em><em>" + or1.Phone + "</em><em>, " + cd.CustEmail + "</em></td></tr></tbody></table><table class='table table-hover'><thead><tr><th>Address</th></tr></thead><tbody><tr><td class='col-md-9'><em>" + or1.Address1 + "<br />" + or1.Address2 + "</em></td></tr></tbody></table></div></div></div></div></div></body></html>";
                            mail.Body       = mybody;
                            mail.IsBodyHtml = true;
                            //  mail.Attachments.Add(new Attachment("C:\\file.zip"));
                            using (SmtpClient smtp = new SmtpClient())//465 //587
                            {
                                smtp.EnableSsl             = true;
                                smtp.UseDefaultCredentials = false;
                                smtp.Credentials           = new NetworkCredential("*****@*****.**", "nayananm291193");
                                smtp.Host           = "smtp.gmail.com";
                                smtp.Port           = 587;
                                smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                                smtp.Send(mail);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }
            OrderLog ol = new OrderLog();

            ol.OID        = orderid;
            ol.CustId     = Session["CustId"].ToString();
            ol.Status     = "Order Placed";
            ol.InsertDate = DateTime.Now;
            ol.Owner      = "Vishu";
            db.OrderLogs.Add(ol);
            db.SaveChanges();
            return(orderid);
        }
        public CreateOrder CreateOrder()
        {
            HttpContextBase context  = (HttpContextBase)Request.Properties["MS_HttpContext"];
            HttpRequestBase request  = context.Request;
            string          jsonText = request["data"];


            CreateOrder   createOrder   = new CreateOrder();
            GoodOrderView goodOrderView = JsonConvert.DeserializeObject <GoodOrderView>(jsonText);
            string        payway        = request["payway"];
            //string jifen = request["jifen"];
            string liuyan = request["liuyan"];

            int?           userID         = null;
            Authentication authentication = new Authentication(request);

            if (string.IsNullOrEmpty(authentication.state))
            {
                userID = authentication.userID;
            }

            bool baoyou = false;
            OrderDetailsModel orderDetailsModel = new OrderDetailsModel();
            Order             order             = new Order();

            using (Entity entity = new Entity())
            {
                foreach (var goodCartView in goodOrderView.GoodCartViewList)
                {
                    int goodChildID = goodCartView.goodChildID;
                    int num         = goodCartView.num;
                    var goodChild   = entity.GoodChild.Include("Good").Where(o => o.GoodChildID == goodChildID && o.State == 1).FirstOrDefault();
                    if (goodChild == null)
                    {
                        createOrder.error = "商品不存在或者已经下架";
                        return(createOrder);
                    }
                    if (goodChild.Repertory == 0)
                    {
                        createOrder.error = "商品库存不够";
                        return(createOrder);
                    }
                    if ((goodChild.Good.State & 32) > 0)
                    {
                        baoyou = true;
                    }
                    order.Num += num;
                    orderDetailsModel.OrderDetailModelList.Add(new OrderDetailModel()
                    {
                        GoodID        = goodChild.Good.GoodID,
                        Title         = goodChild.Good.Title,
                        SubTitle      = goodChild.Good.SubTitle,
                        RealPrice     = goodChild.Good.RealPrice,
                        GoodChildID   = goodChild.GoodChildID,
                        Specification = goodChild.Specification,
                        AddPrice      = goodChild.AddPrice,
                        Image         = goodChild.Image,
                        num           = num
                    });
                    if (string.IsNullOrEmpty(order.Image))
                    {
                        order.Image = goodChild.Image;
                    }
                    if (order.GoodID == 0)
                    {
                        order.GoodID = goodChild.Good.GoodID;
                    }
                    if (string.IsNullOrEmpty(order.Title))
                    {
                        order.Title = goodChild.Good.Title;
                    }
                    if (userID != null)
                    {
                        var t = entity.GoodCart.Where(o => o.UserID == userID && o.GoodChildID == goodChildID).FirstOrDefault();
                        if (t != null)
                        {
                            entity.GoodCart.Remove(t);
                        }
                    }
                }


                order.OrderID                = DateTime.Now.ToString("yyMMddhhmmssfff") + new Random().Next(100, 1000).ToString();
                order.UserID                 = userID;
                order.State                  = 1;
                order.Detail                 = JsonConvert.SerializeObject(orderDetailsModel);
                order.Remark1                = liuyan;
                order.CreateTime             = DateTime.Now;
                order.UpdateTime             = DateTime.Now;
                order.LogisticsAddress       = request["dizhi"];
                order.LogisticsTel           = request["Tel"];
                order.LogisticsPerson        = request["shouhuoren"];
                order.OrderExtend            = new OrderExtend();
                order.OrderExtend.TotalPrice = orderDetailsModel.OrderDetailModelList.Sum(o => (o.RealPrice + o.AddPrice) * o.num);


                order.OrderExtend.DiscountPrice     = 0;
                order.OrderExtend.LogisticsPrice    = 0;
                order.OrderExtend.PaymentPrice      = 0;
                order.OrderExtend.ThirdPartyPayment = payway;


                WholeFieldActivity wholeFieldActivity = entity.WholeFieldActivity.Where(o => o.Type == 0).FirstOrDefault();
                if (wholeFieldActivity != null)
                {
                    if (order.OrderExtend.TotalPrice >= wholeFieldActivity.FillPrice)
                    {
                        if (wholeFieldActivity.DiscountPrice != null)
                        {
                            order.OrderExtend.DiscountPrice = wholeFieldActivity.DiscountPrice.Value;
                        }
                    }
                }
                order.OrderExtend.PaymentPrice = order.OrderExtend.TotalPrice - order.OrderExtend.DiscountPrice;
                if (!baoyou)
                {
                    order.OrderExtend.LogisticsPrice = Convert.ToInt32(ConfigurationManager.AppSettings["LogisticsPrice"]);
                    wholeFieldActivity = entity.WholeFieldActivity.Where(o => o.Type == 1).FirstOrDefault();
                    if (wholeFieldActivity != null)
                    {
                        if (order.OrderExtend.PaymentPrice >= wholeFieldActivity.FillPrice)
                        {
                            order.OrderExtend.LogisticsPrice = 0;
                        }
                    }
                }

                order.OrderExtend.PaymentPrice = order.OrderExtend.TotalPrice - order.OrderExtend.DiscountPrice + order.OrderExtend.LogisticsPrice;
                //if (jifen == "true" && !string.IsNullOrEmpty(authentication.state))
                //{
                //    var user = entity.User.Find(authentication.userID);
                //    order.OrderExtend.UseIntegral = user.UserExtend.Integral;
                //    order.OrderExtend.PaymentPrice -= (order.OrderExtend.UseIntegral / 100);
                //}

                //order.OrderExtend.GainIntegral = Convert.ToInt32(order.OrderExtend.TotalPrice - order.OrderExtend.DiscountPrice + order.OrderExtend.LogisticsPrice);

                OrderLog orderLog = new OrderLog();
                orderLog.State      = order.State;
                orderLog.CreateTime = DateTime.Now;
                orderLog.UserId     = order.UserID;
                orderLog.Mark       = "用户下单";
                order.OrderLog.Add(orderLog);
                entity.Order.Add(order);

                entity.SaveChanges();
            }
            string subject = "分享";
            string body    = "";

            foreach (var v in orderDetailsModel.OrderDetailModelList)
            {
                body += v.Title + " ";
            }
            body = body.Trim();

            createOrder.orderid = order.OrderID;
            createOrder.subject = subject;
            createOrder.body    = body;
            createOrder.fee     = order.OrderExtend.PaymentPrice.ToString("#0.00");
            return(createOrder);
        }
Ejemplo n.º 6
0
        public void CreatedScheduling(Sender sender, SaveCreatedSchedulingArgs args)
        {
            try
            {
                using (ObjectProxy op = new ObjectProxy(true))
                {
                    #region 部件工序
                    if (args.OrderWorkFlows != null)
                    {
                        foreach (OrderWorkFlow workflow in args.OrderWorkFlows)
                        {
                            OrderWorkFlow ow = new OrderWorkFlow();
                            ow.WorkingID = workflow.WorkingID;
                            if (op.LoadOrderWorkFlowByWorkingID(ow) == 0)
                            {
                                op.InsertOrderWorkFlow(workflow);
                            }
                            else
                            {
                                op.UpdateOrderWorkFlowByWorkingID(workflow);
                            }
                        }
                    }
                    #endregion

                    #region 排产计划
                    if (args.OrderSchedulings != null)
                    {
                        foreach (OrderScheduling item in args.OrderSchedulings)
                        {
                            OrderScheduling subobj = new OrderScheduling();
                            subobj.MadeID = item.MadeID;
                            if (op.LoadOrderSchedulingByMadeID(subobj) == 0)
                            {
                                item.Created    = DateTime.Now;
                                item.CreatedBy  = sender.UserCode + "." + sender.UserName;
                                item.Modified   = DateTime.Now;
                                item.ModifiedBy = sender.UserCode + "." + sender.UserName;
                                op.InsertOrderScheduling(item);
                            }
                            else
                            {
                                item.Modified   = DateTime.Now;
                                item.ModifiedBy = sender.UserCode + "." + sender.UserName;
                                op.UpdateOrderSchedulingByMadeID(item);
                            }
                        }
                    }
                    //工作车间生产计划
                    if (args.WorkCenterSchedulings != null)
                    {
                        foreach (WorkCenterScheduling item in args.WorkCenterSchedulings)
                        {
                            WorkCenterScheduling wcs = new WorkCenterScheduling();
                            wcs.WorkID = item.WorkID;
                            if (op.LoadWorkCenterSchedulingByWorkID(wcs) == 0)
                            {
                                item.Created    = DateTime.Now;
                                item.CreatedBy  = sender.UserCode + "." + sender.UserName;
                                item.Modified   = DateTime.Now;
                                item.ModifiedBy = sender.UserCode + "." + sender.UserName;
                                op.InsertWorkCenterScheduling(item);
                            }
                            else
                            {
                                item.Modified   = DateTime.Now;
                                item.ModifiedBy = sender.UserCode + "." + sender.UserName;
                                op.UpdateWorkCenterSchedulingByWorkID(item);
                            }
                        }
                    }
                    #endregion

                    #region 包装数据
                    if (args.PackageDetails != null)
                    {
                        foreach (PackageDetail item in args.PackageDetails)
                        {
                            PackageDetail subobj = new PackageDetail();
                            subobj.DetailID = item.DetailID;
                            if (op.LoadPackageDetailByDetailID(subobj) == 0)
                            {
                                item.Created    = DateTime.Now;
                                item.CreatedBy  = string.Format("{0}.{1}", sender.UserCode, sender.UserName);
                                item.Modified   = DateTime.Now;
                                item.ModifiedBy = string.Format("{0}.{1}", sender.UserCode, sender.UserName);
                                op.InsertPackageDetail(item);
                            }
                            else
                            {
                                item.Modified   = DateTime.Now;
                                item.ModifiedBy = string.Format("{0}.{1}", sender.UserCode, sender.UserName);
                                op.UpdatePackageDetailByDetailID(item);
                            }
                        }
                    }
                    #endregion

                    #region 修改柜体状态
                    List <Guid> OrderIDs = new List <Guid>();
                    if (args.CabinetIDs != null)
                    {
                        foreach (Guid CabinetID in args.CabinetIDs)
                        {
                            Order2Cabinet cabinet = new Order2Cabinet();
                            cabinet.CabinetID = CabinetID;
                            if (op.LoadOrder2CabinetByCabinetID(cabinet) != 0)
                            {
                                if (!OrderIDs.Contains(cabinet.OrderID))
                                {
                                    OrderIDs.Add(cabinet.OrderID);
                                }
                                Order order = new Order();
                                order.OrderID = cabinet.OrderID;
                                if (op.LoadOrder(order) != 0)
                                {
                                    //订单日志
                                    OrderLog log = new OrderLog();
                                    log.LogID     = Guid.NewGuid();
                                    log.OrderID   = order.OrderID;
                                    log.LogType   = "订单排产";
                                    log.Remark    = "完成排产";
                                    log.Created   = DateTime.Now;
                                    log.CreatedBy = sender.UserCode + "." + sender.UserName;
                                    op.InsertOrderLog(log);

                                    //流程步骤
                                    //OrderTask ot = new OrderTask();
                                    //ot.Action = "排产完成,待订单优化";
                                    //ot.CurrentStep = "订单排产";
                                    //ot.ActionRemarksType = "订单系统操作";
                                    //ot.ActionRemarks = "排产完成,待订单优化";
                                    //ot.Resource = "订单排产组";
                                    //ot.NextResources = "订单优化组";
                                    //ot.NextStep = "待生产优化";

                                    cabinet.BattchCode    = args.BattchCode;
                                    cabinet.CabinetStatus = "M";//待生产
                                    op.UpdateOrder2CabinetByCabinetID(cabinet);

                                    SaveOrderArgs orderargs = new SaveOrderArgs();
                                    orderargs.Order = order;
                                    //orderargs.OrderTask = ot;
                                    //orderargs.Order2Cabinets = new List<Order2Cabinet>() { cabinet };
                                    //this.SubmitTask(op, sender, orderargs);
                                }
                            }
                        }

                        foreach (Guid orderID in OrderIDs)
                        {
                            //op.UpdateMadeOrderStatus(orderID);
                        }
                    }
                    #endregion

                    op.CommitTransaction();
                }
            }
            catch (Exception ex)
            {
                PLogger.LogError(ex);
                throw ex;
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// 微信支付异步通知
        /// </summary>
        /// <returns></returns>
        public IActionResult notify()
        {
            XTrace.WriteLine("微信支付异步通知开始:");
            try
            {
                ResponseHandler resHandler = new ResponseHandler(null);

                string return_code = resHandler.GetParameter("return_code");
                string return_msg  = resHandler.GetParameter("return_msg");

                //配置
                Core.Config cfg        = Core.Config.GetSystemConfig();
                string      appId      = cfg.WXAppId;     // ConfigurationManager.AppSettings["WeixinAppId"];
                string      appSecrect = cfg.WXAppSecret; // ConfigurationManager.AppSettings["WeixinAppSecrect"];
                string      wxmchId    = cfg.MCHId;       // ConfigurationManager.AppSettings["WeixinMCHId"];
                string      wxmchKey   = cfg.MCHKey;      // ConfigurationManager.AppSettings["WeixinMCHKey"];

                TenPayV3Info TenPayV3Info = new TenPayV3Info(appId, appSecrect, wxmchId, wxmchKey, Utils.GetServerUrl() + "/wxpayment/notify");

                string res = null;

                resHandler.SetKey(TenPayV3Info.Key);
                //验证请求是否从微信发过来(安全)
                if (resHandler.IsTenpaySign() && return_code.ToUpper() == "SUCCESS")
                {
                    res = "success";                                               //正确的订单处理
                                                                                   //直到这里,才能认为交易真正成功了,可以进行数据库操作,但是别忘了返回规定格式的消息!
                    string out_trade_no = resHandler.GetParameter("out_trade_no"); //商户订单号
                    XTrace.WriteLine("微信异步通知订单号:" + out_trade_no + ";" + JsonConvert.SerializeObject(resHandler));

                    OnlinePayOrder payOrder = OnlinePayOrder.Find(OnlinePayOrder._.PayOrderNum == out_trade_no);
                    if (payOrder == null)
                    {
                        XTrace.WriteLine($"支付成功,但是支付订单不存在:{out_trade_no}");
                        res = "wrong";//错误的订单处理
                    }
                    else
                    {
                        if (payOrder.PaymentStatus == Utils.PaymentState[0])
                        {
                            //更新支付订单
                            payOrder.PaymentStatus = Utils.PaymentState[1];
                            payOrder.ReceiveTime   = DateTime.Now;
                            payOrder.IsOK          = 1;
                            payOrder.Update();

                            //获取订单
                            Order order = Order.Find(Order._.OrderNum == payOrder.OrderNum);
                            if (order != null)
                            {
                                order.PaymentStatus = Utils.PaymentState[1];
                                order.PayType       = "微信支付";
                                if (order.MyType == (int)Utils.MyType.分销商认证)
                                {
                                    order.OrderStatus = Utils.OrdersState[2];
                                }
                                order.Update();
                                //如果是属于升级会员的,那要修改会员状态
                                if (order.MyType == (int)Utils.MyType.分销商认证 && order.OrderType > 0)
                                {
                                    Member he = Member.FindById(order.UId);
                                    if (he.RoleId != order.OrderType)
                                    {
                                        he.RoleId          = order.OrderType;
                                        he.IsVerifySellers = 1;
                                        he.Update();
                                    }
                                }
                                //写入订单记录
                                OrderLog log = new OrderLog();
                                log.AddTime  = DateTime.Now;
                                log.OrderId  = order.Id;
                                log.OrderNum = order.OrderNum;
                                log.UId      = order.UId;
                                log.Actions  = "微信支付成功;订单号:" + order.OrderNum + ";金额:" + order.TotalPay.ToString("N2");
                                log.Insert();
                            }
                        }
                    }
                }
                else
                {
                    res = "wrong";//错误的订单处理
                }

                #region 记录日志
                XTrace.WriteLine($"微信支付回调处理结果:{res}");
                #endregion

                string xml = string.Format(@"<xml>
<return_code><![CDATA[{0}]]></return_code>
<return_msg><![CDATA[{1}]]></return_msg>
</xml>", return_code, return_msg);
                return(Content(xml, "text/xml"));
            }
            catch (Exception ex)
            {
                new WeixinException(ex.Message, ex);
                throw;
            }
        }
Ejemplo n.º 8
0
 public void SendOrderLog(OrderLog user)
 {
     base.transactionType = MessageQueueTransactionType.Single;
     base.Send(user);
 }
Ejemplo n.º 9
0
        public ReJson DoPayOrder(string ordernum, string random = "", string timeStamp = "", string signature = "")
        {
            //获取订单
            Order entity = Order.Find(Order._.OrderNum == ordernum);

            if (entity == null)
            {
                //reJson.code = 40000;
                //reJson.message = "系统找不到本订单!";
                //return reJson;

                return(new ReJson(40000, "系统找不到本订单!"));
            }
            //判断订单状态
            if (entity.OrderStatus == Utils.OrdersState[3])
            {
                //reJson.code = 40000;
                //reJson.message = "已完成订单不允许支付!";
                //return reJson;
                return(new ReJson(40000, "已完成订单不允许支付!"));
            }
            if (entity.PaymentStatus != Utils.PaymentState[0])
            {
                //reJson.code = 40000;
                //reJson.message = "当前订单支付状态不允许支付!";
                //return reJson;
                return(new ReJson(40000, "当前订单支付状态不允许支付!"));
            }
            //获取用户并判断是否是已经注册用户
            Member my = Member.FindById(entity.UId);

            if (my == null || string.IsNullOrEmpty(my.WeixinAppOpenId))
            {
                //reJson.code = 40000;
                //reJson.message = "用户状态错误,无法使用本功能!";
                //return reJson;
                return(new ReJson(40000, "用户状态错误,无法使用本功能!"));
            }
            //开始生成支付订单
            OnlinePayOrder model = new OnlinePayOrder();

            model.OrderId       = entity.Id;
            model.OrderNum      = entity.OrderNum;
            model.PayId         = 1;
            model.PaymentNotes  = "微信支付";
            model.PaymentStatus = Utils.PaymentState[0];
            model.PayOrderNum   = Utils.GetOrderNum();//在线支付订单的订单号
            model.PayType       = "微信支付";
            model.TotalPrice    = entity.TotalPay;
            model.TotalQty      = entity.TotalQty;
            model.UId           = entity.UId;
            model.IP            = Utils.GetIP();
            model.IsOK          = 0;
            model.AddTime       = DateTime.Now;
            model.Insert();

            //写入日志
            OrderLog log = new OrderLog();

            log.AddTime  = DateTime.Now;
            log.OrderId  = entity.Id;
            log.OrderNum = entity.OrderNum;
            log.UId      = entity.UId;
            log.Actions  = "用户使用微信支付;支付订单号:" + model.PayOrderNum;
            log.Insert();

            Core.Config cfg        = Core.Config.GetSystemConfig();
            string      appId      = cfg.WXAppId;     // ConfigurationManager.AppSettings["WeixinAppId"];
            string      appSecrect = cfg.WXAppSecret; // ConfigurationManager.AppSettings["WeixinAppSecrect"];
            string      wxmchId    = cfg.MCHId;       // ConfigurationManager.AppSettings["WeixinMCHId"];
            string      wxmchKey   = cfg.MCHKey;      // ConfigurationManager.AppSettings["WeixinMCHKey"];



            TenPayV3Info TenPayV3Info = new TenPayV3Info(appId, appSecrect, wxmchId, wxmchKey, Utils.GetServerUrl() + "/wxpayment/notify", Utils.GetServerUrl() + "/wxpayment/notify");

            TenPayV3Info.TenPayV3Notify = Utils.GetServerUrl() + "/wxpayment/notify";
            XTrace.WriteLine("微信支付异步通知地址:" + TenPayV3Info.TenPayV3Notify);
            //创建支付应答对象
            RequestHandler packageReqHandler = new RequestHandler(null);
            var            sp_billno         = DateTime.Now.ToString("HHmmss") + TenPayV3Util.BuildRandomStr(26);//最多32位
            var            nonceStr          = TenPayV3Util.GetNoncestr();
            string         rtimeStamp        = Utils.GetTimeStamp();

            //创建请求统一订单接口参数
            var xmlDataInfo = new TenPayV3UnifiedorderRequestData(TenPayV3Info.AppId, TenPayV3Info.MchId, entity.Title, model.PayOrderNum, (int)(entity.TotalPay * 100), Utils.GetIP(), TenPayV3Info.TenPayV3Notify, Senparc.Weixin.TenPay.TenPayV3Type.JSAPI, my.WeixinAppOpenId, TenPayV3Info.Key, nonceStr);

            //返回给微信的请求
            RequestHandler res = new RequestHandler(null);

            try
            {
                //调用统一订单接口
                var result = TenPayV3.Unifiedorder(xmlDataInfo);
                XTrace.WriteLine("微信支付统一下单返回:" + JsonConvert.SerializeObject(result));

                if (result.return_code == "FAIL")
                {
                    //reJson.code = 40005;
                    //reJson.message = result.return_msg;
                    //return reJson;
                    return(new ReJson(40005, result.return_msg));
                }
                string nativeReqSign = res.CreateMd5Sign("key", TenPayV3Info.Key);
                //https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_7&index=3
                //paySign = MD5(appId=wxd678efh567hg6787&nonceStr=5K8264ILTKCH16CQ2502SI8ZNMTM67VS&package=prepay_id=wx2017033010242291fcfe0db70013231072&signType=MD5&timeStamp=1490840662&key=qazwsxedcrfvtgbyhnujmikolp111111)
                string paySign = Utils.MD5($"appId={TenPayV3Info.AppId}&nonceStr={nonceStr}&package=prepay_id={result.prepay_id}&signType=MD5&timeStamp={rtimeStamp}&key={TenPayV3Info.Key}").ToUpper();

                string package = $"prepay_id={result.prepay_id}";

                dynamic detail = new { timeStamp = rtimeStamp, nonceStr = nonceStr, package = package, signType = "MD5", paySign = paySign };

                //reJson.code = 0;
                //reJson.message = "下单成功!";
                //reJson.detail = detail;
                //return reJson;
                return(new ReJson(40000, "下单成功!", detail));
            }
            catch (Exception ex)
            {
                res.SetParameter("return_code", "FAIL");
                res.SetParameter("return_msg", "统一下单失败");
                XTrace.WriteLine($"统一下单失败:{ex.Message}");

                //reJson.code = 40005;
                //reJson.message = "统一下单失败,请联系管理员!";
                return(new ReJson(40005, "统一下单失败,请联系管理员!"));
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Gets a customer with HAL formatted hypermedia.
        /// </summary>
        public HttpResponseMessage Get(HttpRequestMessage request)
        {
            //this will be our embedded resource.
            var customer = new Customer
            {
                Name  = "Joe Blow",
                Title = "President"
            };

            //this will be our root resource
            var orderLog = new OrderLog
            {
                NumberOfItemsPurchase = 2,
                OrderDate             = new DateTime(1999, 12, 31),
                TotalAmount           = 43.23m
            };

            //Create a builder so we can build our HAL document that will get serialized.
            var bldr = new HalDocumentBuilder(orderLog);

            //Add all of our links to our HAL document.
            //Note: The use of relative paths for brevity.
            bldr.IncludeRelationWithSingleLink(HalRelation.CreateSelfRelation(), new HalLink("/orderlogs/123"));
            bldr.IncludeRelationWithMultipleLinks(new HalRelation("archive"),
                                                  new[]
            {
                new HalLink("/orderlogs/archive/")
                {
                    Profile = "http://profiles.mydomain.com/standard/"
                },
                new HalLink("m/orderlogs/archive")
                {
                    Profile = "http://profiles.mydomain.com/mobile/"
                }
            });

            //Create a builder to build our Customer embedded resource.
            var embeddedBldr =
                new HalEmbeddedResourceBuilder(customer);

            //Add all of our HAL links that will be on the Customer embedded resource.
            embeddedBldr
            .IncludeRelationWithSingleLink(HalRelation.CreateSelfRelation(),
                                           new HalLink("/customer/112")
            {
                Profile =
                    "https://profiles.mydomain.com/customer/"
            })
            .IncludeRelationWithMultipleLinks(new HalRelation("tags"),
                                              new[] { new HalLink("/tags/123"), new HalLink("tags/345") });

            //Create an embedded resource with the links we added through the builder.
            var embeddedResource = new HalEmbeddedResource(embeddedBldr);

            //Add our single embedded resource to our HAL document builder.
            bldr.IncludeEmbeddedWithSingleResource(new HalRelation("customer"), embeddedResource);


            var embeds = new List <HalEmbeddedResource>
            {
                new HalEmbeddedResource(embeddedBldr),
                new HalEmbeddedResource(embeddedBldr)
            };

            //Add a relation that has 2 embedded resources.
            bldr.IncludeEmbeddedWithMultipleResources(new HalRelation("contrived"),
                                                      embeds);

            //Build our HAL document.
            HalDocument document = bldr.Build();

            //Create a response that will have our HAL document. We use the appropriate media type on the response.
            //The HalDocument we built will get serialized into HAL formatted JSON since we added the HalJsonMediaTypeFormatter
            //to the application's formatters collection during application start up in the WebApiConfig.cs file.
            var response = request.CreateResponse(HttpStatusCode.OK, document,
                                                  HalJsonMediaTypeFormatter.SupportedMediaType);

            return(response);
        }
        public ActionResult OrderConfirm(Order obj, string CouponKey)
        {
            List <Cart> cartList = repoRakibCart.GetCartByUserId(obj.User_Id).ToList();

            if (cartList.Count == 0)
            {
                return(RedirectToAction("Index", "Home"));
            }
            float p = 0;

            if (CouponKey != "")
            {
                Coupon c = repoRakibCoupon.GetPercentage(CouponKey);
                obj.Coupon_Id = c.Id;
                p             = (float)c.Percentage;
            }

            repoRakibOrder.Insert(obj);
            repoRakibOrder.EContext.SaveChanges();

            var lastOrder = repoRakibOrder.GetLastEntryOfUser(obj.User_Id);

            //var cartList = repoRakibCart.GetCartByUserId(obj.User_Id);
            foreach (var item in cartList)
            {
                OrderData orderData = new OrderData();
                orderData.Book_Id         = item.Book_Id;
                orderData.Order_Id        = lastOrder.Id;
                orderData.QuantityOrdered = item.QuantityOrdered;
                orderData.Subtotal        = item.QuantityOrdered * item.Book.Price;

                if (CouponKey != "")
                {
                    orderData.ActualPrice = Math.Ceiling(orderData.Subtotal - ((orderData.Subtotal * p) / 100));
                }
                else
                {
                    orderData.ActualPrice = Math.Ceiling(orderData.Subtotal);
                }
                repoRakibOrderData.Insert(orderData);
                repoRakibOrderData.EContext.SaveChanges();

                Stock s = repoRakibStock.GetStockByBookId(item.Book_Id);
                s.OrderStock -= item.QuantityOrdered;
                repoRakibStock.EContext.Entry(s).State = EntityState.Modified;
                repoRakibStock.EContext.SaveChanges();
            }

            repoRakibCart.RemoveRange(cartList);
            repoRakibCart.EContext.SaveChanges();
            OrderLog o = new OrderLog();

            o.AddedDate  = DateTime.Now;
            o.LogDetails = "Pending for comfirmation";
            o.Order_Id   = lastOrder.Id;

            repoRakibOrderLog.Insert(o);
            repoRakibOrderLog.EContext.SaveChanges();

            return(RedirectToAction("OrderS"));
        }
Ejemplo n.º 12
0
        public string AlipayNotify()
        {
            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];
            HttpRequestBase request = context.Request;
            SortedDictionary <string, string> sPara = GetRequestPost();

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

                if (verifyResult)//验证成功
                {
                    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
                    //请在这里加上商户的业务逻辑程序代码


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

                    //商户订单号
                    string out_trade_no = request["out_trade_no"];

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

                    //交易状态
                    string trade_status = request["trade_status"];


                    if (request["trade_status"] == "TRADE_FINISHED")
                    {
                        //判断该笔订单是否在商户网站中已经做过处理
                        //如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序
                        //如果有做过处理,不执行商户的业务程序

                        //注意:
                        //退款日期超过可退款期限后(如三个月可退款),支付宝系统发送该交易状态通知
                        //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的

                        using (Entity entity = new Entity())
                        {
                            Order order = entity.Order.Find(out_trade_no);
                            if ((order.State & 2) == 0)
                            {
                                order.State |= 2;
                                OrderDetailsModel orderDetailsModel = Newtonsoft.Json.JsonConvert.DeserializeObject <OrderDetailsModel>(order.Detail);
                                foreach (var v in orderDetailsModel.OrderDetailModelList)
                                {
                                    entity.Good.Find(v.GoodID).SalesVolume++;
                                    entity.GoodChild.Find(v.GoodChildID).SalesVolume++;
                                }
                                OrderLog orderLog = new OrderLog();
                                orderLog.OrderID    = order.OrderID;
                                orderLog.State      = 2;
                                orderLog.CreateTime = DateTime.Now;
                                orderLog.Mark       = "支付宝返回成功";
                                entity.OrderLog.Add(orderLog);
                                order.OrderExtend.ThirdPartyPaymentNumber = trade_no;

                                entity.SaveChanges();
                            }
                        }
                    }
                    else if (request["trade_status"] == "TRADE_SUCCESS")
                    {
                        //判断该笔订单是否在商户网站中已经做过处理
                        //如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序
                        //如果有做过处理,不执行商户的业务程序

                        //注意:
                        //付款完成后,支付宝系统发送该交易状态通知
                        //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的

                        using (Entity entity = new Entity())
                        {
                            Order order = entity.Order.Find(out_trade_no);
                            if ((order.State & 2) == 0)
                            {
                                order.State |= 2;
                                OrderDetailsModel orderDetailsModel = Newtonsoft.Json.JsonConvert.DeserializeObject <OrderDetailsModel>(order.Detail);
                                foreach (var v in orderDetailsModel.OrderDetailModelList)
                                {
                                    entity.Good.Find(v.GoodID).SalesVolume++;
                                    entity.GoodChild.Find(v.GoodChildID).SalesVolume++;
                                }
                                OrderLog orderLog = new OrderLog();
                                orderLog.OrderID    = order.OrderID;
                                orderLog.State      = 2;
                                orderLog.CreateTime = DateTime.Now;
                                orderLog.Mark       = "支付宝返回成功";
                                entity.OrderLog.Add(orderLog);
                                order.OrderExtend.ThirdPartyPaymentNumber = trade_no;
                                entity.SaveChanges();
                                ThreadPool.QueueUserWorkItem(delegate(object a)
                                {
                                    string tt       = @"有用户已经支付订单 " + order.OrderID + "金额 " + order.OrderExtend.PaymentPrice + " 请尽快发货";
                                    UserSMS userSMS = new UserSMS()
                                    {
                                        Tel = ConfigurationManager.AppSettings["SMSAdmin"]
                                    };
                                    Random random        = new Random();
                                    userSMS.SerialNumber = DateTime.Now.ToString("yyyyMMddhhmmssfff" + random.Next(100, 999).ToString());
                                    string bb            = SMS.sendSMS(userSMS.Tel, tt, userSMS.SerialNumber);
                                });
                            }
                        }
                    }
                    else
                    {
                        OrderLog orderLog = new OrderLog();
                        orderLog.OrderID = out_trade_no;

                        orderLog.CreateTime = DateTime.Now;
                        orderLog.Mark       = "支付宝返回" + request["trade_status"];

                        using (Entity entity = new Entity())
                        {
                            entity.OrderLog.Add(orderLog);
                            entity.SaveChanges();
                        }
                    }

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

                    return("success");  //请不要修改或删除

                    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
                }
                else//验证失败
                {
                    return("fail");
                }
            }
            else
            {
                return("无通知参数");
            }
        }
        protected void DetailsView1_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)
        {
            try
            {
                using (Entity entity = new Entity())
                {
                    var order = entity.Order.Find(DetailsView1.DataKey.Value.ToString());

                    var CheckBoxList_State = ((CheckBoxList)DetailsView1.FindControl("CheckBoxList_State"));
                    order.State = 0;
                    int fahuoTemp = order.State & 4;
                    foreach (ListItem item in CheckBoxList_State.Items)
                    {
                        if (item.Selected)
                        {
                            order.State = order.State | Convert.ToInt32(item.Value);
                        }
                    }

                    if (fahuoTemp == 0)
                    {
                        if ((order.State & 4) > 0)
                        {
                            OrderLog orderLog = new OrderLog();
                            orderLog.OrderID    = order.OrderID;
                            orderLog.State      = 2;
                            orderLog.CreateTime = DateTime.Now;
                            orderLog.Mark       = "卖家发货";
                            orderLog.UserId     = Convert.ToInt32(Session["userID"]);
                            entity.OrderLog.Add(orderLog);
                            if (order.UserID != null)
                            {
                                string text = string.Format("您的订单{0}已经发货", order.OrderID);
                                UserLetterBLL.Create(Convert.ToInt32(Session["userID"]), order.UserID.Value, text, 1 | 8);

                                ThreadPool.QueueUserWorkItem(delegate(object a)
                                {
                                    string tt = @"您的订单 " + order.OrderID + " 已经发货,不日则到。请注意查收您的订单 ";
                                    using (Entity entity1 = new Entity())
                                    {
                                        UserSMS userSMS = new UserSMS()
                                        {
                                            Tel = entity1.User.Find(order.UserID).Tel
                                        };

                                        string bb = SMS.sendSMS(userSMS.Tel, tt, userSMS.SerialNumber);
                                    }
                                });
                            }
                        }
                    }


                    var DropDownList1 = ((DropDownList)DetailsView1.FindControl("DropDownList1"));
                    order.LogisticsCompany = DropDownList1.SelectedValue;
                    if (e.NewValues["LogisticsNumber"] != null)
                    {
                        order.LogisticsNumber = e.NewValues["LogisticsNumber"].ToString();
                    }
                    order.UpdateTime = DateTime.Now;

                    entity.SaveChanges();

                    Response.Redirect("OrderDetail.aspx?OrderID=" + order.OrderID);
                }
            }
            catch (Exception exception)
            {
                string error = exception.GetErrorMessage().Replace("'", "\\'").Replace("\"", "\\\"").Replace("\r\n", "\\r\\n");
                ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", string.Format("<script>alert('{0}')</script>", error));
            }
        }