Example #1
0
        //public JsonResult CreateOrder(int fieldId, string startTime, string endTime, string note,
        //    double price, string paidType, string useDate)
        //{
        //    TimeSpan StartTime = TimeSpan.Parse(startTime);
        //    TimeSpan EndTime = TimeSpan.Parse(endTime);
        //    DateTime UseDate = DateTime.Parse(useDate);
        //    DateTime sTime = new DateTime(UseDate.Year, UseDate.Month, UseDate.Day, StartTime.Hours,
        //        StartTime.Minutes, StartTime.Seconds);
        //    DateTime eTime = new DateTime(UseDate.Year, UseDate.Month, UseDate.Day, EndTime.Hours,
        //        EndTime.Minutes, EndTime.Seconds);
        //    var userId = User.Identity.GetUserId();
        //    var _orderService = this.Service<IOrderService>();
        //    int pType = Int32.Parse(paidType);
        //    Order result = _orderService.CreateOrder(userId, fieldId, sTime, eTime, note, price, pType);
        //    if (result != null)
        //    {
        //        return Json(new
        //        {
        //            success = true
        //        });
        //    }
        //    else
        //    {
        //        return Json(new
        //        {
        //            success = false
        //        });
        //    }
        //}

        public ActionResult PayOnlineNow(object sender, EventArgs e, OrderViewModel model)
        {
            var _orderService = this.Service <IOrderService>();
            var order         = new Order();

            if (String.IsNullOrEmpty(model.OrderCode))
            {
                return(RedirectToAction("PageNotFound", "Errors"));
            }
            else
            {
                order = _orderService.FirstOrDefaultActive(p => p.OrderCode == model.OrderCode);
                if (order != null)
                {
                    String transaction_info = "Thanh toan dat san";
                    String receiver         = "*****@*****.**";//Tài khoản nhận tiền
                    String return_url       = Url.Action("verifyOrder", "Order",
                                                         new { area = "", orderCode = order.OrderCode }, Request.Url.Scheme);
                    String cancel_url = "http://ssn.techeco.net/Order";
                    //String price = model.Price.ToString();
                    String      price = "2000";
                    NL_Checkout nl    = new NL_Checkout();
                    String      url;
                    url = nl.buildCheckoutUrl(return_url, cancel_url, receiver, transaction_info, order.OrderCode, price);

                    order.PaidType = (int)OrderPaidType.ChosePayOnline;
                    _orderService.Update(order);
                    return(Redirect(url));
                }
                else
                {
                    return(RedirectToAction("PageNotFound", "Errors"));
                }
            }
        }
 protected void Page_Load(object sender, EventArgs e)
 {
     try
     {
         String      return_url       = Request["return_url"];
         String      receiver         = Request["receiver"];
         String      transaction_info = Request["transaction_info"];
         String      order_code       = Request["order_code"];
         String      price            = Request["price"];
         String      payment_id       = Request["payment_id"];
         String      payment_type     = Request["payment_type"];
         String      error_text       = Request["error_text"];
         String      secure_code      = Request["secure_code"];
         NL_Checkout checkOut         = new NL_Checkout();
         bool        rs = checkOut.verifyPaymentUrl(transaction_info, order_code, price, payment_id, payment_type, error_text, secure_code);
         if (rs)
         {
             Response.Write("Thanh toán thành công !");
         }
         else
         {
             Response.Write("Thanh toán không thành công");
         }
     }
     catch (Exception ex) {
         Response.Write(ex.ToString());
     }
 }
    public bool ValidateCheckout()
    {
        string transaction_info = Request.QueryString["transaction_info"].ToSafetyString();
        string order_code       = Request.QueryString["order_code"].ToSafetyString();
        string payment_id       = Request.QueryString["payment_id"].ToSafetyString();
        string payment_type     = Request.QueryString["payment_type"].ToSafetyString();
        string secure_code      = Request.QueryString["secure_code"].ToSafetyString();
        string price            = Request.QueryString["price"].ToSafetyString();
        string error_text       = Request.QueryString["error_text"].ToSafetyString();

        NL_Checkout nl           = new NL_Checkout();
        bool        isCheckoutOk = nl.verifyPaymentUrl(transaction_info, order_code, price, payment_id, payment_type, error_text, secure_code);

        // (String transaction_info, String order_code, String price, String payment_id, String payment_type, String error_text, String secure_code)
        if (isCheckoutOk && error_text == string.Empty)
        {
            isCheckoutOk = true;
            ucMessage.ShowSuccess("Xin chúc mừng, đơn hàng đã được thanh toán thanh công. Chúng tôi sẽ giao hàng trong thời gian sớm nhất. <a href='OderDetail.aspx'>xem Đơn Hàng</a>");
        }
        else
        {
            isCheckoutOk = false;
            ucMessage.ShowError("Rất tiếc, đơn hàng chưa được thanh toán thanh công. Vui lòng kiểm tra lại hoặc <a href='OderDetail.aspx'>xem Đơn Hàng</a>");
        }

        return(isCheckoutOk);
    }
    protected void btcheckoder_Click(object sender, EventArgs e)
    {
        NL_Checkout nlcheckout = new NL_Checkout();

        nlcheckout.merchant_site_code = this.merchant_site_code;
        nlcheckout.secure_pass        = this.merchant_pass;
        string resultcheckorder = nlcheckout.Nl_checkoder(1, "1849", "1117603");


        XmlDocument dom = new XmlDocument();

        dom.LoadXml(resultcheckorder);
        XmlNodeList root = dom.DocumentElement.ChildNodes;

        if (root.Item(1).InnerText == "00")
        {
            string result = root.Item(0).InnerText + "|" + root.Item(1).InnerText + "|"
                            + root.Item(2).ChildNodes.Item(0).InnerText
                            + "|"
                            + root.Item(2).ChildNodes.Item(14).InnerText;

            texbox_result_checkoder.Text = result;
        }


        txtserverkt.Text = resultcheckorder;
    }
