public ActionResult ThanhToanOnline(int maDH)
        {
            HoaDon hd = db.HoaDon.Find(maDH);
            //Get Config Info
            string vnp_Returnurl  = ConfigurationManager.AppSettings["vnp_Returnurl"];  //URL nhan ket qua tra ve
            string vnp_Url        = ConfigurationManager.AppSettings["vnp_Url"];        //URL thanh toan cua VNPAY
            string vnp_TmnCode    = ConfigurationManager.AppSettings["vnp_TmnCode"];    //Ma website
            string vnp_HashSecret = ConfigurationManager.AppSettings["vnp_HashSecret"]; //Chuoi bi mat

            //Get payment input
            OrderInfo orderInfo = new OrderInfo();

            //Save order to db
            orderInfo.OrderId          = hd.MaDonHang;
            orderInfo.Amount           = Convert.ToDecimal(hd.TongTien);
            orderInfo.OrderDescription = hd.DiaChi;
            orderInfo.CreatedDate      = DateTime.Now;

            //Build URL for VNPAY
            VnPayLibrary vnpay = new VnPayLibrary();

            vnpay.AddRequestData("vnp_Version", "2.0.0");
            vnpay.AddRequestData("vnp_Command", "pay");
            vnpay.AddRequestData("vnp_TmnCode", vnp_TmnCode);

            string locale = "vn";

            if (!string.IsNullOrEmpty(locale))
            {
                vnpay.AddRequestData("vnp_Locale", locale);
            }
            else
            {
                vnpay.AddRequestData("vnp_Locale", "vn");
            }

            vnpay.AddRequestData("vnp_CurrCode", "VND");
            vnpay.AddRequestData("vnp_TxnRef", orderInfo.OrderId.ToString());
            vnpay.AddRequestData("vnp_OrderId", hd.MaDonHang.ToString());
            vnpay.AddRequestData("vnp_OrderInfo", hd.MaDonHang.ToString());
            vnpay.AddRequestData("vnp_OrderType", "other"); //default value: other
            vnpay.AddRequestData("vnp_Amount", Math.Round(orderInfo.Amount * 100).ToString());
            vnpay.AddRequestData("vnp_ReturnUrl", vnp_Returnurl);
            vnpay.AddRequestData("vnp_IpAddr", Utils.GetIpAddress());
            vnpay.AddRequestData("vnp_CreateDate", orderInfo.CreatedDate.ToString("yyyyMMddHHmmss"));

            //if (bank.SelectedItem != null && !string.IsNullOrEmpty(bank.SelectedItem.Value))
            //{
            vnpay.AddRequestData("vnp_BankCode", "NCB");
            //}

            string paymentUrl = vnpay.CreateRequestUrl(vnp_Url, vnp_HashSecret);

            Debug.WriteLine("VNPAY URL: {0}", paymentUrl);
            Session["cart"] = new List <Item>();
            return(Redirect(paymentUrl));
            //return RedirectToAction("Success");
        }
Example #2
0
        // private static readonly ILog log =
        //    LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        protected void Page_Load(object sender, EventArgs e)
        {
            //Get Config Info
            string vnp_Returnurl  = ConfigurationManager.AppSettings["vnp_Returnurl"];  //URL nhan ket qua tra ve
            string vnp_Url        = ConfigurationManager.AppSettings["vnp_Url"];        //URL thanh toan cua VNPAY
            string vnp_TmnCode    = ConfigurationManager.AppSettings["vnp_TmnCode"];    //Ma website
            string vnp_HashSecret = ConfigurationManager.AppSettings["vnp_HashSecret"]; //Chuoi bi mat

            //Get payment input
            OrderInfo order = new OrderInfo();

            //Save order to db
            order.OrderId          = DateTime.Now.Ticks;
            order.Amount           = Convert.ToDecimal(Request.QueryString["Amount"]);
            order.OrderDescription = Request.QueryString["OrderDescription"];
            order.CreatedDate      = DateTime.Now;

            //Build URL for VNPAY
            VnPayLibrary vnpay = new VnPayLibrary();

            vnpay.AddRequestData("vnp_Version", "2.0.0");
            vnpay.AddRequestData("vnp_Command", "pay");
            vnpay.AddRequestData("vnp_TmnCode", vnp_TmnCode);

            string locale = "vn";//"en"

            if (!string.IsNullOrEmpty(locale))
            {
                vnpay.AddRequestData("vnp_Locale", locale);
            }
            else
            {
                vnpay.AddRequestData("vnp_Locale", "vn");
            }

            vnpay.AddRequestData("vnp_CurrCode", "VND");
            vnpay.AddRequestData("vnp_TxnRef", order.OrderId.ToString());
            vnpay.AddRequestData("vnp_OrderInfo", order.OrderDescription);
            vnpay.AddRequestData("vnp_OrderType", "insurance"); //default value: other
            vnpay.AddRequestData("vnp_Amount", (order.Amount * 100).ToString());
            vnpay.AddRequestData("vnp_ReturnUrl", vnp_Returnurl);
            vnpay.AddRequestData("vnp_IpAddr", GetIpAddress());
            vnpay.AddRequestData("vnp_CreateDate", order.CreatedDate.ToString("yyyyMMddHHmmss"));
            //if (bank.SelectedItem != null && !string.IsNullOrEmpty(bank.SelectedItem.Value))
            //{
            //    vnpay.AddRequestData("vnp_BankCode", bank.SelectedItem.Value);
            //}
            string paymentUrl = vnpay.CreateRequestUrl(vnp_Url, vnp_HashSecret);

            //log.InfoFormat("VNPAY URL: {0}", paymentUrl);

            Response.Clear();
            Response.Write("{\"code\":\"00\",\"Message\":\"Confirm Success\",\"data\":\"" + paymentUrl + "\"}");

            Response.End();
        }
