Пример #1
0
        public ActionResult Callback()
        {
            if (Request.QueryString.Count > 0)
            {
                var          vnpayData = Request.QueryString;
                VnPayLibrary vnpay     = new VnPayLibrary();
                //if (vnpayData.Count > 0)
                //{
                foreach (string s in vnpayData)
                {
                    //get all querystring data
                    if (!string.IsNullOrEmpty(s) && s.StartsWith("vnp_"))
                    {
                        vnpay.AddResponseData(s, vnpayData[s]);
                    }
                }
                // }

                //vnp_TxnRef: Ma don hang merchant gui VNPAY tai command=pay
                string orderId = vnpay.GetResponseData("vnp_TxnRef");

                // lấy ra idkiosk để lấy hashsecret trong kiosk
                string   vnp_HashSecret = "NZWQLJRMIMACCBLXUUHZXWRDPRMJPIVQ";
                int      IdTransaction  = int.Parse(orderId);
                int      IdKiosk        = 0;
                DateTime payDate        = DateTime.Now;

                //vnp_TransactionNo: Ma GD tai he thong VNPAY
                long vnpayTranId = Convert.ToInt64(vnpay.GetResponseData("vnp_TransactionNo"));
                //vnp_ResponseCode:Response code from VNPAY: 00: Thanh cong, Khac 00: Xem tai lieu
                string vnp_ResponseCode = vnpay.GetResponseData("vnp_ResponseCode");
                //vnp_SecureHash: MD5 cua du lieu tra ve
                String vnp_SecureHash = Request.QueryString["vnp_SecureHash"];


                bool checkSignature = vnpay.ValidateSignature(vnp_SecureHash, vnp_HashSecret);
                if (checkSignature)
                {
                    if (vnp_ResponseCode.Equals("00"))
                    {
                        //Thanh toan thanh cong

                        using (THUONGMAIDIENTUEntities db = new THUONGMAIDIENTUEntities())
                        {
                            var order = db.ORDERs.Where(x => x.IdOrder == IdTransaction).FirstOrDefault();
                            order.IdStatus = 2;
                            db.SaveChanges();
                            TempData["id"] = IdTransaction;
                            return(RedirectToAction("Success"));
                        }
                    }
                }
            }
            return(RedirectToAction("Fail"));
        }
Пример #2
0
        public ActionResult VnPayReturn()
        {
            log.InfoFormat("Begin VNPAY Return, URL={0}", Request.RawUrl);
            if (Request.QueryString.Count > 0)
            {
                string       vnp_HashSecret = ConfigurationManager.AppSettings["vnp_HashSecret"]; //Chuoi bi mat
                var          vnpayData      = Request.QueryString;
                VnPayLibrary vnpay          = new VnPayLibrary();
                //if (vnpayData.Count > 0)
                //{
                foreach (string s in vnpayData)
                {
                    //get all querystring data
                    if (!string.IsNullOrEmpty(s) && s.StartsWith("vnp_"))
                    {
                        vnpay.AddResponseData(s, vnpayData[s]);
                    }
                }
                // }

                //vnp_TxnRef: Ma don hang merchant gui VNPAY tai command=pay
                long orderId = Convert.ToInt64(vnpay.GetResponseData("vnp_TxnRef"));
                //vnp_TransactionNo: Ma GD tai he thong VNPAY
                long vnpayTranId = Convert.ToInt64(vnpay.GetResponseData("vnp_TransactionNo"));
                //vnp_ResponseCode:Response code from VNPAY: 00: Thanh cong, Khac 00: Xem tai lieu
                string vnp_ResponseCode = vnpay.GetResponseData("vnp_ResponseCode");
                //vnp_SecureHash: MD5 cua du lieu tra ve
                String vnp_SecureHash = Request.QueryString["vnp_SecureHash"];
                bool   checkSignature = vnpay.ValidateSignature(vnp_SecureHash, vnp_HashSecret);
                if (checkSignature)
                {
                    if (vnp_ResponseCode == "00")
                    {
                        //Thanh toan thanh cong
                        ViewBag.displayMsg = "Thanh toán thành công";
                        log.InfoFormat("Thanh toan thanh cong, OrderId={0}, VNPAY TranId={1}", orderId, vnpayTranId);
                    }
                    else
                    {
                        //Thanh toan khong thanh cong. Ma loi: vnp_ResponseCode
                        ViewBag.displayMsg = "Có lỗi xảy ra trong quá trình xử lý.Mã lỗi: " + vnp_ResponseCode;
                        log.InfoFormat("Thanh toan loi, OrderId={0}, VNPAY TranId={1},ResponseCode={2}", orderId,
                                       vnpayTranId, vnp_ResponseCode);
                    }
                }
                else
                {
                    log.InfoFormat("Invalid signature, InputData={0}", Request.RawUrl);
                    ViewBag.displayMsg = "Có lỗi xảy ra trong quá trình xử lý";
                }
            }

            return(View());
        }