Example #5
0
    protected void Page_Load(object sender, EventArgs e)
    {
        NL_Checkout checkOut = new NL_Checkout();
        string      html     = "Bạn chưa đăng nhập !<br/>";

        html += "Để tiếp tục mua hàng vui lòng chọn ";
        //subtitle.InnerHtml = html;
        //Tổng cộng : <span style='color:red;' ></span> vnđ <br/> <small>Trình duyệt sẽ tự chuyển trong 3s nữa</small>";
    }
Example #6
0
 protected void btnSubmit_Click(object sender, EventArgs e)
 {
     String return_url       = "http://*****:*****@dotnet.vn";
     //Tài khoản nhận tiền
     String      price    = "100000";
     NL_Checkout nl       = new NL_Checkout();
     String      url; url = nl.buildCheckoutUrl(return_url, receiver, transaction_info, order_code, price);
     //Response.Redirect(url);
 }
    protected void btthanhtoan_Click(object sender, EventArgs e)
    {
        NL_Checkout nlcheckout = new NL_Checkout();

        nlcheckout.merchant_site_code = this.merchant_site_code;
        nlcheckout.secure_pass        = this.merchant_pass;

        string rs = nlcheckout.buildCheckoutUrlNew("http://hoannet.vn/success.aspx", this.receiver, "", txtOrderID.Text, txtPriceOrder.Text, "vnd", 1, 0, 0, 0, 0, "", "Truong Xuan Hoan*|*[email protected]*|*0986588099*|*18 Tam Trinh", "");

        Response.Write(rs);
        Response.Redirect(rs);
    }
Example #8
0
        public ActionResult verifyOrder(object sender, EventArgs e, string orderCode)
        {
            String      transaction_info = Request.QueryString["transaction_info"];
            String      order_code       = Request.QueryString["order_code"];
            String      payment_id       = Request.QueryString["payment_id"];
            String      payment_type     = Request.QueryString["payment_type"];
            String      secure_code      = Request.QueryString["secure_code"];
            String      price            = Request.QueryString["price"];
            String      error_text       = Request.QueryString["error_text"];
            NL_Checkout nl    = new NL_Checkout();
            bool        check = nl.verifyPaymentUrl(transaction_info, order_code, price, payment_id, payment_type, error_text, secure_code);

            if (check)
            {
                var _orderService = this.Service <IOrderService>();
                var order         = _orderService.FirstOrDefaultActive(p => p.OrderCode == orderCode);
                if (order != null)
                {
                    order.PaidType = (int)OrderPaidType.PaidOnline;
                    _orderService.Update(order);
                    var _userService = this.Service <IAspNetUserService>();
                    var userId       = User.Identity.GetUserId();
                    var user         = _userService.FirstOrDefaultActive(p => p.Id == userId);
                    if (user == null)
                    {
                        return(RedirectToAction("PageNotFound", "Errors"));
                    }
                    string subject = "[SSN] - Thông tin thanh toán";
                    string body    = "Hi <strong>" + user.FullName + "</strong>" +
                                     ",<br/><br/>Bạn đã thanh toán đơn đặt sân: " + order.OrderCode + " thành công" +
                                     "<br/><strong>Thông tin hóa đơn:</strong><ul> " +
                                     "<li> Tên sân: " + order.Field.Name + "</li>" +
                                     "<li> Tại địa điểm: " + order.Field.Place.Name + "</li>" +
                                     "<li> Thời gian: " + order.StartTime.ToString("HH:mm") + " - " +
                                     order.EndTime.ToString("HH:mm") + ", ngày " + order.StartTime.ToString("dd/MM/yyyy") + "</li>" +
                                     "<li> Giá tiền : " + order.Price.ToString("n0") + " đồng</li></ul>" +
                                     "<br/> Cảm ơn bạn đã sử dụng dịch vụ của SSN. Chúc bạn có những giờ phút thoải mái chơi thể thao!";
                    EmailSender.Send(Setting.CREDENTIAL_EMAIL, new string[] { order.PayerEmail }, null, null, subject, body, true);
                    var url = Url.Action("PaymentSuccessful", "Order",
                                         new { area = "", orderCode = order_code }, Request.Url.Scheme);
                    return(Redirect(url));
                }
                else
                {
                    return(RedirectToAction("PageNotFound", "Errors"));
                }
            }
            else
            {
                return(RedirectToAction("PaymentFail", "Order"));
            }
        }
Example #9
0
    protected void bt_naptien_Click(object sender, EventArgs e)
    {
        NL_Checkout nlcheckout = new NL_Checkout();

        nlcheckout.merchant_site_code = this.merchant_site_code;
        nlcheckout.secure_pass        = this.merchant_pass;

        var      rnd        = new Random(DateTime.Now.Millisecond);
        int      oderID     = rnd.Next(0, 3000);
        DateTime dtNow      = DateTime.Now;
        string   strOrderID = dtNow.Year.ToString() + dtNow.Month.ToString() + dtNow.Day.ToString() + dtNow.Hour.ToString() + dtNow.Minute.ToString() + dtNow.Second.ToString();

        string rs = nlcheckout.buildCheckoutUrlNew("http://localhost/success.aspx", this.receiver, "", strOrderID, txtPriceOrder.Text, "vnd", 1, 0, 0, 0, 0, "", "", "");

        Response.Write(rs);
        Response.Redirect(rs);
    }