Example #3
0
        protected void btnPay_Click(object sender, EventArgs e)
        {
            //Get Config Info
            string vnp_Returnurl  = ConfigurationManager.AppSettings["vnp_Returnurl"];  //URL nhan ket qua tra ve
            string vnp_Url        = ConfigurationManager.AppSettings["vnp_Url"];        //URL thanh toan cua VNPAY
            string vnp_TmnCode    = ConfigurationManager.AppSettings["vnp_TmnCode"];    //Ma website
            string vnp_HashSecret = ConfigurationManager.AppSettings["vnp_HashSecret"]; //Chuoi bi mat

            //Get payment input
            // OrderInfo order = new OrderInfo();
            Tour      tour  = new Tour();
            OrderInfo order = new OrderInfo();

            //Save order to db
            order.OrderId          = DateTime.Now.Ticks;
            order.Amount           = Convert.ToDecimal(Amount.Text);
            order.OrderDescription = OrderDescription.Text;
            order.CreatedDate      = DateTime.Now;

            //Build URL for VNPAY
            VnPayLibrary vnpay = new VnPayLibrary();

            vnpay.AddRequestData("vnp_Version", "2.0.0");
            vnpay.AddRequestData("vnp_Command", "pay");
            vnpay.AddRequestData("vnp_TmnCode", vnp_TmnCode);

            string locale = language.SelectedItem.Value;

            if (!string.IsNullOrEmpty(locale))
            {
                vnpay.AddRequestData("vnp_Locale", locale);
            }
            else
            {
                vnpay.AddRequestData("vnp_Locale", "vn");
            }

            vnpay.AddRequestData("vnp_CurrCode", "VND");
            vnpay.AddRequestData("vnp_TxnRef", order.OrderId.ToString());
            vnpay.AddRequestData("vnp_OrderInfo", order.OrderDescription);
            vnpay.AddRequestData("vnp_OrderType", orderCategory.SelectedItem.Value); //default value: other
            vnpay.AddRequestData("vnp_Amount", (order.Amount * 100).ToString());
            vnpay.AddRequestData("vnp_ReturnUrl", vnp_Returnurl);
            vnpay.AddRequestData("vnp_IpAddr", Utils.GetIpAddress());
            vnpay.AddRequestData("vnp_CreateDate", order.CreatedDate.ToString("yyyyMMddHHmmss"));

            if (bank.SelectedItem != null && !string.IsNullOrEmpty(bank.SelectedItem.Value))
            {
                vnpay.AddRequestData("vnp_BankCode", bank.SelectedItem.Value);
            }

            string paymentUrl = vnpay.CreateRequestUrl(vnp_Url, vnp_HashSecret);

            //  log.InfoFormat("VNPAY URL: {0}", paymentUrl);
            Response.Redirect(paymentUrl);
        }
Example #4
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"));
        }
Example #5
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());
        }
Example #6
0
        public IActionResult ShopOnline(OrderInfo orderInfo)
        {
            // Console.WriteLine(orderInfo.bank);
            //Get Config Info
            string vnp_Returnurl = _vnpay.vnp_Returnurl; //URL nhan ket qua tra ve 
            string vnp_Url = _vnpay.vnp_Url; //URL thanh toan cua VNPAY 
            string vnp_TmnCode = _vnpay.vnp_TmnCode; //Ma website
            string vnp_HashSecret = _vnpay.vnp_HashSecret; //Chuoi bi mat

            //Get payment input
            OrderInfo order = new OrderInfo();
            //Save order to db
            order.OrderId = DateTime.Now.Ticks;
            order.Amount = Convert.ToDecimal(orderInfo.Amount);
            order.OrderDescription = orderInfo.OrderDescription;
            order.CreatedDate = DateTime.Now;

            //Build URL for VNPAY
            VnPayLibrary vnpay = new VnPayLibrary();

            vnpay.AddRequestData("vnp_Version", "2.0.0");
            vnpay.AddRequestData("vnp_Command", "pay");
            vnpay.AddRequestData("vnp_TmnCode", vnp_TmnCode);

            string locale = orderInfo.language;
            if (!string.IsNullOrEmpty(locale))
            {
                vnpay.AddRequestData("vnp_Locale", locale);
            }
            else
            {
                vnpay.AddRequestData("vnp_Locale", "vn");
            }
            Utils utils = new Utils(_httpContextAccessor);
            vnpay.AddRequestData("vnp_CurrCode", "VND");
            vnpay.AddRequestData("vnp_TxnRef", order.OrderId.ToString());
            vnpay.AddRequestData("vnp_OrderInfo", order.OrderDescription);
            vnpay.AddRequestData("vnp_OrderType", orderInfo.OrderCatory); //default value: other
            vnpay.AddRequestData("vnp_Amount", (order.Amount * 100).ToString());
            vnpay.AddRequestData("vnp_ReturnUrl", vnp_Returnurl);
            vnpay.AddRequestData("vnp_IpAddr", utils.GetIpAddress());
            vnpay.AddRequestData("vnp_CreateDate", order.CreatedDate.ToString("yyyyMMddHHmmss"));

            if (orderInfo.bank != null && !string.IsNullOrEmpty(orderInfo.bank))
            {
                vnpay.AddRequestData("vnp_BankCode", orderInfo.bank);
            }

            string paymentUrl = vnpay.CreateRequestUrl(vnp_Url, vnp_HashSecret);
            log.InfoFormat("VNPAY URL: {0}", paymentUrl);
            Response.Redirect(paymentUrl);
            return View();
        }