Пример #3
0
        public ActionResult IpnListener()
        {
            string returnContent = string.Empty;

            if (Request.QueryString.Count > 0)
            {
                string       vnp_HashSecret = ConfigurationManager.AppSettings["vnp_HashSecret"]; //Secret key
                var          vnpayData      = Request.QueryString;
                VnPayLibrary vnpay          = new VnPayLibrary();


                foreach (string s in vnpayData)
                {
                    //get all querystring data
                    if (!string.IsNullOrEmpty(s) && s.StartsWith("vnp_"))
                    {
                        vnpay.AddResponseData(s, vnpayData[s]);
                    }
                }
                //Lay danh sach tham so tra ve tu VNPAY
                //vnp_TxnRef: Ma don hang merchant gui VNPAY tai command=pay
                //vnp_TransactionNo: Ma GD tai he thong VNPAY
                //vnp_ResponseCode:Response code from VNPAY: 00: Thanh cong, Khac 00: Xem tai lieu
                //vnp_SecureHash: SHA256 cua du lieu tra ve

                long   orderId          = Convert.ToInt64(vnpay.GetResponseData("vnp_TxnRef"));
                long   vnpayTranId      = Convert.ToInt64(vnpay.GetResponseData("vnp_TransactionNo"));
                string vnp_ResponseCode = vnpay.GetResponseData("vnp_ResponseCode");
                String vnp_SecureHash   = Request.QueryString["vnp_SecureHash"];
                bool   checkSignature   = vnpay.ValidateSignature(vnp_SecureHash, vnp_HashSecret);

                if (checkSignature)
                {
                    //Cap nhat ket qua GD
                    //Yeu cau: Truy van vao CSDL cua  Merchant => lay ra duoc OrderInfo
                    //Giả sử OrderInfo lấy ra được như giả lập bên dưới
                    OrderInfo order = new OrderInfo();
                    order.OrderId           = orderId;
                    order.vnp_TransactionNo = vnpayTranId;
                    order.Status            = 0; //0: Cho thanh toan,1: da thanh toan,2: GD loi
                                                 //Kiem tra tinh trang Order
                    if (order != null)
                    {
                        if (order.Status == 0)
                        {
                            if (vnp_ResponseCode == "00")
                            {
                                //Thanh toan thanh cong
                                log.InfoFormat("Thanh toan thanh cong, OrderId={0}, VNPAY TranId={1}", orderId,
                                               vnpayTranId);
                                order.Status = 1;
                            }
                            else
                            {
                                //Thanh toan khong thanh cong. Ma loi: vnp_ResponseCode
                                //  displayMsg.InnerText = "Có lỗi xảy ra trong quá trình xử lý.Mã lỗi: " + vnp_ResponseCode;
                                log.InfoFormat("Thanh toan loi, OrderId={0}, VNPAY TranId={1},ResponseCode={2}",
                                               orderId,
                                               vnpayTranId, vnp_ResponseCode);
                                order.Status = 2;
                            }

                            //Thêm code Thực hiện cập nhật vào Database
                            //Update Database

                            returnContent = "{\"RspCode\":\"00\",\"Message\":\"Confirm Success\"}";
                        }
                        else
                        {
                            returnContent = "{\"RspCode\":\"02\",\"Message\":\"Order already confirmed\"}";
                        }
                    }
                    else
                    {
                        returnContent = "{\"RspCode\":\"01\",\"Message\":\"Order not found\"}";
                    }
                }
                else
                {
                    log.InfoFormat("Invalid signature, InputData={0}", Request.RawUrl);
                    returnContent = "{\"RspCode\":\"97\",\"Message\":\"Invalid signature\"}";
                }
            }
            else
            {
                returnContent = "{\"RspCode\":\"99\",\"Message\":\"Input data required\"}";
            }

            return(new JsonResult()
            {
                Data = returnContent,
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            });
        }