Example #10
0
    protected void Page_Load(object sender, EventArgs e)
    {
        String      return_url       = Request["return_url"];
        String      receiver         = Request["receiver"];
        String      transaction_info = Request["transaction_info"];
        String      order_code       = Request["order_code"];
        String      price            = Request["price"];
        String      payment_id       = Request["payment_id"];
        String      payment_type     = Request["payment_type"];
        String      error_text       = Request["error_text"];
        String      secure_code      = Request["secure_code"];
        NL_Checkout checkOut         = new NL_Checkout();
        bool        rs = checkOut.verifyPaymentUrl(transaction_info, order_code, price, payment_id, payment_type, error_text, secure_code);

        subtitle.InnerHtml = "Đơn hàng " + order_code.ToString() + " đã xử lý thành công<br/> Tổng cộng : <span style='color:red;' >" + price.ToString() + "</span> vnđ <br/> <small>Trình duyệt sẽ tự chuyển trong 3s nữa</small>";
        //if (rs)
        //{
        //    title.InnerHtml = "Thanh toán thành công !";
        //}
        //else
        //{
        //    title.InnerHtml = "Thanh toán không thành công !";
        //}
    }
Example #11
0
    private void PaymentOnline()
    {
        string HoTen     = txtFullname.Value; //StaticData.ValidParameter(Request.QueryString["HoTen"].Trim());
        string DienThoai = txtPhone.Value;    //StaticData.ValidParameter(Request.QueryString["DienThoai"].Trim());
        string DiaChi    = txtNo.Text + "," + slProvince.SelectedItem.Text + "," + slCity.SelectedItem.Text;
        string GhiChu    = txtDesc.Value;     //StaticData.ValidParameter(Request.QueryString["GhiChu"].Trim());
        //string ID = Session["CurrentUser"] == null ? "" : Session["CurrentUser"].ToString();//StaticData.ValidParameter(Request.QueryString["ID"].Trim());
        //string tenMuaHang = txtHoTen.Value;
        //string sdtMuaHang = txtSoDienThoai.Value;

        double total = 0;

        cart = Session["CartSession"] as DataTable;
        foreach (DataRow dr in cart.Rows)
        {
            string    idProduct  = dr["idSanPham"].ToString();
            string    sqlProduct = "select * from tb_SanPham where idSanPham = '" + idProduct + "'";
            DataTable dataUser   = Connect.GetTable(sqlProduct);

            string str_price     = dataUser.Rows[0]["GiaMoi"].ToString();
            double product_price = 0;
            if (!string.IsNullOrEmpty(str_price))
            {
                product_price = double.Parse(str_price);
            }

            total += product_price;
        }

        NL_Checkout nlcheckout = new NL_Checkout();

        nlcheckout.merchant_site_code = this.merchant_site_code;
        nlcheckout.secure_pass        = this.merchant_pass;

        var      rnd    = new Random(DateTime.Now.Millisecond);
        int      oderID = rnd.Next(0, 3000);
        DateTime dtNow  = DateTime.Now;

        //string strOrderID = dtNow.Year.ToString() + dtNow.Month.ToString() + dtNow.Day.ToString() + dtNow.Hour.ToString() + dtNow.Minute.ToString() + dtNow.Second.ToString();

        //string return_url, string receiver, string transaction_info, string order_code, string price, string currency, float quantity, float tax, float discount, float fee_cal, float fee_shipping, string order_description, string buyer_info, string affiliate_code
        string return_url, transaction_info, order_code, price, currency, order_description, buyer_info, affiliate_code;
        float  quantity, tax, discount, fee_cal, fee_shipping;

        //return_url = HttpContext.Current.Request.Url.Authority.ToString() + GetRouteUrl("finishCheckOut", new { });
        return_url       = "http://" + HttpContext.Current.Request.Url.Authority.ToString() + "/finishcheckout";
        transaction_info = "";

        order_code        = MyStaticData.TaoMaDonDatHang();
        price             = total.ToString();
        currency          = "vnd";
        quantity          = cart.Rows.Count;
        tax               = 0;
        discount          = 0;
        fee_cal           = 0;
        fee_shipping      = 0;
        order_description = "";
        buyer_info        = "";
        affiliate_code    = "";

        string rs = nlcheckout.buildCheckoutUrlNew(return_url, this.receiver, transaction_info, order_code, price, currency, quantity, tax, discount, fee_cal, fee_shipping, order_description, buyer_info, affiliate_code);

        Response.Redirect(rs);
    }