Example #7
0
        public ActionResult Checkout(CheckoutViewModel model)
        {
            string vnp_Returnurl  = ConfigurationManager.AppSettings["vnp_Returnurl"];  //URL nhan ket qua tra ve
            string vnp_Url        = ConfigurationManager.AppSettings["vnp_Url"];        //URL thanh toan cua VNPAY
            string vnp_TmnCode    = ConfigurationManager.AppSettings["vnp_TmnCode"];    //Ma website
            string vnp_HashSecret = ConfigurationManager.AppSettings["vnp_HashSecret"]; //Chuoi bi mat

            //Get payment input
            OrderInfo order = new OrderInfo();

            //Save order to db
            order.OrderId          = DateTime.Now.Ticks;
            order.Amount           = Convert.ToDecimal(model.Amount);
            order.OrderDescription = model.OrderDescription;
            order.CreatedDate      = DateTime.Now;

            //Build URL for VNPAY
            VnPayLibrary vnpay = new VnPayLibrary();

            vnpay.AddRequestData("vnp_Version", "2.0.0");
            vnpay.AddRequestData("vnp_Command", "pay");
            vnpay.AddRequestData("vnp_TmnCode", vnp_TmnCode);

            string locale = "vn";

            if (!string.IsNullOrEmpty(locale))
            {
                vnpay.AddRequestData("vnp_Locale", locale);
            }
            else
            {
                vnpay.AddRequestData("vnp_Locale", "vn");
            }

            vnpay.AddRequestData("vnp_CurrCode", "VND");
            vnpay.AddRequestData("vnp_TxnRef", order.OrderId.ToString());
            vnpay.AddRequestData("vnp_OrderInfo", order.OrderDescription);
            vnpay.AddRequestData("vnp_OrderType", model.OrderCategory); //default value: other
            vnpay.AddRequestData("vnp_Amount", (order.Amount * 100).ToString());
            vnpay.AddRequestData("vnp_ReturnUrl", vnp_Returnurl);
            vnpay.AddRequestData("vnp_IpAddr", Utils.GetIpAddress());
            vnpay.AddRequestData("vnp_CreateDate", order.CreatedDate.ToString("yyyyMMddHHmmss"));

            if (model.Bank != null && !string.IsNullOrEmpty(model.Bank))
            {
                vnpay.AddRequestData("vnp_BankCode", model.Bank);
            }

            string paymentUrl = vnpay.CreateRequestUrl(vnp_Url, vnp_HashSecret);

            log.InfoFormat("VNPAY URL: {0}", paymentUrl);
            return(Redirect(paymentUrl));
        }
        public void thanhToan(int id, int tien_, string bank)
        {
            //Get Config Info
            string vnp_Returnurl  = ConfigurationManager.AppSettings["vnp_Returnurl"];  //URL nhan ket qua tra ve
            string vnp_Url        = ConfigurationManager.AppSettings["vnp_Url"];        //URL thanh toan cua VNPAY
            string vnp_TmnCode    = ConfigurationManager.AppSettings["vnp_TmnCode"];    //Ma website
            string vnp_HashSecret = ConfigurationManager.AppSettings["vnp_HashSecret"]; //Chuoi bi mat



            // Debug.WriteLine(Convert.ToInt32(tienThanhToan_));

            int maThanhToan = donDatTourController.themGiaoDich(id, tien_);

            if (maThanhToan != 0)
            {
                //Build URL for VNPAY
                VnPayLibrary vnpay = new VnPayLibrary();

                vnpay.AddRequestData("vnp_Version", "2.0.0");
                vnpay.AddRequestData("vnp_Command", "pay");
                vnpay.AddRequestData("vnp_TmnCode", vnp_TmnCode);
                vnpay.AddRequestData("vnp_Locale", "vn");
                vnpay.AddRequestData("vnp_CurrCode", "VND");
                vnpay.AddRequestData("vnp_TxnRef", maThanhToan.ToString());
                vnpay.AddRequestData("vnp_OrderInfo", "ghi chu");
                vnpay.AddRequestData("vnp_OrderType", "other");     //default value: other
                vnpay.AddRequestData("vnp_Amount", (tien_ * 100).ToString());
                vnpay.AddRequestData("vnp_ReturnUrl", vnp_Returnurl);
                vnpay.AddRequestData("vnp_IpAddr", Utils.GetIpAddress());
                vnpay.AddRequestData("vnp_CreateDate", DateTime.Now.ToString("yyyyMMddHHmmss"));


                vnpay.AddRequestData("vnp_BankCode", bank);


                string paymentUrl = vnpay.CreateRequestUrl(vnp_Url, vnp_HashSecret);
                //  log.InfoFormat("VNPAY URL: {0}", paymentUrl);
                Debug.WriteLine(paymentUrl);
                Response.Redirect(paymentUrl);

                Debug.WriteLine("Dat TOur thanh Cong.");
            }
            else
            {
                Debug.WriteLine("Dat Tour THat Bai");
            }
        }
Example #9
0
        public string GetUrl(int AppId)
        {
            //Get Config Info

            //Get payment input
            BuyPackageHistory order = cnn.BuyPackageHistories.Find(AppId);
            //Save order to db

            //Build URL for VNPAY
            VnPayLibrary vnpay = new VnPayLibrary();

            vnpay.AddRequestData("vnp_Version", "2.0.0");
            vnpay.AddRequestData("vnp_Command", "pay");
            vnpay.AddRequestData("vnp_TmnCode", SystemParam.vnp_TmnCode);

            string locale = "vn";//"en"

            if (!string.IsNullOrEmpty(locale))
            {
                vnpay.AddRequestData("vnp_Locale", locale);
            }
            else
            {
                vnpay.AddRequestData("vnp_Locale", "vn");
            }

            vnpay.AddRequestData("vnp_CurrCode", "VND");
            vnpay.AddRequestData("vnp_TxnRef", order.ID.ToString());
            vnpay.AddRequestData("vnp_OrderInfo", order.ServicePackage.PackageName);
            vnpay.AddRequestData("vnp_OrderType", "insurance"); //default value: other
            vnpay.AddRequestData("vnp_Amount", (order.Price * 100).ToString());
            vnpay.AddRequestData("vnp_ReturnUrl", SystemParam.vnp_Return_url);
            vnpay.AddRequestData("vnp_IpAddr", GetIpAddress());
            vnpay.AddRequestData("vnp_CreateDate", DateTime.Now.ToString("yyyyMMddHHmmss"));
            //if (bank.SelectedItem != null && !string.IsNullOrEmpty(bank.SelectedItem.Value))
            //{
            //    vnpay.AddRequestData("vnp_BankCode", bank.SelectedItem.Value);
            //}

            string paymentUrl = vnpay.CreateRequestUrl(SystemParam.vnp_Url, SystemParam.vnp_HashSecret);

            return(paymentUrl);
        }