Пример #4
0
        public async Task<IActionResult> ResultATMPay(GetRequest getRequest)
        {
            log.InfoFormat("Begin VNPAY Return, URL={0}", Request.QueryString);
            if (Request.QueryString.Value.Length > 0 && getRequest.vnp_BankTranNo != null && getRequest.vnp_Amount.Length > 0 && getRequest.vnp_BankCode.Length > 0 && getRequest.vnp_CardType.Length > 0 && getRequest.vnp_OrderInfo.Length > 0 && getRequest.vnp_PayDate.Length > 0 && getRequest.vnp_ResponseCode.Length > 0 && getRequest.vnp_SecureHash.Length > 0 && getRequest.vnp_SecureHashType.Length > 0 && getRequest.vnp_TmnCode.Length > 0 && getRequest.vnp_TransactionNo.Length > 0 && getRequest.vnp_TxnRef.Length > 0)
            {
                string vnp_HashSecret = _vnpay.vnp_HashSecret; //Chuoi bi mat
                string vnpayData = Request.QueryString.ToString();
                VnPayLibrary vnpay = new VnPayLibrary();
                vnpay.AddResponseData("vnp_Amount", getRequest.vnp_Amount);
                vnpay.AddResponseData("vnp_BankCode", getRequest.vnp_BankCode);
                vnpay.AddResponseData("vnp_BankTranNo", getRequest.vnp_BankTranNo);
                vnpay.AddResponseData("vnp_CardType", getRequest.vnp_CardType);
                vnpay.AddResponseData("vnp_OrderInfo", getRequest.vnp_OrderInfo);
                vnpay.AddResponseData("vnp_PayDate", getRequest.vnp_PayDate);
                vnpay.AddResponseData("vnp_ResponseCode", getRequest.vnp_ResponseCode);
                vnpay.AddResponseData("vnp_SecureHash", getRequest.vnp_SecureHash);
                vnpay.AddResponseData("vnp_SecureHashType", getRequest.vnp_SecureHashType);
                vnpay.AddResponseData("vnp_TmnCode", getRequest.vnp_TmnCode);
                vnpay.AddResponseData("vnp_TransactionNo", getRequest.vnp_TransactionNo);
                vnpay.AddResponseData("vnp_TxnRef", getRequest.vnp_TxnRef);
                //vnp_TxnRef: Ma don hang merchant gui VNPAY tai command=pay    
                long orderId = Convert.ToInt64(vnpay.GetResponseData("vnp_TxnRef"));
                //vnp_TransactionNo: Ma GD tai he thong VNPAY
                long vnpayTranId = Convert.ToInt64(vnpay.GetResponseData("vnp_TransactionNo"));
                //vnp_ResponseCode:Response code from VNPAY: 00: Thanh cong, Khac 00: Xem tai lieu
                string vnp_ResponseCode = vnpay.GetResponseData("vnp_ResponseCode");
                //vnp_SecureHash: MD5 cua du lieu tra ve
                String vnp_SecureHash = getRequest.vnp_SecureHash;
                bool checkSignature = vnpay.ValidateSignature(vnp_SecureHash, vnp_HashSecret);
                EmptyCartRemove();
                if (checkSignature)
                {
                    if (vnp_ResponseCode == "00")
                    {
                        try
                        {
                            //Thanh toan thanh cong
                            ViewBag.thongbao = "Thanh toán thành công";
                            var ma = vnpay.GetResponseData("vnp_OrderInfo");
                            var order = _unitOfWork.OrderRepository.Get(x => x.MaDonHang.Equals(ma)).FirstOrDefault();
                            order.Payment = true;
                            order.ThanhToanTruoc = int.TryParse(vnpay.GetResponseData("vnp_Amount"), out int number) ? int.Parse(vnpay.GetResponseData("vnp_Amount")) / 100 : 0;
                            _unitOfWork.OrderRepository.Update(order);
                            _unitOfWork.SaveNotAync();
                            log.InfoFormat("Thanh toan thanh cong, OrderId={0}, VNPAY TranId={1}", orderId, vnpayTranId);
                            await _mailer.SendEmailSync(order.Email, "[" + order.MaDonHang + "] Đơn đặt hàng từ website ShopAsp.Net", "<p>Thanh toán đơn hàng thành công, số hoá đơn:" + orderId + ". Cảm ơn quý khách đã mua hàng !</p>");

                            var model = new CheckOutCompleteViewModel()
                            {
                                OrderID = ma,
                                Contact = _unitOfWork.ContactRepository.Get().FirstOrDefault()
                            };
                            return View(model);
                        }
                        catch (Exception)
                        {
                            ViewBag.thongbao = "Có lỗi xảy ra trong quá trình xử lý.Mã lỗi: " + vnp_ResponseCode;
                            log.InfoFormat("Thanh toan loi, OrderId={0}, VNPAY TranId={1},ResponseCode={2}", orderId, vnpayTranId, vnp_ResponseCode);
                        }

                    }
                    else
                    {
                        //Thanh toan khong thanh cong. Ma loi: vnp_ResponseCode
                        ViewBag.thongbao = "Có lỗi xảy ra trong quá trình xử lý.Mã lỗi: " + vnp_ResponseCode;
                        log.InfoFormat("Thanh toan loi, OrderId={0}, VNPAY TranId={1},ResponseCode={2}", orderId, vnpayTranId, vnp_ResponseCode);
                    }
                }
                else
                {
                    log.InfoFormat("Invalid signature, InputData={0}", Request.QueryString);
                    ViewBag.thongbao = "Có lỗi xảy ra trong quá trình xử lý";
                }
            }
            else
            {
                //Thanh toan khong thanh cong. Ma loi: vnp_ResponseCode
                ViewBag.thongbao = "Lỗi, xin bạn vui lòng thử lại nha ";
                log.InfoFormat("Thanh toan loi");
            }

            return View();
        }