Example #12
0
        public ActionResult Payment(string CustName, string CustPhone, string CustAdd, string CustEmail, bool?thanhtoantructuyenNL, bool?thanhtoantructuyenPP)
        {
            if (Session["userName"] == null)
            {
                return(RedirectToAction("LoginUsernormal", "LoginUser"));
            }
            var orderBook = new OrdersBook();
            int userID    = Convert.ToInt32(Session["userID"]);

            //Lưu vào trong db OrderBook
            orderBook.FoundedDate = DateTime.Now;
            orderBook.UserID      = userID;
            orderBook.Status      = 0;
            orderBook.Address     = CustAdd;
            orderBook.Phone       = CustPhone;
            orderBook.Email       = CustEmail;
            orderBook.FullName    = CustName;
            orderBook.Paid        = false; // Mặc định là chưa thanh toán
            bool result = new OrderBookDAO().Insert(orderBook);

            try
            {
                if (result)
                {
                    int tempID = orderBook.OrderID;

                    var    cart      = (List <CartItem>)Session[CommonConstant.cartSession];
                    var    detailDAO = new OrdersDetailsDAO();
                    double sum       = 0;
                    foreach (var item in cart)
                    {
                        var orderDetail = new OrdersDetail();
                        orderDetail.OrderID  = tempID;
                        orderDetail.BookID   = item.Books.BookID;
                        orderDetail.Total    = (item.Quantity * item.Books.Price);
                        orderDetail.Quantity = item.Quantity;
                        orderDetail.Status   = 0;
                        detailDAO.Insert(orderDetail);

                        sum += (item.Books.Price.GetValueOrDefault(0) * item.Quantity);
                    }

                    //Gửi mail thông báo đơn hàng cho Khách hàng
                    string content = System.IO.File.ReadAllText(Server.MapPath("~/Areas/Store/Views/template/newOrder.cshtml"));
                    content = content.Replace("{{CustomerName}}", CustName);
                    content = content.Replace("{{Phone}}", CustPhone);
                    content = content.Replace("{{Email}}", CustEmail);
                    content = content.Replace("{{Address}}", CustAdd);
                    content = content.Replace("{{Total}}", sum.ToString("N0"));
                    new MailHelper().SendMail(CustEmail, "Đơn hàng mới từ QT BookStore", content, "Thông báo Đơn Đặt hàng từ QT BookStore");

                    if ((thanhtoantructuyenNL == null || thanhtoantructuyenNL == false) && (thanhtoantructuyenPP == null || thanhtoantructuyenPP == false))
                    {
                        Session[CommonConstant.cartSession] = null;
                        return(Redirect("/hoan-thanh"));
                    }
                    else if (thanhtoantructuyenPP != null || thanhtoantructuyenPP == true)
                    {
                        var model = new CommonConstant.InforPaypal
                        {
                            OrderId = tempID,
                            Total   = cart.Sum(m => m.Quantity * m.Books.Price) ?? 0
                        };
                        TempData["InforPaypal"] = model;
                        return(RedirectToAction("PaymentWithPaypal", "Paypal"));
                    }
                    else
                    {
                        NL_Checkout nganluong    = new NL_Checkout();
                        double      total        = cart.Sum(m => m.Quantity * m.Books.Price) ?? 0;
                        string      urlThanhToan = nganluong.buildCheckoutUrlNew(Url.Action("PaymentConfirmed", "OrderBook", null, Request.Url.Scheme), ConfigurationManager.AppSettings["email_nganluong"].ToString(), "Thanh toán " + total.ToString("#,##0").Replace(',', '.') + " đồng", tempID.ToString(), total.ToString(), "vnd", 1, 0, 0, 0, 0, "Thanh toán " + total.ToString("#,##0").Replace(',', '.') + " đồng",
                                                                                 "Thanh toán " + total.ToString("#,##0").Replace(',', '.') + " đồng", "");
                        return(Redirect(urlThanhToan));
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Không thể thêm đơn hàng vì xảy ra lỗi ở server!");
                    return(View("ThongBaoLoi"));
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                return(View("ThongBaoLoi"));
            }
        }
Example #13
0
    protected void LinkButton_CheckOut_Click(object sender, EventArgs e)
    {
        string email = input_Email.Value.Trim();
        string fullname = input_Fullname.Value.Trim();
        string mobi = input_Mobi.Value.Trim();
        string mobi2 = input_Mobi2.Value.Trim();
        bool gender = radio_GenderMale.Checked ? true : false;
        string address = input_Address.Value.Trim();
        //kiểm tra có null không
        if (email.IsNullOrEmptyOrWhiteSpaces() || !email.IsEmailFormat())
        {
            ucMessage.ShowError("Mời Nhập Email Đúng Định Dạng");
            return;
        }

        if (fullname.IsNullOrEmptyOrWhiteSpaces())
        {
            ucMessage.ShowError("Mời Nhập Họ Tên ");
            return;
        }
        if (mobi.IsNullOrEmptyOrWhiteSpaces() || IsNumber(mobi) == false )
        {
            ucMessage.ShowError("Quý Khách Chưa Nhập Số Điện Thoại hoặc Nhập Sai Số Điện Thoại");
            return;
        }
        if (mobi2.IsNullOrEmptyOrWhiteSpaces() || IsNumber(mobi2) == false)
        {
            ucMessage.ShowError("Quý Khách Chưa Nhập Số Điện Thoại 2 hoặc Nhập Sai Số Điện Thoại");
            return;
        }

        if (address.IsNullOrEmptyOrWhiteSpaces())
        {
            ucMessage.ShowError("Mời Nhập Địa Chỉ");
            return;
        }

        int paymenMethod = radio_payment_NganLuong.Checked == true ? 1 : 0;

        // kiểm tra giỏ hàng khác rỗng
        if (SessionUtility.Cart.Count == 0)
        {
            ucMessage.ShowError("Bạn Chưa Chọn Sản Phẩm");
            return;
        }
        // thêm mã cho đơn hàng
        string addCode = "VSD2020";
        Order order = new Order();
        order.Code = addCode;
        order.Email = email;
        order.FullName = fullname;
        order.Mobi = mobi;
        order.Mobi2 = mobi2;
        order.Gender = gender;
        order.Address = address;
        order.Ship = SessionUtility.Cart.Ship;
        order.Total = SessionUtility.Cart.AmountPay;
        order.OrderStatus = true; // đã đặt hàng
        order.DeliverStatus = false; // chưa giao hàng
        order.ChargeStatus = false; // chưa thanh toán
        order.CreateTime = DateTime.Now;
        order.PaymentMethod = paymenMethod;

        // kiểm tra khách đăng nhập chưa nếu rồi thì lưu thông tin khách
        if (SessionUtility.Client != null)
        {
            order.ClientID = SessionUtility.Client.ClientID;
        }

        // lưu chi tiết đơn hàng vào trong đơn hàng
        foreach (var item in SessionUtility.Cart.CartItems.Values)
        {
            OrderDetail detail = new OrderDetail();
            detail.ProductID = item.ID;
            detail.Price = item.Price;
            detail.Quantity = item.Quantity;

            order.OrderDetails.Add(detail);
        }
        //lưu db
        DBEntities db = new DBEntities();
        db.Orders.Add(order);
        db.SaveChanges();

        // lưu thông tin khách vào session để có thể kiểm tra lại đơn hàng
        SessionUtility.Cart.Email = order.Email;


        //Chuyển đến trang thanh toán
        //Lấy url của website
        string baseUrl = Request.Url.GetLeftPart(UriPartial.Authority);

        //Kiểm tra phương thức thanh toán
        if (order.PaymentMethod == 0)
        {
            //Thanh toán tại nhà
            string returnUrl = "{0}/ProductCheckoutComplete.aspx?payment_type={1}&order_code={2}".StringFormat(baseUrl, order.PaymentMethod, order.OrderID);
            Response.Redirect(returnUrl);
            return;
        }
        else
        {
            //Thanh toán tại nganluong
            string returnUrl = "{0}/ProductCheckoutComplete.aspx".StringFormat(baseUrl);
            string transaction_info = "Quốc Khánh thanh toán đơn hàng có mã số {0}".StringFormat(order.OrderID);
            string order_code = order.OrderID.ToString();
            string receiver = "*****@*****.**";
            string price = "2000"; //Giá demo tối thiểu
            NL_Checkout nl = new NL_Checkout();
            string url = nl.buildCheckoutUrl(returnUrl, receiver, transaction_info, order_code, price);
            Response.Redirect(url);
        }

        ucMessage.ShowSuccess("Đã Lưu Đơn Hàng , Đang Chờ Thanh Toán");
    }
Example #14
0
        public ActionResult btnSubmit_Click(object sender, EventArgs e, OrderViewModel model)
        {
            String transaction_info = "Thanh toan dat san";
            String order_code       = DateTime.Now.ToString("yyyyMMddHHmmss");
            String receiver         = "*****@*****.**";//Tài khoản nhận tiền
            String return_url       = Url.Action("verifyOrder", "Order",
                                                 new { area = "", orderCode = order_code }, Request.Url.Scheme);
            String cancel_url = "http://ssn.techeco.net/Order";
            //String price = model.Price.ToString();
            String      price = "2000";
            NL_Checkout nl    = new NL_Checkout();
            String      url;

            url = nl.buildCheckoutUrl(return_url, cancel_url, receiver, transaction_info, order_code, price);

            var      _orderService     = this.Service <IOrderService>();
            var      _timeBlockService = this.Service <ITimeBlockService>();
            var      order             = new Order();
            DateTime PlayDate          = DateTime.ParseExact(Request["CreateDate"], "dd/MM/yyyy", CultureInfo.InvariantCulture);

            order.UserId  = User.Identity.GetUserId();
            order.FieldId = model.FieldId;
            DateTime sTime = new DateTime(PlayDate.Year, PlayDate.Month, PlayDate.Day, model.StartTime.Hour,
                                          model.StartTime.Minute, model.StartTime.Second);
            DateTime eTime = new DateTime(PlayDate.Year, PlayDate.Month, PlayDate.Day, model.EndTime.Hour,
                                          model.EndTime.Minute, model.EndTime.Second);

            order.StartTime  = sTime;
            order.EndTime    = eTime;
            order.CreateDate = DateTime.Now;
            //order.Token = result.Token;
            order.Price = _timeBlockService.calPrice(model.FieldId, sTime.TimeOfDay, eTime.TimeOfDay);
            //order.OnlinePaymentMethod = info.Payment_method;
            //order.BankCode = info.bank_code;
            order.Note       = model.Note;
            order.PayerName  = model.PayerName;
            order.PayerEmail = model.PayerEmail;
            order.PayerPhone = model.PayerPhone;
            order.Status     = (int)OrderStatus.Pending;
            order.OrderCode  = order_code;
            order.QRCodeUrl  = Utils.GenerateQRCode(order_code, QRCodeGenerator.ECCLevel.Q);
            var transdate = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");

            order.TransactionTime = DateTime.Parse(transdate);

            if (model.PaidType == (int)OrderPaidType.ChosePayOnline)
            {
                order.PaidType = (int)OrderPaidType.ChosePayOnline;
            }
            if (model.PaidType == (int)OrderPaidType.ChosePayByCash)
            {
                order.PaidType = (int)OrderPaidType.ChosePayByCash;
                url            = Url.Action("BookFieldSuccessful", "Order",
                                            new { area = "", orderCode = order_code }, Request.Url.Scheme);
            }

            var _userService = this.Service <IAspNetUserService>();
            var userId       = User.Identity.GetUserId();
            var user         = _userService.FirstOrDefaultActive(p => p.Id == userId);

            if (user == null)
            {
                return(RedirectToAction("PageNotFound", "Errors"));
            }

            var _fieldService = this.Service <IFieldService>();
            var field         = _fieldService.FirstOrDefaultActive(p => p.Id == order.FieldId);

            if (field == null)
            {
                return(RedirectToAction("PageNotFound", "Errors"));
            }
            var noti = new Notification();

            noti.UserId     = field.Place.UserId;
            noti.FromUserId = userId;
            noti.CreateDate = DateTime.Now;
            noti.Message    = user.FullName + " đã đặt sân tại " + field.Name;
            noti.Title      = "Đơn hàng mới";
            noti.Type       = (int)NotificationType.Order;
            noti.MarkRead   = false;
            noti.Active     = true;
            order.Notifications.Add(noti);
            _orderService.Create(order);


            //Fire base noti
            List <string> registrationIds = GetToken(noti.UserId);

            //registrationIds.Add("dgizAK4sGBs:APA91bGtyQTwOiAgNHE_mIYCZhP0pIqLCUvDzuf29otcT214jdtN2e9D6iUPg3cbYvljKbbRJj5z7uaTLEn1WeUam3cnFqzU1E74AAZ7V82JUlvUbS77mM42xHZJ5DifojXEv3JPNEXQ");

            NotificationModel Amodel = Mapper.Map <NotificationModel>(PrepareNotificationCustomViewModel(noti));

            if (registrationIds != null && registrationIds.Count != 0)
            {
                Android.Notify(registrationIds, null, Amodel);
            }

            //SignalR Noti
            var notiService = this.Service <INotificationService>();
            NotificationFullInfoViewModel notiModelR = notiService.PrepareNoti(Mapper.Map <NotificationFullInfoViewModel>(noti));

            // Get the context for the Pusher hub
            IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext <RealTimeHub>();

            // Notify clients in the group
            hubContext.Clients.User(notiModelR.UserId).send(notiModelR);


            string subject = "[SSN] - Thông tin đặt sân";
            string body    = "Hi <strong>" + user.FullName + "</strong>" +
                             ",<br/><br/>Bạn đã đặt sân: " + field.Name + "<br/> Tại địa điểm: " + field.Place.Name +
                             "<br/> Thời gian: " + order.StartTime.ToString("HH:mm") + " - " +
                             order.EndTime.ToString("HH:mm") + ", ngày " + order.StartTime.ToString("dd/MM/yyyy") +
                             "<br/> Giá tiền : " + order.Price.ToString("n0") + " đồng" +
                             "<br/> <strong>Mã đặt sân của bạn : " + order.OrderCode + "</strong>" +
                             "<br/><img src='ssn.techeco.net/" + order.QRCodeUrl + "'>" +
                             "<br/> Cảm ơn bạn đã sử dụng dịch vụ của SSN. Chúc bạn có những giờ phút thoải mái chơi thể thao!";

            EmailSender.Send(Setting.CREDENTIAL_EMAIL, new string[] { model.PayerEmail }, null, null, subject, body, true);

            return(Redirect(url));
        }
Example #15
0
        public IHttpActionResult Get(string query, string transaction_info, string order_code, string price, string payment_id, string payment_type, string error_text, string secure_code, [FromUri] double longtitude, [FromUri] double latitude, string id_shipper = null)
        {
            //Get URL from Ngan luong
            //var uri = new Uri(url);
            //var query = HttpUtility.ParseQueryString(uri.Query);
            //var transaction_info = query.Get("transaction_info");
            //var order_code = query.Get("order_code");
            //var price = query.Get("price");
            //var payment_id = query.Get("payment_id");
            //var payment_type = query.Get("payment_type");
            //var error_text = query.Get("error_text");
            //var secure_code = query.Get("secure_code");
            //var return_url = query.Get("return_url");

            //Customer from order
            var customer = _context.Orders.Select(x => x.Account);

            //Shipper from order
            var shipper = _context.Orders.Select(x => x.Account1);

            //order từ order_code
            var order_fcm = _context.Orders.Find(order_code);


            try
            {
                NL_Checkout checkOut = new NL_Checkout();
                bool        rs       = checkOut.verifyPaymentUrl(transaction_info, order_code, price, payment_id, payment_type, error_text, secure_code);
                byte[]      buffer   = Guid.NewGuid().ToByteArray();
                var         trans_id = BitConverter.ToInt64(buffer, 0).ToString();
                rs = true;
                #region rs:OK Shipper:tìm thấy
                if (rs)
                {
                    _context.Transactions.Add(new Transaction
                    {
                        id_transaction = trans_id,
                        id_order       = order_code,
                        money          = double.Parse(price),
                        created_time   = DateTime.Today
                    });
                    _context.SaveChanges();
                    try
                    {
                        var sCoord  = new GeoCoordinate(latitude, longtitude);
                        var address = _context.Accounts.AsEnumerable().Where(x => x.id_role == "1").Select(x => new ShipperVM
                        {
                            id          = x.id_account,
                            username    = x.username,
                            lat         = x.GroupAddress.Addresses.FirstOrDefault().lat,
                            @long       = x.GroupAddress.Addresses.FirstOrDefault().@long,
                            levels      = x.Levels.Select(xx => xx.point).FirstOrDefault(),
                            fcm_token   = x.fcm_token,
                            id_order    = order_code,
                            getDistance = sCoord.GetDistanceTo(new GeoCoordinate(x.GroupAddress.Addresses.FirstOrDefault().lat ?? 0, x.GroupAddress.Addresses.FirstOrDefault().@long ?? 0))
                        }).ToList().OrderBy(x => x.getDistance);

                        var list  = new List <ShipperVM>();
                        var list1 = new List <ShipperVM>();
                        var list2 = new List <ShipperVM>();
                        foreach (var item in address)
                        {
                            if (item.getDistance <= 3000)
                            {
                                list.Add(item);
                            }
                        }

                        foreach (var item in list.OrderBy(x => x.levels).Take(5))
                        {
                            list1.Add(item);
                        }
                        list1.Reverse();

                        if (list.Count == 0)
                        {
                            WebRequest ftRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
                            ftRequest.Method = "post";
                            //serverKey - Key from Firebase cloud messaging server
                            ftRequest.Headers.Add(string.Format("Authorization: key={0}", "AIzaSyDN6yImcd7eWPRiN86cn1C7iecVNaF945M"));
                            //Sender Id - From firebase project setting
                            ftRequest.Headers.Add(string.Format("Sender: id={0}", "462404511537"));
                            ftRequest.ContentType = "application/json";

                            var fcm_ss = "eg8nUQs-lbQ:APA91bHPgVKmMy8d0vnpt-u0UMJPivSvU9kaGPyttY1-ZP-gcu6qkt7VuJ9MG-uDPOPCIkDxpgWJ0TfdP_axotwn-mZEcBOpkEXpn1QfD_HeueUMt-myWeS3ZATw_R11s5D2-N83Sq6U";

                            Account _customer = _context.Accounts.Find(order_fcm.id_customer);
                            fcm_ss = _context.Accounts.AsEnumerable().Where(x => x.id_role == "2" && x.id_account == _customer.id_account).Select(x => x.fcm_token).FirstOrDefault();
                            var payload2 = new
                            {
                                //to = customer.Select(x => x.fcm_token).FirstOrDefault().ToString(),
                                to                = fcm_ss,
                                priority          = "high",
                                content_available = true,
                                notification      = new
                                {
                                    body  = "Không tìm thấy Shipper gần Market!",
                                    title = "Test",
                                    badge = 1
                                },
                            };

                            string postbody2  = JsonConvert.SerializeObject(payload2).ToString();
                            Byte[] byteArray2 = Encoding.UTF8.GetBytes(postbody2);
                            ftRequest.ContentLength = byteArray2.Length;
                            using (Stream dataStream = ftRequest.GetRequestStream())
                            {
                                dataStream.Write(byteArray2, 0, byteArray2.Length);
                                using (WebResponse tResponse = ftRequest.GetResponse())
                                {
                                    using (Stream dataStreamResponse = tResponse.GetResponseStream())
                                    {
                                        if (dataStreamResponse != null)
                                        {
                                            using (StreamReader tReader = new StreamReader(dataStreamResponse))
                                            {
                                                String sResponseFromServer = tReader.ReadToEnd();
                                                //result.Response = sResponseFromServer;
                                            }
                                        }
                                    }
                                }
                            }
                            return(NotFound());
                        }


                        WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
                        tRequest.Method = "post";
                        //serverKey - Key from Firebase cloud messaging server
                        tRequest.Headers.Add(string.Format("Authorization: key={0}", "AIzaSyDN6yImcd7eWPRiN86cn1C7iecVNaF945M"));
                        //Sender Id - From firebase project setting
                        tRequest.Headers.Add(string.Format("Sender: id={0}", "462404511537"));
                        tRequest.ContentType = "application/json";



                        var fcm_s = "eg8nUQs-lbQ:APA91bHPgVKmMy8d0vnpt-u0UMJPivSvU9kaGPyttY1-ZP-gcu6qkt7VuJ9MG-uDPOPCIkDxpgWJ0TfdP_axotwn-mZEcBOpkEXpn1QfD_HeueUMt-myWeS3ZATw_R11s5D2-N83Sq6U";

                        ShipperVM shipperr = list1.First();
                        fcm_s = _context.Accounts.AsEnumerable().Where(x => x.id_role == "1" && x.id_account == shipperr.id).Select(x => x.fcm_token).FirstOrDefault();

                        var payload = new
                        {
                            //Bỏ vô để test cho vui chứ chưa có FCM token nó trả ra lỗi BAD request(400) từ firebase server
                            to                = "eg8nUQs-lbQ:APA91bHPgVKmMy8d0vnpt-u0UMJPivSvU9kaGPyttY1-ZP-gcu6qkt7VuJ9MG-uDPOPCIkDxpgWJ0TfdP_axotwn-mZEcBOpkEXpn1QfD_HeueUMt-myWeS3ZATw_R11s5D2-N83Sq6U",
                            priority          = "high",
                            content_available = true,
                            notification      = new
                            {
                                body  = "Bạn có một đơn hàng!",
                                title = "Test",
                                badge = 1
                            },
                        };

                        string postbody  = JsonConvert.SerializeObject(payload).ToString();
                        Byte[] byteArray = Encoding.UTF8.GetBytes(postbody);
                        tRequest.ContentLength = byteArray.Length;
                        using (Stream dataStream = tRequest.GetRequestStream())
                        {
                            dataStream.Write(byteArray, 0, byteArray.Length);
                            using (WebResponse tResponse = tRequest.GetResponse())
                            {
                                using (Stream dataStreamResponse = tResponse.GetResponseStream())
                                {
                                    if (dataStreamResponse != null)
                                    {
                                        using (StreamReader tReader = new StreamReader(dataStreamResponse))
                                        {
                                            String sResponseFromServer = tReader.ReadToEnd();
                                            //result.Response = sResponseFromServer;
                                        }
                                    }
                                }
                            }
                        }

                        if (list1.Count > 0)
                        {
                            order_fcm.id_shipper = list1.First().id;
                            _context.SaveChanges();
                            return(Ok(list1));
                        }
                        #endregion

                        #region rs:OK Shipper: không tìm thấy

                        return(NotFound());
                    }
                    catch (Exception ex)
                    {
                        return(InternalServerError(ex));
                    }
                }

                #endregion

                #region rs:không thành công
                else
                {
                    WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
                    tRequest.Method = "post";
                    //serverKey - Key from Firebase cloud messaging server
                    tRequest.Headers.Add(string.Format("Authorization: key={0}", "AIzaSyDN6yImcd7eWPRiN86cn1C7iecVNaF945M"));
                    //Sender Id - From firebase project setting
                    tRequest.Headers.Add(string.Format("Sender: id={0}", "462404511537"));
                    tRequest.ContentType = "application/json";

                    var fcm_ss = "eg8nUQs-lbQ:APA91bHPgVKmMy8d0vnpt-u0UMJPivSvU9kaGPyttY1-ZP-gcu6qkt7VuJ9MG-uDPOPCIkDxpgWJ0TfdP_axotwn-mZEcBOpkEXpn1QfD_HeueUMt-myWeS3ZATw_R11s5D2-N83Sq6U";

                    Account _customer = _context.Accounts.FirstOrDefault(x => x.id_account == order_fcm.id_customer);
                    fcm_ss = _context.Accounts.AsEnumerable().Where(x => x.id_role == "2" && x.id_account == _customer.id_account).Select(x => x.fcm_token).FirstOrDefault();

                    var payload3 = new
                    {
                        // to
                        to                = fcm_ss,
                        priority          = "high",
                        content_available = true,
                        notification      = new
                        {
                            body  = "Giao dịch thất bại!",
                            title = "Test",
                            badge = 1
                        },
                    };

                    string postbody3  = JsonConvert.SerializeObject(payload3).ToString();
                    Byte[] byteArray3 = Encoding.UTF8.GetBytes(postbody3);
                    tRequest.ContentLength = byteArray3.Length;
                    using (Stream dataStream = tRequest.GetRequestStream())
                    {
                        dataStream.Write(byteArray3, 0, byteArray3.Length);
                        using (WebResponse tResponse = tRequest.GetResponse())
                        {
                            using (Stream dataStreamResponse = tResponse.GetResponseStream())
                            {
                                if (dataStreamResponse != null)
                                {
                                    using (StreamReader tReader = new StreamReader(dataStreamResponse))
                                    {
                                        String sResponseFromServer = tReader.ReadToEnd();
                                        //result.Response = sResponseFromServer;
                                    }
                                }
                            }
                        }
                    }
                    return(NotFound());
                }
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }

            #endregion
        }
Example #16
0
    public Boolean UpdateOrder(String transaction_info, String order_code, String payment_id, String payment_type, String secure_code)
    {
        String path           = Server.MapPath("Contend");
        String secure_code_ws = this.GetMD5Hash(transaction_info + " " + order_code + " " + payment_id + " " + payment_type + " " + this.secure_pass);
        String nd             = transaction_info + " " + order_code + " " + payment_id + " " + payment_type + " " + this.secure_pass;

        System.IO.StreamWriter str = new System.IO.StreamWriter(path + "/nganluong.txt");
        str.Write(nd);
        str.Flush();
        str.Close();

        if (secure_code == secure_code_ws)
        {
            try
            {
                SqlConnection cnn = new SqlConnection();
                cnn.ConnectionString = "data source=(local);Database=Online.Topcare;uid=tc;pwd=quynhnet0153;";
                cnn.Open();

                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = "UPDATE Gio_hang_ngan_luong set payment_type=" + payment_type + ", payment_id='" + payment_id + "' where transaction_info=" + transaction_info;
                cmd.Connection  = cnn;
                int result = cmd.ExecuteNonQuery();


                NL_Checkout nlcheckout = new NL_Checkout();
                nlcheckout.merchant_site_code = this.merchant_site_code;
                nlcheckout.secure_pass        = this.secure_pass;

                string resultcheckorder = nlcheckout.Nl_checkoder(1, order_code, payment_id);


                XmlDocument dom = new XmlDocument();
                dom.LoadXml(resultcheckorder);
                XmlNodeList root = dom.DocumentElement.ChildNodes;
                if (root.Item(1).InnerText == "00")
                {
                    // cập nhật đơn hàng với oder_code
                    //Phương thức thanh toán khách đã lựa chọn : == root.Item(2).ChildNodes.Item(14).InnerText;
                }



                if (result != 1)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception ex) {
                return(false);
            }
        }
        else
        {
            return(false);
        }
    }