Example #10
0
        public string paymentOrder(OrderInfor orderInfor)
        {
            //Get Config Info
            string vnp_Returnurl  = "https://vnpay.vn/";                                 //URL nhan ket qua tra ve
            string vnp_Url        = "http://sandbox.vnpayment.vn/paymentv2/vpcpay.html"; //URL thanh toan cua VNPAY
            string vnp_TmnCode    = "52HMR9SZ";                                          //Ma website
            string vnp_HashSecret = "NAQYDDNIAKILYBXEAJBGBFCOPZTXLUYC";                  //Chuoi bi mat

            //Build URL for VNPAY
            VnPayLibrary vnpay = new VnPayLibrary();

            vnpay.AddRequestData("vnp_Version", "2.0.0");
            vnpay.AddRequestData("vnp_Command", "pay");
            vnpay.AddRequestData("vnp_TmnCode", vnp_TmnCode);

            string locale = "vn";

            if (!string.IsNullOrEmpty(locale))
            {
                vnpay.AddRequestData("vnp_Locale", locale);
            }
            else
            {
                vnpay.AddRequestData("vnp_Locale", "vn");
            }

            vnpay.AddRequestData("vnp_CurrCode", "VND");
            vnpay.AddRequestData("vnp_TxnRef", orderInfor.OrderId.ToString()); //Mã tham chiếu của giao dịch tại hệ thống của merchant. Mã này là duy nhất đùng để phân biệt các đơn hàng gửi sang VNPAY. Không được trùng lặp trong ngày.
            vnpay.AddRequestData("vnp_OrderInfo", "THANHTOAN");
            vnpay.AddRequestData("vnp_OrderType", "130000");                   //default value: other
            vnpay.AddRequestData("vnp_Amount", (orderInfor.Amount * 100).ToString());
            vnpay.AddRequestData("vnp_ReturnUrl", vnp_Returnurl);
            vnpay.AddRequestData("vnp_IpAddr", Utils.GetIpAddress());
            vnpay.AddRequestData("vnp_CreateDate", DateTime.Now.ToString("yyyyMMddHHmmss"));
            vnpay.AddRequestData("vnp_BankCode", "NCB");

            string paymentUrl = vnpay.CreateRequestUrl(vnp_Url, vnp_HashSecret);

            return(paymentUrl);
        }
        //string menhgia,string moblie,string nhamang,string type
        public ActionResult RePay(string moblie, string id)
        {
            var id_order     = Int32.Parse(Request["id"]);
            var nhamang      = Request["nhamang"];
            var type         = Request["type"];
            var menhgia      = Convert.ToInt32(Request["menhgia"]);
            var valueMenhgia = db.ShowDenomination().Find(c => c.ID == menhgia);
            var sdt          = Int32.Parse(moblie);

            InforOrder inforOrder = new InforOrder();

            inforOrder.phone        = sdt;
            inforOrder.denomination = valueMenhgia.ID;
            inforOrder.network      = nhamang;
            inforOrder.CardType     = type;
            inforOrder.id_order     = id_order;

            Session["InforOrder"] = inforOrder;

            ViewBag.mobile  = sdt;
            ViewBag.menhgia = Request["menhgia"];

            ViewBag.valueMenhgia = valueMenhgia;
            ViewBag.nhamang      = Request["nhamang"];
            ViewBag.type         = Request["type"];

            string vnp_Returnurl  = ConfigurationManager.AppSettings["vnp_Returnurl"];  //URL nhan ket qua tra ve
            string vnp_Url        = ConfigurationManager.AppSettings["vnp_Url"];        //URL thanh toan cua VNPAY
            string vnp_TmnCode    = ConfigurationManager.AppSettings["vnp_TmnCode"];    //Ma website
            string vnp_HashSecret = ConfigurationManager.AppSettings["vnp_HashSecret"]; //Chuoi bi mat

            //Get payment input
            OrderInfo order = new OrderInfo();

            order.OrderId          = DateTime.Now.Ticks;
            order.Phone            = Convert.ToInt32(moblie);
            order.Amount           = Convert.ToInt32(valueMenhgia.Price);
            order.OrderDescription = "aloalo thanh toan";
            order.CreatedDate      = DateTime.Now;


            //Build URL for VNPAY
            VnPayLibrary vnpay = new VnPayLibrary();

            vnpay.AddRequestData("vnp_Version", "2.0.0");
            vnpay.AddRequestData("vnp_Command", "pay");
            vnpay.AddRequestData("vnp_TmnCode", vnp_TmnCode);

            string locale = "vn";//"en"

            if (!string.IsNullOrEmpty(locale))
            {
                vnpay.AddRequestData("vnp_Locale", locale);
            }
            else
            {
                vnpay.AddRequestData("vnp_Locale", "vn");
            }

            vnpay.AddRequestData("vnp_CurrCode", "VND");
            vnpay.AddRequestData("vnp_TxnRef", order.OrderId.ToString());
            vnpay.AddRequestData("vnp_Phone", order.Phone.ToString());
            vnpay.AddRequestData("vnp_OrderInfo", order.OrderDescription);
            vnpay.AddRequestData("vnp_OrderType", "insurance"); //default value: other
            vnpay.AddRequestData("vnp_Amount", (order.Amount * 100).ToString());
            vnpay.AddRequestData("vnp_ReturnUrl", vnp_Returnurl);
            vnpay.AddRequestData("vnp_IpAddr", GetIpAddress());
            vnpay.AddRequestData("vnp_CreateDate", order.CreatedDate.ToString("yyyyMMddHHmmss"));
            string paymentUrl = vnpay.CreateRequestUrl(vnp_Url, vnp_HashSecret);

            ViewBag.demoUrl = paymentUrl;
            return(View());
        }