Пример #5
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string returnContent = string.Empty;

            if (Request.QueryString.Count > 0)
            {
                string       vnp_HashSecret = ConfigurationManager.AppSettings["vnp_HashSecret"]; //Chuoi bi mat
                var          vnpayData      = Request.QueryString;
                VnPayLibrary vnpay          = new VnPayLibrary();

                //if (vnpayData.Count > 0)
                //{
                foreach (string s in vnpayData)
                {
                    //get all querystring data
                    if (!string.IsNullOrEmpty(s) && s.StartsWith("vnp_"))
                    {
                        vnpay.AddResponseData(s, vnpayData[s]);
                    }
                }
                // }
                //Lay danh sach tham so tra ve tu VNPAY

                //vnp_TxnRef: Ma don hang merchant gui VNPAY tai command=pay
                long orderId  = Convert.ToInt64(vnpay.GetResponseData("vnp_TxnRef"));
                int  orderID_ = Convert.ToInt32(vnpay.GetResponseData("vnp_TxnRef"));
                //vnp_TransactionNo: Ma GD tai he thong VNPAY
                long vnpayTranId = Convert.ToInt64(vnpay.GetResponseData("vnp_TransactionNo"));
                //vnp_ResponseCode:Response code from VNPAY: 00: Thanh cong, Khac 00: Xem tai lieu
                string vnp_ResponseCode = vnpay.GetResponseData("vnp_ResponseCode");
                //vnp_SecureHash: MD5 cua du lieu tra ve
                String vnp_SecureHash = Request.QueryString["vnp_SecureHash"];
                bool   checkSignature = vnpay.ValidateSignature(vnp_SecureHash, vnp_HashSecret);
                if (checkSignature)
                {
                    //Cap nhat ket qua GD
                    //Yeu cau: Truy van vao CSDL cua  Merchant => lay ra duoc OrderInfo
                    //Giả sử OrderInfo lấy ra được như giả lập bên dưới
                    OrderInfo order = new OrderInfo();
                    order.OrderId           = orderId;
                    order.vnp_TransactionNo = vnpayTranId;
                    order.Status            = 0; //0: Cho thanh toan,1: da thanh toan,2: GD loi

                    //Kiem tra tinh trang Order
                    if (order != null)
                    {
                        if (order.Status == 0)
                        {
                            if (vnp_ResponseCode == "00")
                            {
                                //Thanh toan thanh cong
                                Debug.WriteLine("Thanh toan thanh cong, OrderId={0}, VNPAY TranId={1}", orderId, vnpayTranId);
                                //log.InfoFormat("Thanh toan thanh cong, OrderId={0}, VNPAY TranId={1}", orderId, vnpayTranId);
                                order.Status = 1;
                                donDatTourController.updateTrangThaiGiaoDich(vnpayTranId, orderID_, 1);
                                Response.Redirect("../fontend/toanthanhthanhtoan.aspx?id=1");
                            }
                            else
                            {
                                //Thanh toan khong thanh cong. Ma loi: vnp_ResponseCode
                                donDatTourController.updateTrangThaiGiaoDich(vnpayTranId, orderID_, 2);
                                //  displayMsg.InnerText = "Có lỗi xảy ra trong quá trình xử lý.Mã lỗi: " + vnp_ResponseCode;
                                Debug.WriteLine("Thanh toan loi, OrderId={0}, VNPAY TranId={1},ResponseCode={2}", orderId,
                                                vnpayTranId, vnp_ResponseCode);
                                // log.InfoFormat("Thanh toan loi, OrderId={0}, VNPAY TranId={1},ResponseCode={2}", orderId,
                                // vnpayTranId, vnp_ResponseCode);
                                order.Status = 2;
                                Response.Redirect("../fontend/toanthanhthanhtoan.aspx?id=2");
                            }
                            returnContent = "{\"RspCode\":\"00\",\"Message\":\"Confirm Success\"}";
                            //Thêm code Thực hiện cập nhật vào Database
                            //Update Database
                        }
                        else
                        {
                            returnContent = "{\"RspCode\":\"02\",\"Message\":\"Order already confirmed\"}";
                        }
                    }
                    else
                    {
                        returnContent = "{\"RspCode\":\"01\",\"Message\":\"Order not found\"}";
                    }
                }
                else
                {
                    //   log.InfoFormat("Invalid signature, InputData={0}", Request.RawUrl);
                    returnContent = "{\"RspCode\":\"97\",\"Message\":\"Invalid signature\"}";
                }
            }
            else
            {
                returnContent = "{\"RspCode\":\"99\",\"Message\":\"Input data required\"}";
            }

            Response.ClearContent();
            Response.Write(returnContent);
            Response.End();
        }
Пример #6
0
        public async Task <IActionResult> StatusAsync()
        {
            string returnContent = string.Empty;

            if (Request.QueryString.Value.Length > 0)
            {
                string vnp_HashSecret = _configuration.GetSection("VNPayInfo").GetSection("vnp_HashSecret").Value; //Chuoi bi mat
                var    vnpayData      = Request.Query;
                //return Json(vnpayData);
                VnPayLibrary vnpay = new VnPayLibrary();
                if (vnpayData.Count > 0)
                {
                    foreach (var s in vnpayData)
                    {
                        //get all querystring data
                        if (!string.IsNullOrEmpty(s.Key) && s.Key.StartsWith("vnp_"))
                        {
                            vnpay.AddResponseData(s.Key, s.Value);
                        }
                    }
                }
                //Lay danh sach tham so tra ve tu VNPAY

                //vnp_TxnRef: Ma don hang merchant gui VNPAY tai command=pay
                string orderId = vnpay.GetResponseData("vnp_TxnRef");
                //vnp_TransactionNo: Ma GD tai he thong VNPAY
                long vnpayTranId = Convert.ToInt64(vnpay.GetResponseData("vnp_TransactionNo"));
                //vnp_ResponseCode:Response code from VNPAY: 00: Thanh cong, Khac 00: Xem tai lieu
                string vnp_ResponseCode = vnpay.GetResponseData("vnp_ResponseCode");
                //vnp_SecureHash: MD5 cua du lieu tra ve
                string vnp_SecureHash = vnpay.GetResponseData("vnp_SecureHash");
                bool   checkSignature = vnpay.ValidateSignature(vnp_SecureHash, vnp_HashSecret);
                if (checkSignature)
                {
                    //Cap nhat ket qua GD
                    //Yeu cau: Truy van vao CSDL cua  Merchant => lay ra duoc OrderInfo
                    //Giả sử OrderInfo lấy ra được như giả lập bên dưới
                    var order = await _context.OrderInfo
                                .FirstOrDefaultAsync(m => m.OrderId == orderId);

                    order.vnp_TransactionNo   = vnpayTranId;
                    order.vpn_TxnResponseCode = vnp_ResponseCode;
                    order.Status = 0; //0: Cho thanh toan,1: da thanh toan,2: GD loi
                                      //Kiem tra tinh trang Order
                    if (order != null)
                    {
                        if (order.Status == 0)
                        {
                            if (vnp_ResponseCode == "00")
                            {
                                //Thanh toan thanh cong
                                ViewData["Status"] = "Thanh toán thành công, OrderId=" + orderId + ", VNPAY TranId=" + vnpayTranId;
                                order.Status       = 1;
                            }
                            else
                            {
                                //Thanh toan khong thanh cong. Ma loi: vnp_ResponseCode
                                //  displayMsg.InnerText = "Có lỗi xảy ra trong quá trình xử lý.Mã lỗi: " + vnp_ResponseCode;
                                ViewData["Status"] = "Thanh toán lỗi, OrderId=" + orderId + ", VNPAY TranId=" + vnpayTranId + ",ResponseCode=" + vnp_ResponseCode;
                                order.Status       = 2;
                            }
                            returnContent = "{\"RspCode\":\"00\",\"Message\":\"Confirm Success\"}";
                            //Thêm code Thực hiện cập nhật vào Database
                            //Update Database
                        }
                        else
                        {
                            returnContent = "{\"RspCode\":\"02\",\"Message\":\"Order already confirmed\"}";
                        }
                        _context.Update(order);
                        await _context.SaveChangesAsync();
                    }
                    else
                    {
                        returnContent = "{\"RspCode\":\"01\",\"Message\":\"Order not found\"}";
                    }
                }
                else
                {
                    ViewData["Status"] = "Invalid signature";
                    returnContent      = "{\"RspCode\":\"97\",\"Message\":\"Invalid signature\"}";
                }
            }
            else
            {
                returnContent = "{\"RspCode\":\"99\",\"Message\":\"Input data required\"}";
            }

            //Response.ClearContent();
            //Response.Write(returnContent);
            //Response.End();
            return(View());
        }