Example #12
0
        protected void btnDatVe_Click(object sender, EventArgs e)
        {
            if (tour.Value != null && maTG.Value != null && iNL.Value != null && iTE.Value != null)
            {
                int i = Convert.ToInt32(tourController.kiemTraSoChoCon(tour.Value, maTG.Value));
                int s = Convert.ToInt32(iTE.Value);
                Debug.WriteLine("idso " + i + "  " + (Convert.ToInt32(iNL.Value) + Convert.ToInt32(iTE.Value)));
                if (i >= (Convert.ToInt32(iNL.Value) + Convert.ToInt32(iTE.Value)))
                {
                    //Get Config Info
                    string vnp_Returnurl  = ConfigurationManager.AppSettings["vnp_Returnurl"];  //URL nhan ket qua tra ve
                    string vnp_Url        = ConfigurationManager.AppSettings["vnp_Url"];        //URL thanh toan cua VNPAY
                    string vnp_TmnCode    = ConfigurationManager.AppSettings["vnp_TmnCode"];    //Ma website
                    string vnp_HashSecret = ConfigurationManager.AppSettings["vnp_HashSecret"]; //Chuoi bi mat


                    if (!phanTramDat.Text.Equals("none"))

                    {
                        // Debug.WriteLine(Convert.ToInt32(tienThanhToan_));
                        DonDatTour donDatTour = new DonDatTour();
                        donDatTour.ChoNL           = Convert.ToInt32(iNL.Value);
                        donDatTour.ChoTE           = Convert.ToInt32(iTE.Value);
                        donDatTour.MaTour          = Convert.ToInt32(tour.Value);
                        donDatTour.GhiChu          = txtGhiChu.Text;
                        donDatTour.NgayDat         = DateTime.Now;                   //DateTime.UtcNow.Date;
                        donDatTour.TienDaThanhToan = Convert.ToInt32(tien_tt.Value); //tienThanhToan_(tour.Value.ToString(), Convert.ToInt32(iTE.Value), Convert.ToInt32(iNL.Value));
                        donDatTour.MaNgaydi        = Convert.ToInt32(maTG.Value);
                        donDatTour.TrangThai       = 0;
                        donDatTour.MaKH            = Convert.ToInt32(Session["maKH"].ToString());
                        float phantram = (float)Convert.ToDouble(phanTramDat.SelectedValue);
                        float tien_1   = Convert.ToInt32(tien_tt.Value) * phantram;
                        int   tien_    = Convert.ToInt32(tien_1);
                        Debug.WriteLine(Convert.ToInt32(tien_tt.Value) + "  tien " + tien_1 + " ma thoi gian : " + maTG.Value);
                        int maThanhToan = datTourController.themDonDatTour(donDatTour, tien_);
                        if (maThanhToan != 0)
                        {
                            //Build URL for VNPAY
                            VnPayLibrary vnpay = new VnPayLibrary();

                            vnpay.AddRequestData("vnp_Version", "2.0.0");
                            vnpay.AddRequestData("vnp_Command", "pay");
                            vnpay.AddRequestData("vnp_TmnCode", vnp_TmnCode);
                            vnpay.AddRequestData("vnp_Locale", "vn");
                            vnpay.AddRequestData("vnp_CurrCode", "VND");
                            vnpay.AddRequestData("vnp_TxnRef", maThanhToan.ToString());
                            vnpay.AddRequestData("vnp_OrderInfo", "ghi chu");
                            vnpay.AddRequestData("vnp_OrderType", "other"); //default value: other
                            vnpay.AddRequestData("vnp_Amount", (tien_ * 100).ToString());
                            vnpay.AddRequestData("vnp_ReturnUrl", vnp_Returnurl);
                            vnpay.AddRequestData("vnp_IpAddr", Utils.GetIpAddress());
                            vnpay.AddRequestData("vnp_CreateDate", DateTime.Now.ToString("yyyyMMddHHmmss"));

                            if (bank.SelectedItem != null && !string.IsNullOrEmpty(bank.SelectedItem.Value))
                            {
                                vnpay.AddRequestData("vnp_BankCode", bank.SelectedItem.Value);
                                Debug.WriteLine("bank " + bank.SelectedItem.Value);
                            }

                            string paymentUrl = vnpay.CreateRequestUrl(vnp_Url, vnp_HashSecret);
                            //  log.InfoFormat("VNPAY URL: {0}", paymentUrl);
                            Debug.WriteLine(paymentUrl);
                            Response.Redirect(paymentUrl);

                            Debug.WriteLine("Dat TOur thanh Cong.");
                        }
                        else
                        {
                            Debug.WriteLine("Dat Tour THat Bai");
                        }
                    }
                }
                else
                {
                    Response.Redirect("loi.aspx?id=0");
                }
            }
            else
            {
                Response.Redirect("loi.aspx?id=1");
            }
        }
        public ActionResult PaymentByVNPay()
        {
            try
            {
                //Get Config Info
                //string vnp_Returnurl = ConfigurationManager.AppSettings["/VNPay/Index"]; //URL nhan ket qua tra ve
                //string vnp_Url = ConfigurationManager.AppSettings["http://sandbox.vnpayment.vn/paymentv2/vpcpay.html"]; //URL thanh toan cua VNPAY
                //string vnp_TmnCode = ConfigurationManager.AppSettings["V44NHFT4"]; //Ma website
                //string vnp_HashSecret = ConfigurationManager.AppSettings["YXYUPGHVVOYZGQQBUBUJCLSEUMIUPMKI"]; //Chuoi bi mat

                string vnp_Returnurl  = ConfigurationManager.AppSettings["vnp_Returnurl"];  //URL nhan ket qua tra ve
                string vnp_Url        = ConfigurationManager.AppSettings["vnp_Url"];        //URL thanh toan cua VNPAY
                string vnp_TmnCode    = ConfigurationManager.AppSettings["vnp_TmnCode"];    //Ma website
                string vnp_HashSecret = ConfigurationManager.AppSettings["vnp_HashSecret"]; //Chuoi bi mat
                if (string.IsNullOrEmpty(vnp_TmnCode) || string.IsNullOrEmpty(vnp_HashSecret))
                {
                    //lblMessage.Text = "Vui lòng cấu hình các tham số: vnp_TmnCode,vnp_HashSecret trong file web.config";
                    //return;
                }
                //Get payment input
                var     cart   = (List <CartModel>)Session[CartSession.CartSesstion];
                Decimal Amount = 0;
                foreach (var item in cart)
                {
                    Amount += item.SOLUONG * item.SANPHAM.GIABAN;
                }
                if (Amount < 300000)
                {
                    Amount += 30000;
                }
                OrderInfo order = new OrderInfo();
                //Save order to db
                order.OrderId          = DateTime.Now.Ticks;
                order.Amount           = Convert.ToInt64(Amount);
                order.OrderDescription = "abc";
                order.CreatedDate      = DateTime.Now;
                //string locale = cboLanguage.SelectedItem.Value;
                //Build URL for VNPAY
                VnPayLibrary vnpay = new VnPayLibrary();

                vnpay.AddRequestData("vnp_Version", "2.0.0");
                vnpay.AddRequestData("vnp_Command", "pay");
                vnpay.AddRequestData("vnp_TmnCode", vnp_TmnCode);
                vnpay.AddRequestData("vnp_Amount", (order.Amount * 100).ToString());
                //if (cboBankCode.SelectedItem != null && !string.IsNullOrEmpty(cboBankCode.SelectedItem.Value))
                //{
                //    vnpay.AddRequestData("vnp_BankCode", cboBankCode.SelectedItem.Value);
                //}
                vnpay.AddRequestData("vnp_CreateDate", order.CreatedDate.ToString("yyyyMMddHHmmss"));
                vnpay.AddRequestData("vnp_CurrCode", "VND");
                vnpay.AddRequestData("vnp_IpAddr", Utils.GetIpAddress());


                //if (!string.IsNullOrEmpty(locale))
                //{
                //    vnpay.AddRequestData("vnp_Locale", locale);
                //}
                //else
                //{
                //    vnpay.AddRequestData("vnp_Locale", "vn");
                //}
                vnpay.AddRequestData("vnp_Locale", "vn");
                vnpay.AddRequestData("vnp_OrderInfo", order.OrderDescription);
                vnpay.AddRequestData("vnp_OrderType", "other"); //default value:
                vnpay.AddRequestData("vnp_ReturnUrl", vnp_Returnurl);
                vnpay.AddRequestData("vnp_TxnRef", order.OrderId.ToString());

                string paymentUrl = vnpay.CreateRequestUrl(vnp_Url, vnp_HashSecret);
                log.InfoFormat("VNPAY URL: {0}", paymentUrl);
                return(Redirect(paymentUrl));
            }
            catch
            {
                return(View("Index"));
            }
        }
        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"));
        }
Example #15
0
        public ActionResult VnPay(string amount, string description, List <int> listCourseId)
        {
            //Get Config Info
            string vnp_Returnurl  = "https://localhost:44374/Home/Cart";                 //URL nhan ket qua tra ve
            string vnp_Url        = "http://sandbox.vnpayment.vn/paymentv2/vpcpay.html"; //URL thanh toan cua VNPAY
            string vnp_TmnCode    = "P1V8JH37";                                          //Ma website
            string vnp_HashSecret = "XAUJIMFNKYUUWWNWOLLNIHJCUGLOIGEF";                  //Chuoi bi mat

            //Get payment input
            OrderInfo order = new OrderInfo();

            //Save order to db
            order.OrderId       = "DH" + DateTime.Now.Ticks.ToString();
            TempData["OrderId"] = order.OrderId;
            var orderDetails = new List <OrderDetail>();

            foreach (var item in listCourseId)
            {
                var course = db.Courses.Find(item);
                if (course == null)
                {
                    break;
                }
                var orderDetail = new OrderDetail();

                orderDetail.CourseId = item;
                orderDetail.OrderId  = order.OrderId;
                orderDetail.Price    = course.Price;
                orderDetails.Add(orderDetail);
            }
            order.orderType     = (int)OrderInfo.OrderType.BuyCourse;
            order.OrderDetails  = orderDetails;
            order.Status        = Convert.ToInt16(OrderInfo.OrderStatus.Pending);
            order.MemberId      = User.Identity.GetUserId();
            order.PaymentTypeId = Convert.ToInt16(OrderInfo.PaymentType.DirectTransfer);
            order.Amount        = Convert.ToDecimal(amount);
            if (description == null)
            {
                description = "NA";
            }
            order.OrderDescription = description;
            order.CreatedAt        = DateTime.Now.ToString();
            db.OrderInfos.Add(order);
            try
            {
                db.SaveChanges();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
            //Build URL for VNPAY
            VnPayLibrary vnpay = new VnPayLibrary();

            vnpay.AddRequestData("vnp_Version", "2.0.0");
            vnpay.AddRequestData("vnp_Command", "pay");
            vnpay.AddRequestData("vnp_TmnCode", vnp_TmnCode);
            vnpay.AddRequestData("vnp_Amount", (order.Amount * 100).ToString());
            vnpay.AddRequestData("vnp_BankCode", "NCB");
            vnpay.AddRequestData("vnp_CreateDate", DateTime.Now.ToString("yyyyMMddHHmmss"));
            vnpay.AddRequestData("vnp_CurrCode", "VND");
            vnpay.AddRequestData("vnp_IpAddr", Utils.GetIpAddress());
            vnpay.AddRequestData("vnp_Locale", "vn");
            vnpay.AddRequestData("vnp_OrderInfo", order.OrderDescription);
            vnpay.AddRequestData("vnp_OrderType", "190002"); //default value: other
            vnpay.AddRequestData("vnp_ReturnUrl", vnp_Returnurl);
            vnpay.AddRequestData("vnp_TxnRef", order.OrderId.ToString());

            string paymentUrl = vnpay.CreateRequestUrl(vnp_Url, vnp_HashSecret);

            log.InfoFormat("VNPAY URL: {0}", paymentUrl);
            //Response.Redirect(paymentUrl);
            Debug.WriteLine(paymentUrl);
            Console.WriteLine(paymentUrl);
            return(Redirect(paymentUrl));
        }
Example #16
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();
        }
Example #17
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());
        }