Пример #7
0
        public ActionResult Index()
        {
            log.InfoFormat("Begin VNPAY Return, URL={0}", Request.RawUrl);
            if (Request.QueryString.Count > 0)
            {
                string       vnp_HashSecret = ConfigurationManager.AppSettings["vnp_HashSecret"]; //Chuoi bi mat
                var          vnpayData      = Request.QueryString;
                VnPayLibrary vnpay          = new VnPayLibrary();
                //if (vnpayData.Count > 0)
                //{
                foreach (string s in vnpayData)
                {
                    //get all querystring data
                    if (!string.IsNullOrEmpty(s) && s.StartsWith("vnp_"))
                    {
                        vnpay.AddResponseData(s, vnpayData[s]);
                    }
                }
                // }

                //vnp_TxnRef: Ma don hang merchant gui VNPAY tai command=pay
                long orderId = Convert.ToInt64(vnpay.GetResponseData("vnp_TxnRef"));
                //vnp_TransactionNo: Ma GD tai he thong VNPAY
                long vnpayTranId = Convert.ToInt64(vnpay.GetResponseData("vnp_TransactionNo"));
                //vnp_ResponseCode:Response code from VNPAY: 00: Thanh cong, Khac 00: Xem tai lieu
                string vnp_ResponseCode = vnpay.GetResponseData("vnp_ResponseCode");
                //vnp_SecureHash: MD5 cua du lieu tra ve
                String vnp_SecureHash = Request.QueryString["vnp_SecureHash"];
                bool   checkSignature = vnpay.ValidateSignature(vnp_SecureHash, vnp_HashSecret);
                if (checkSignature)
                {
                    if (vnp_ResponseCode == "00")
                    {
                        //Thanh toan thanh cong
                        var id   = "";
                        var idDH = "";
                        var cart = (List <CartModel>)Session[CartSession.CartSesstion];
                        var info = (InfoOrderModel)Session[CartSession.OrderSesstion];
                        if (info.id == null)
                        {
                            id = new UserDao().CreateIDAuto("KH");
                            KHACHHANG cus = new KHACHHANG()
                            {
                                MAKHACHHANG  = id,
                                TENKHACHHANG = info.Name,
                                HOKHACHHANG  = "Temp",
                                DIENTHOAI    = info.PhoneNumber,
                                DIACHI       = info.Address,
                                EMAIL        = info.Email,
                                TRANGTHAI    = 0
                            };
                            var result = new UserDao().Insert(cus);
                        }
                        else
                        {
                            id = info.id;
                        }
                        idDH = new SanPhamDao().IdDonHangAuto("DH");
                        var order = new DONHANG()
                        {
                            MAHOADON              = idDH,
                            MAKHACHHANG           = id,
                            NGAYLAP               = DateTime.Now,
                            NGAYCAPNHAT           = DateTime.Now,
                            MAPHUONGTHUCTHANHTOAN = "2",
                            TRANGTHAI             = 0,
                            GHICHU = "Thanh toán qua VNPay",
                        };
                        var a = new SanPhamDao().InsertDonHang(order);

                        foreach (var item in cart)
                        {
                            var detailorder = new CHITIETDONHANG()
                            {
                                MAHOADON  = idDH,
                                MASANPHAM = item.SANPHAM.MASANPHAM,
                                SOLUONG   = item.SOLUONG,
                                THANHTIEN = item.SANPHAM.GIABAN
                            };
                            int res = new SanPhamDao().InsertCTDonHang(detailorder);
                        }
                        //Gửi mail
                        string smtpUserName = "******";
                        string smtpPassword = "******";
                        string smtpHost     = "smtp.gmail.com";
                        int    smtpPort     = 587;

                        string emailTo = info.Email;
                        string subject = "Đơn hàng vừa mua";
                        string body    = string.Format("Bạn vừa nhận được liên hê từ: <b>{0}</b><br/>Email: {1}<br/>Cảm ơn bạn đã mua hàng tại website Fahasa.<br/> Mã đơn hàng của bạn là: " + idDH + ".<br/>Dùng mã đơn hàng để tra cứu đơn hàng trực tiếp trên website. <br/>Đơn hàng của bạn đang được xử lý.", "Admin ", "");

                        EmailService service = new EmailService();
                        bool         kq      = service.Send(smtpUserName, smtpPassword, smtpHost, smtpPort, emailTo, subject, body);
                        Session[CartSession.CartSesstion] = null;


                        ViewBag.Message = "Thanh toán thành công";
                        log.InfoFormat("Thanh toan thanh cong, OrderId={0}, VNPAY TranId={1}", orderId, vnpayTranId);

                        return(RedirectToAction("OrderSuccess", "Cart", new { id = idDH }));
                    }
                    else
                    {
                        //Thanh toan khong thanh cong. Ma loi: vnp_ResponseCode
                        ViewBag.Message = "Có lỗi xảy ra trong quá trình xử lý.Mã lỗi: " + vnp_ResponseCode;
                        log.InfoFormat("Thanh toan loi, OrderId={0}, VNPAY TranId={1},ResponseCode={2}", orderId, vnpayTranId, vnp_ResponseCode);
                    }
                }
                else
                {
                    log.InfoFormat("Invalid signature, InputData={0}", Request.RawUrl);
                    ViewBag.Message = "Có lỗi xảy ra trong quá trình xử lý";
                }
            }


            return(RedirectToAction("Index", "Home"));
        }