Example #18
0
        public async Task <IActionResult> PaymentAsync()
        {
            //Get Config Info
            string vnp_Returnurl  = _configuration.GetSection("VNPayInfo").GetSection("vnp_Returnurl").Value;  //URL nhan ket qua tra ve
            string vnp_Url        = _configuration.GetSection("VNPayInfo").GetSection("vnp_Url").Value;        //URL thanh toan cua VNPAY
            string vnp_TmnCode    = _configuration.GetSection("VNPayInfo").GetSection("vnp_TmnCode").Value;    //Ma website
            string vnp_HashSecret = _configuration.GetSection("VNPayInfo").GetSection("vnp_HashSecret").Value; //Chuoi bi mat

            if (string.IsNullOrEmpty(vnp_TmnCode) || string.IsNullOrEmpty(vnp_HashSecret))
            {
                return(Json("Vui lòng cấu hình các tham số: vnp_TmnCode,vnp_HashSecret trong file appsetting.json"));
            }
            //Get payment input
            OrderInfo order = new OrderInfo();

            //Save order to db
            order.OrderId          = Guid.NewGuid().ToString();
            order.Amount           = 10000;
            order.OrderDescription = "VIP1";
            order.CreatedDate      = DateTime.Now;
            order.BankCode         = "NCB";
            order.Status           = 0;
            _context.Add(order);
            await _context.SaveChangesAsync();

            string locale = "vn";
            //Build URL for VNPAY
            VnPayLibrary vnpay = new VnPayLibrary();

            vnpay.AddRequestData("vnp_Version", "2.0.0");
            vnpay.AddRequestData("vnp_Command", "pay");
            vnpay.AddRequestData("vnp_TmnCode", vnp_TmnCode);
            vnpay.AddRequestData("vnp_Amount", (order.Amount * 100).ToString());
            //if (cboBankCode.SelectedItem != null && !string.IsNullOrEmpty(cboBankCode.SelectedItem.Value))
            //{
            //    vnpay.AddRequestData("vnp_BankCode", cboBankCode.SelectedItem.Value);
            //}
            vnpay.AddRequestData("vnp_BankCode", "NCB");
            vnpay.AddRequestData("vnp_CreateDate", order.CreatedDate.ToString("yyyyMMddHHmmss"));
            vnpay.AddRequestData("vnp_CurrCode", "VND");
            vnpay.AddRequestData("vnp_IpAddr", Models.Utils.GetIpAddress());


            if (!string.IsNullOrEmpty(locale))
            {
                vnpay.AddRequestData("vnp_Locale", locale);
            }
            else
            {
                vnpay.AddRequestData("vnp_Locale", "vn");
            }
            vnpay.AddRequestData("vnp_OrderInfo", order.OrderDescription);
            //vnpay.AddRequestData("vnp_OrderType", orderCategory.SelectedItem.Value); //default value: other
            vnpay.AddRequestData("vnp_ReturnUrl", vnp_Returnurl);
            vnpay.AddRequestData("vnp_TxnRef", order.OrderId);

            string paymentUrl = vnpay.CreateRequestUrl(vnp_Url, vnp_HashSecret);

            //log.InfoFormat("VNPAY URL: {0}", paymentUrl);
            Response.Redirect(paymentUrl);
            return(Json("Success"));
        }
        // GET: Membership
        public ActionResult VnPayMembership(string amount, string description)
        {
            var getAmount      = Convert.ToDecimal(amount);
            var listMemberType = db.Members.ToList();
            var validate       = false;

            foreach (var memberType in listMemberType)
            {
                if (description == memberType.MemberType && getAmount == memberType.Price)
                {
                    validate = true;
                    break;
                }
            }

            if (validate == false)
            {
                return(RedirectToAction("Index", "Home"));
            }

            //Get Config Info
            string vnp_Returnurl  = "https://localhost:44302/Home";                      //URL nhan ket qua tra ve
            string vnp_Url        = "http://sandbox.vnpayment.vn/paymentv2/vpcpay.html"; //URL thanh toan cua VNPAY
            string vnp_TmnCode    = "P1V8JH37";                                          //Ma website
            string vnp_HashSecret = "XAUJIMFNKYUUWWNWOLLNIHJCUGLOIGEF";                  //Chuoi bi mat

            var UserManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(db));
            //Get payment input
            OrderInfo order = new OrderInfo();

            //Save order to db
            order.OrderId       = "DH" + DateTime.Now.Ticks.ToString();
            TempData["OrderId"] = order.OrderId;
            order.Status        = Convert.ToInt16(OrderStatus.Pending);
            var userId = User.Identity.GetUserId();

            order.UserId           = userId;
            order.ApplicationUser  = UserManager.FindById(userId);
            order.Amount           = Math.Round(getAmount);
            order.OrderDescription = description;
            order.CreatedAt        = DateTime.Now;


            db.OrderInfos.Add(order);
            try
            {
                db.SaveChanges();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
            //Build URL for VNPAY
            VnPayLibrary vnpay = new VnPayLibrary();

            vnpay.AddRequestData("vnp_Version", "2.0.0");
            vnpay.AddRequestData("vnp_Command", "pay");
            vnpay.AddRequestData("vnp_TmnCode", vnp_TmnCode);
            vnpay.AddRequestData("vnp_Amount", (order.Amount * 23145 * 100).ToString());
            vnpay.AddRequestData("vnp_BankCode", "NCB");
            vnpay.AddRequestData("vnp_CreateDate", DateTime.Now.ToString("yyyyMMddHHmmss"));
            vnpay.AddRequestData("vnp_CurrCode", "VND");
            vnpay.AddRequestData("vnp_IpAddr", Utils.GetIpAddress());
            vnpay.AddRequestData("vnp_Locale", "vn");
            vnpay.AddRequestData("vnp_OrderInfo", order.OrderDescription);
            vnpay.AddRequestData("vnp_OrderType", "190002"); //default value: other
            vnpay.AddRequestData("vnp_ReturnUrl", vnp_Returnurl);
            vnpay.AddRequestData("vnp_TxnRef", order.OrderId.ToString());

            string paymentUrl = vnpay.CreateRequestUrl(vnp_Url, vnp_HashSecret);

            log.InfoFormat("VNPAY URL: {0}", paymentUrl);
            return(Redirect(paymentUrl));
        }
Example #20
0
        public async Task <IActionResult> Checkout(CheckoutViewModel model)
        {
            var sessions = HttpContext.Session.Get <List <ShoppingCartViewModel> >(CommonConstants.CartSession);

            if (ModelState.IsValid)
            {
                if (sessions != null)
                {
                    var details = new List <BillDetailViewModel>();

                    decimal totalMoney = 0;
                    bool    canBuy     = true;
                    foreach (var item in sessions)
                    {
                        totalMoney += item.Price * item.Quantity;

                        details.Add(new BillDetailViewModel()
                        {
                            Price     = item.Price,
                            ColorId   = item.Color.Id,
                            SizeId    = item.Size.Id,
                            Quantity  = item.Quantity,
                            ProductId = item.Product.Id
                        });

                        canBuy = await _quantityService.SellProduct(item.Product.Id, item.Quantity);

                        if (!canBuy)
                        {
                            break;
                        }
                    }

                    if (canBuy)
                    {
                        var billViewModel = new BillViewModel()
                        {
                            CustomerMobile  = model.CustomerMobile,
                            BillStatus      = BillStatus.New,
                            CustomerAddress = model.CustomerAddress,
                            CustomerName    = model.CustomerName,
                            CustomerMessage = model.CustomerMessage,
                            BillDetails     = details,
                            DateCreated     = DateTime.Now,
                            PaymentMethod   = model.PaymentMethod
                        };
                        if (User.Identity.IsAuthenticated)
                        {
                            billViewModel.CustomerId = Guid.Parse(User.GetSpecificDefault("UserId"));
                        }
                        var dataReturn = await _billService.Create(billViewModel);

                        _billService.Save();
                        HttpContext.Session.Set(CommonConstants.BillSession, dataReturn);
                        string vnp_Returnurl         = _configuration["VNPAY:vnp_Returnurl"];  //URL nhan ket qua tra ve
                        string vnp_Url               = _configuration["VNPAY:vnp_Url"];        //URL thanh toan cua VNPAY
                        string vnp_TmnCode           = _configuration["VNPAY:vnp_TmnCode"];    //Ma website
                        string vnp_HashSecret        = _configuration["VNPAY:vnp_HashSecret"]; //Chuoi bi mat
                        HttpContextAccessor accessor = new HttpContextAccessor();
                        VnPayLibrary        vnpay    = new VnPayLibrary(accessor);
                        vnpay.AddRequestData("vnp_Version", "2.0.0");
                        vnpay.AddRequestData("vnp_Command", "pay");
                        vnpay.AddRequestData("vnp_TmnCode", vnp_TmnCode);
                        vnpay.AddRequestData("vnp_Locale", "vn");
                        vnpay.AddRequestData("vnp_CurrCode", "VND");
                        vnpay.AddRequestData("vnp_TxnRef", DateTime.Now.Ticks.ToString());
                        vnpay.AddRequestData("vnp_OrderInfo", "Noi dung thanh toan:20190421030204");
                        vnpay.AddRequestData("vnp_OrderType", "topup"); //default value: other
                        vnpay.AddRequestData("vnp_Amount", ((int)totalMoney * 100).ToString());
                        vnpay.AddRequestData("vnp_ReturnUrl", vnp_Returnurl);
                        vnpay.AddRequestData("vnp_IpAddr", vnpay.GetIpAddress());
                        vnpay.AddRequestData("vnp_CreateDate", DateTime.Now.ToString("yyyyMMddHHmmss"));
                        vnpay.AddRequestData("vnp_BankCode", "NCB");
                        string paymentUrl = vnpay.CreateRequestUrl(vnp_Url, vnp_HashSecret);
                        return(new OkObjectResult(new
                        {
                            status = true,
                            url = paymentUrl
                        }));
                    }

                    return(new OkObjectResult(new
                    {
                        status = false,
                        message = "Hiện số lượng sản phẩm không đủ."
                    }));
                }

                model.Carts = sessions;
                HttpContext.Session.Set(CommonConstants.CartSession, new List <ShoppingCartViewModel>());
                return(View(model));
            }
            return(new OkObjectResult(""));
        }