Пример #8
0
        public async Task <bool> VnPaySuccess()
        {
            if (Request.QueryString.Count > 0 && Request.QueryString["vnp_SecureHash"] != null)
            {
                string       vnp_HashSecret = "XAUJIMFNKYUUWWNWOLLNIHJCUGLOIGEF"; //Secret key
                var          vnpayData      = Request.QueryString;
                VnPayLibrary vnpay          = new VnPayLibrary();

                foreach (string s in vnpayData)
                {
                    //get all querystring data
                    if (!string.IsNullOrEmpty(s) && s.StartsWith("vnp_"))
                    {
                        vnpay.AddResponseData(s, vnpayData[s]);
                    }
                }
                //Lay danh sach tham so tra ve tu VNPAY
                var    UserManager      = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(db));
                string orderId          = vnpay.GetResponseData("vnp_TxnRef");
                string BankCode         = vnpay.GetResponseData("vnp_BankCode");
                string vnp_ResponseCode = vnpay.GetResponseData("vnp_ResponseCode");
                String vnp_SecureHash   = Request.QueryString["vnp_SecureHash"];
                bool   checkSignature   = vnpay.ValidateSignature(vnp_SecureHash, vnp_HashSecret);

                if (checkSignature)
                {
                    //Cap nhat ket qua GD
                    OrderInfo order = db.OrderInfos.Find(orderId);
                    if (order != null)
                    {
                        if (order.Status == (int)OrderStatus.Pending)
                        {
                            if (vnp_ResponseCode == "00")
                            {
                                //Thanh toan thanh cong
                                order.Status   = (int)OrderStatus.Paid;
                                order.BankCode = BankCode;
                                db.OrderInfos.AddOrUpdate(order);
                                if (User.Identity.IsAuthenticated)
                                {
                                    //Luu membership
                                    var listMemberType = db.Members.ToList();
                                    var memberShip     = new Membership();
                                    foreach (var memberType in listMemberType)
                                    {
                                        if (order.Amount == memberType.Price && order.OrderDescription == memberType.MemberType)
                                        {
                                            memberShip.Member = memberType;
                                        }
                                    }
                                    var id = User.Identity.GetUserId();
                                    memberShip.ApplicationUser = UserManager.FindById(id);
                                    memberShip.CreatedAt       = DateTime.Now;
                                    db.Memberships.Add(memberShip);
                                    //Add role member:
                                    UserManager.AddToRole(id, memberShip.Member.RoleName);
                                }
                                db.SaveChanges();
                                return(true);
                            }
                            else
                            {
                                //Thanh toan khong thanh cong. Ma loi: vnp_ResponseCode
                                order.Status = (int)OrderStatus.Error;
                                db.OrderInfos.AddOrUpdate(order);
                                db.SaveChanges();
                                return(false);
                            }
                        }
                    }
                }
            }
            return(false);
        }