Example #21
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
            });
        }
        public ActionResult ThanhToan(string name, string diachi, string sdt)
        {
            sdt = sdt.Trim();
            var db      = new BookContext();
            var kh      = Session["KhachHang"] as KhachHang;
            var lstItem = Session["cart"] as List <Item>;

            // insert khach hang
            if (kh == null)
            {
                KhachHang khachHang = db.KhachHang.Where(item => item.TaiKhoan.Equals(sdt)).FirstOrDefault();
                if (khachHang == null)
                {
                    kh          = new KhachHang();
                    kh.HoTen    = name;
                    kh.NgaySinh = DateTime.Now;
                    kh.TaiKhoan = sdt.Trim();
                    kh.MatKhau  = "123456";
                    kh.LoaiKH   = "Khách Hàng";
                    kh.flag     = false;
                    db.KhachHang.Add(kh);
                    db.SaveChanges();
                }
                else
                {
                    kh = khachHang;
                }
            }

            // insert hoa don
            HoaDon hd = new HoaDon();

            hd.NgayTao     = DateTime.Now;
            hd.DaThanhToan = false;
            hd.MaKH        = kh.MaKH;
            hd.TongTien    = lstItem.Sum(item => item.Quantity * item.sach.GiaBan);
            hd.SDT         = sdt;
            hd.DiaChi      = diachi;
            hd.flag        = false;
            hd.DaGiaoHang  = false;
            hd.TrangThai   = 1;
            db.HoaDon.Add(hd);
            db.SaveChanges();
            foreach (Item item in lstItem)
            {
                ChiTietHoaDon cthd = new ChiTietHoaDon();
                cthd.MaDonHang = hd.MaDonHang;
                cthd.MaSach    = item.sach.MaSach;
                cthd.SoLuong   = item.Quantity;
                cthd.ThanhTien = item.sach.GiaBan * item.Quantity;
                cthd.flag      = false;
                db.ChiTietHoaDon.Add(cthd);
            }
            // insert log
            Log log = new Log();

            log.flag     = false;
            log.ThoiGian = DateTime.Now;
            log.TaiKhoan = kh.TaiKhoan;
            log.TacVu    = "Admin";
            log.HanhDong = "Đã mua sách với hóa đơn có mã: " + hd.MaDonHang;
            db.Log.Add(log);

            db.SaveChanges();
            //Get Config Info
            string vnp_Returnurl  = ConfigurationManager.AppSettings["vnp_Returnurl"];  //URL nhan ket qua tra ve
            string vnp_Url        = ConfigurationManager.AppSettings["vnp_Url"];        //URL thanh toan cua VNPAY
            string vnp_TmnCode    = ConfigurationManager.AppSettings["vnp_TmnCode"];    //Ma website
            string vnp_HashSecret = ConfigurationManager.AppSettings["vnp_HashSecret"]; //Chuoi bi mat

            //Get payment input
            OrderInfo orderInfo = new OrderInfo();

            //Save order to db
            orderInfo.OrderId          = hd.MaDonHang;
            orderInfo.Amount           = Convert.ToDecimal(hd.TongTien);
            orderInfo.OrderDescription = hd.DiaChi;
            orderInfo.CreatedDate      = DateTime.Now;

            //Build URL for VNPAY
            VnPayLibrary vnpay = new VnPayLibrary();

            vnpay.AddRequestData("vnp_Version", "2.0.0");
            vnpay.AddRequestData("vnp_Command", "pay");
            vnpay.AddRequestData("vnp_TmnCode", vnp_TmnCode);

            string locale = "vn";

            if (!string.IsNullOrEmpty(locale))
            {
                vnpay.AddRequestData("vnp_Locale", locale);
            }
            else
            {
                vnpay.AddRequestData("vnp_Locale", "vn");
            }

            vnpay.AddRequestData("vnp_CurrCode", "VND");
            vnpay.AddRequestData("vnp_TxnRef", orderInfo.OrderId.ToString());
            vnpay.AddRequestData("vnp_OrderId", hd.MaDonHang.ToString());
            vnpay.AddRequestData("vnp_OrderInfo", hd.MaDonHang.ToString());
            vnpay.AddRequestData("vnp_OrderType", "other"); //default value: other
            vnpay.AddRequestData("vnp_Amount", Math.Round(orderInfo.Amount * 100).ToString());
            vnpay.AddRequestData("vnp_ReturnUrl", vnp_Returnurl);
            vnpay.AddRequestData("vnp_IpAddr", Utils.GetIpAddress());
            vnpay.AddRequestData("vnp_CreateDate", orderInfo.CreatedDate.ToString("yyyyMMddHHmmss"));

            //if (bank.SelectedItem != null && !string.IsNullOrEmpty(bank.SelectedItem.Value))
            //{
            vnpay.AddRequestData("vnp_BankCode", "NCB");
            //}

            string paymentUrl = vnpay.CreateRequestUrl(vnp_Url, vnp_HashSecret);

            Debug.WriteLine("VNPAY URL: {0}", paymentUrl);
            Session["cart"] = new List <Item>();
            return(Redirect(paymentUrl));
            //return RedirectToAction("Success");
        }
Example #23
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();
        }
Example #24
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);
        }