Example #1
0
        public ActionResult PaymentWithPaypal(ShippingAddress shippingAddress)
        {
            if (!ModelState.IsValid)
            {
                return(View(shippingAddress));
            }

            // Getting context from the paypal bases on clientId and clientSecret for payment
            APIContext apiContext = PaypalConfiguration.GetAPIContext();

            try
            {
                string payerId = Request.Params["PayerID"];
                if (string.IsNullOrEmpty(payerId))
                {
                    // Creating a payment
                    string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/ShoppingCart/PaymentWithPaypal";
                    var    guid    = Convert.ToString((new Random()).Next(100000));

                    var createdPayment = CreatePayment(apiContext, new List <Product>()
                    {
                        new Product()
                    }, shippingAddress, baseURI);


                    // Get links returned from paypal response to create call function
                    var    links = createdPayment.links.GetEnumerator();
                    string paypaylRedirectUrl = string.Empty;

                    while (links.MoveNext())
                    {
                        Links link = links.Current;
                        if (link.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            paypaylRedirectUrl = link.href;
                        }
                    }

                    Session.Add(guid, createdPayment.id);
                    return(Redirect(paypaylRedirectUrl));
                }
                else
                {
                    // This one will be executed when we have recieved all the payment params from previous call
                    var guid            = Request.Params["paymentId"];               // Request.Params["guid"];
                    var executedPayment = ExecutePayment(apiContext, payerId, guid); //Session[guid] as string);
                    if (executedPayment.state.ToLower() != "approved")
                    {
                        return(View("Index", "Errors"));
                    }
                }
            }
            catch (Exception ex)
            {
                PaypalLogger.Log("Error : " + ex.Message);
                return(View("Index", "Errors"));
            }

            return(View("PaymentSuccess"));
        }
Example #2
0
        protected void checkout_Click(object sender, EventArgs e)
        {
            CartList = (List <Section>)Session["ScItms"];
            var discount = Convert.ToDouble(Session["Discount"].ToString());

            APIContext apiContext = PaypalConfiguration.GetAPIContext();

            try
            {
                String baseURI        = Request.Url.Scheme + "://" + Request.Url.Authority + "/site/student/processPayment.aspx?";
                var    guid           = Convert.ToString(new Random().Next(100000));
                var    createdPayment = PaypalPayment.CreatePayment(apiContext, baseURI + "guid=" + guid, CartList, discount);

                var    links             = createdPayment.links.GetEnumerator();
                String paypalRedirectUrl = String.Empty;

                while (links.MoveNext())
                {
                    Links link = links.Current;
                    if (link.rel.ToLower().Trim().Equals("approval_url"))
                    {
                        paypalRedirectUrl = link.href;
                    }
                }
                Session.Add(guid, createdPayment.id);
                Session["cartList"] = CartList;
                Response.Redirect(paypalRedirectUrl, false);
            }
            catch (Exception ex)
            {
                PaypalLogger.Log("Error: " + ex.Message);
                Response.Redirect("~/site/failedPaypal.aspx");
            }
        }
Example #3
0
        //create method
        public ActionResult PaymentWithPaypal()
        {
            var        usrDonate  = (UserDonateView)Session["ud"];
            APIContext apiContext = PaypalConfiguration.GetAPIContext();

            try
            {
                string payerID = Request.Params["PayerID"];
                if (string.IsNullOrEmpty(payerID))
                {
                    //create a payment
                    string baseUri        = Request.Url.Scheme + "://" + Request.Url.Authority + "/Paypal/PaymentWithPaypal?guid=";
                    string guid           = Convert.ToString((new Random()).Next(100000));
                    var    createdPayment = CreatePayment(apiContext, baseUri + guid);

                    var    link = createdPayment.links.GetEnumerator();
                    string paypalRedirectUrl = string.Empty;
                    while (link.MoveNext())
                    {
                        Links links = link.Current;
                        if (links.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            paypalRedirectUrl = links.href;
                        }
                    }
                    Session.Add(guid, createdPayment.id);
                    return(Redirect(paypalRedirectUrl));
                }
                else
                {
                    var guid           = Request.Params["guid"];
                    var executePayment = ExecutePayment(apiContext, payerID, Session[guid] as string);
                    if (executePayment.state.ToLower() != "approved")
                    {
                        TempData["error"] = "Donate Failed. Please try again!";
                        return(RedirectToAction("Donate", "Home"));
                    }
                }
            }
            catch (PayPal.PaymentsException ex)
            {
                TempData["error"] = "Donate Failed. Please try again!";
                PaypalLogger.Log("Error: " + ex.Message);
                return(RedirectToAction("Donate", "Home"));
            }
            var ud = new UserDonate {
                DonateID = usrDonate.DonateID, Money = usrDonate.Money, UserID = usrDonate.UserID, TypeCard = usrDonate.TypeCard
            };

            if (Repositories.InsertUD(ud) > 0)
            {
                TempData["success"] = "Donate Successfully! We appreciate it!";
            }
            else
            {
                TempData["error"] = "Donate Failed. Please try again!";
            }
            return(RedirectToAction("Donate", "Home"));
        }
Example #4
0
        // Create PaymentWithPaypal method
        public ActionResult PaymentWithPaypal()
        {
            // Gettings context from the paypal bases on clientId and clientsecret for payment
            APIContext apiContext = PaypalConfiguration.GetAPIContext();

            try
            {
                string payerId = Request.Params["PayerID"];

                if (string.IsNullOrEmpty(payerId))
                {
                    //Creating a payment
                    string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/NguoiMua/GioHang/PaymentWithPaypal?";
                    MessageBox.Show("tạo base URI");
                    var guid           = Convert.ToString((new Random()).Next(100000));
                    var createdPayment = CreatePayment(apiContext, baseURI + "guid=" + guid);

                    MessageBox.Show("tạo links");
                    //Get link returned from paypal respone to create call function
                    var    links             = createdPayment.links.GetEnumerator();
                    string paypalRedirectUrl = string.Empty;

                    while (links.MoveNext())
                    {
                        Links link = links.Current;
                        if (link.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            paypalRedirectUrl = link.href;
                        }
                    }

                    Session.Add(guid, createdPayment.id);
                    return(Redirect(paypalRedirectUrl));
                }
                else
                {
                    //This one will be executed when we have received all the payment params from previous call
                    var guid           = Request.Params["guid"];
                    var executePayment = ExecutePayment(apiContext, payerId, Session[guid] as string);
                    if (executePayment.state.ToLower() != "approved")
                    {
                        Session["CheckOut"] = 0;
                        return(RedirectToAction("TrangChu", "TaiKhoan_NguoiMua"));
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                PaypalLogger.Log("Error:" + ex.Message);

                Session["CheckOut"] = 0;
                return(RedirectToAction("TrangChu", "TaiKhoan_NguoiMua"));
            }

            Session["CheckOut"] = 1;
            return(RedirectToAction("TrangChu", "TaiKhoan_NguoiMua"));
        }
Example #5
0
        //create method
        public ActionResult PaymentWithPaypal()
        {
            APIContext apiContext = PaypalConfiguration.GetAPIContext();

            try
            {
                string payerID = Request.Params["PayerID"];
                if (string.IsNullOrEmpty(payerID))
                {
                    //create a payment
                    string baseUri        = Request.Url.Scheme + "://" + Request.Url.Authority + "/Paypal/PaymentWithPaypal?guid=";
                    string guid           = Convert.ToString((new Random()).Next(100000));
                    var    createdPayment = CreatePayment(apiContext, baseUri + guid);

                    var    link = createdPayment.links.GetEnumerator();
                    string paypalRedirectUrl = string.Empty;
                    while (link.MoveNext())
                    {
                        Links links = link.Current;
                        if (links.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            paypalRedirectUrl = links.href;
                        }
                    }
                    Session.Add(guid, createdPayment.id);
                    return(Redirect(paypalRedirectUrl));
                }
                else
                {
                    var guid           = Request.Params["guid"];
                    var executePayment = ExecutePayment(apiContext, payerID, Session[guid] as string);
                    if (executePayment.state.ToLower() != "approved")
                    {
                        TempData["error"] = "Thanh toán bằng Paypal lỗi";
                        return(RedirectToAction("InformationBooking", "Booking", new { token = Session["token"].ToString() }));
                    }
                }
            }
            catch (PayPal.PaymentsException ex)
            {
                PaypalLogger.Log("Error: " + ex.Message);
                Console.WriteLine(ex);
                TempData["error"] = "Thanh toán bằng Paypal lỗi";
                return(RedirectToAction("InformationBooking", "Booking", new { token = Session["token"].ToString() }));
            }
            HttpResponseMessage res = GlobalVariables.client.GetAsync("CheckOut?token=" + Session["token"].ToString() + "&payment=" + false).Result;

            if (res.IsSuccessStatusCode)
            {
                TempData["success"] = "Thanh toán bằng Paypal thành công";
            }
            else
            {
                TempData["error"] = "Loi check out!";
            }
            return(RedirectToAction("InformationBooking", "Booking", new { token = Session["token"].ToString() }));
        }
Example #6
0
        public ActionResult PaymentWithPaypal()
        {
            Reservation reservation  = (Reservation)Session[strReservation];
            Reservation reservation1 = new Reservation
            {
                ArrivalDate   = reservation.ArrivalDate,
                DepartureDate = reservation.DepartureDate,
                RoomId        = reservation.RoomId,
                UserId        = reservation.UserId,
            };

            APIContext apiContext = PaypalConfiguration.GetAPIContext();

            try
            {
                string payerId = Request.Params["PayerID"];
                if (string.IsNullOrEmpty(payerId))
                {
                    string baseURI        = Request.Url.Scheme + "://" + Request.Url.Authority + "/reservations/paymentwithpaypal?";
                    var    guid           = Convert.ToString((new Random()).Next(100000));
                    var    createdPayment = this.CreatePayment(apiContext, baseURI + "guid=" + guid);

                    var    links             = createdPayment.links.GetEnumerator();
                    string paypalRedirectUrl = string.Empty;
                    while (links.MoveNext())
                    {
                        Links lnk = links.Current;
                        if (lnk.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            paypalRedirectUrl = lnk.href;
                        }
                    }
                    Session.Add(guid, createdPayment.id);
                    return(Redirect(paypalRedirectUrl));
                }
                else
                {
                    //this one will be executed when we have received all the payment params from previous call
                    var guid           = Request.Params["guid"];
                    var executePayment = ExecutePayment(apiContext, payerId, Session[guid] as string);
                    if (executePayment.state.ToLower() != "approved")
                    {
                        return(View("Failure"));
                    }
                }
            }
            catch (Exception ex)
            {
                PaypalLogger.Log("Error: " + ex.Message);
                return(View("Failure"));
            }
            _reservationsRepository.AddReservation(reservation1);
            return(View("Success"));
        }
        // GET: Payment (Create payment with Paypal method)
        public ActionResult PaymentWithPaypal()
        {
            // Getting context from the paypal based on clientId and clientsecret for payment
            APIContext apicontext = PaypalConfiguration.GetAPIContext();

            try
            {
                string PayerId = Request.Params["PayerID"];
                if (string.IsNullOrEmpty(PayerId) && PayerId != null)
                {
                    string baseURi = Request.Url.Scheme + "://" + Request.Url.Authority +
                                     "/Payment/PaymentWithPaypal?";

                    var Guid          = Convert.ToString((new Random()).Next(100000000));
                    var createPayment = this.CreatePayment(apicontext, baseURi + "guid=" + Guid);

                    // Get links returned from paypal response to create call function
                    var    links             = createPayment.links.GetEnumerator();
                    string paypalRedirectURL = null;

                    while (links.MoveNext())
                    {
                        Links lnk = links.Current;

                        if (lnk.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            paypalRedirectURL = lnk.href;
                        }
                    }
                    Session.Add(Guid, createPayment.id);
                    return(Redirect(paypalRedirectURL));
                }

                else
                {
                    // This one will be executed when we have received all the payment params from previous call
                    var guid           = Request.Params["guid"];
                    var executedPaymnt = ExecutePayment(apicontext, PayerId, Session[guid] as string);


                    if (executedPaymnt.ToString().ToLower() != "approved")
                    {
                        return(View("FailureView"));
                    }
                }
            }
            catch (Exception ex)
            {
                PaypalLogger.Log("Error: " + ex.Message);
                return(View("FailureView"));
            }
            return(View("SuccessView"));
        }
Example #8
0
        //Create PaymentWithPaypal method
        public ActionResult PaymentWithPaypal()
        {
            APIContext apiContext = PaypalConfiguration.GetAPIContext();

            try
            {
                string payerId = Request.Params["PayerID"];
                if (string.IsNullOrEmpty(payerId))
                {
                    string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/Perfume/PaymentWithPayPal?";

                    var guid           = Convert.ToString((new Random()).Next(100000));
                    var createdPayment = this.CreatePayment(apiContext, baseURI + "guid=" + guid);

                    //get links returned from paypal in response to Create function call
                    var links = createdPayment.links.GetEnumerator();
                    //string paypalRedirectUrl = null;
                    string paypalRedirectUrl = string.Empty;

                    while (links.MoveNext())
                    {
                        Links lnk = links.Current;
                        if (lnk.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            paypalRedirectUrl = lnk.href;
                        }
                    }
                    Session.Add(guid, createdPayment.id);
                    return(Redirect(paypalRedirectUrl));
                }
                else
                {
                    // This section is executed when we have received all the payments parameters
                    var guid            = Request.Params["guid"];
                    var executedPayment = ExecutePayment(apiContext, payerId, Session[guid] as string);
                    if (executedPayment.state.ToLower() != "approved")
                    {
                        Session["ShoppingCart"] = null;
                        return(View("FailureView"));
                    }
                }
            }
            catch (Exception ex)
            {
                PaypalLogger.Log("Error" + ex.Message);

                Session["ShoppingCart"] = null;
                return(View("FailureView"));
            }

            Session["ShoppingCart"] = null;
            return(View("SuccessView"));
        }
Example #9
0
        // Create PaymentWithPaypal method
        public ActionResult PaymentWithPaypal()
        {
            // Getting context from the paypal bases on clientID and clientSecret for payment
            APIContext apiContext = PaypalConfiguration.GetAPIContext();

            try
            {
                string payerId = Request.Params["PayerID"];
                if (string.IsNullOrEmpty(payerId))
                {
                    //Creating a payment
                    string baseURI        = Request.Url.Scheme + "://" + Request.Url.Authority + "/ShoppingCart/PaymentwithPaypal?";
                    var    guid           = Convert.ToString((new Random()).Next(100000));
                    var    createdPayment = CreatePayment(apiContext, baseURI + "guid=" + guid);

                    //Get links returned from paypal response to create
                    var    links             = createdPayment.links.GetEnumerator();
                    string paypalRedirectUrl = string.Empty;

                    while (links.MoveNext())
                    {
                        Links link = links.Current;
                        if (link.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            paypalRedirectUrl = link.href;
                        }
                    }
                    Session.Add(guid, createdPayment.id);
                    return(Redirect(paypalRedirectUrl));
                }
                else
                {
                    //This one will be executed when  we have  received all the payment params from previous call
                    string guid            = Request.Params["guid"];
                    string paymentID       = Request.Params["paymentId"];
                    var    executedPayment = ExecutePayment(apiContext, payerId, paymentID);
                    if (executedPayment.state.ToLower() != "approved")
                    {
                        return(View("Failure"));
                    }
                }
            }
            catch (Exception ex)
            {
                PaypalLogger.log("Error: " + ex.Message);
                return(View("Failure"));
            }

            string TCount = "1";
            string Tday   = DateTime.Today.ToString("yyyy-MM-dd");

            return(RedirectToAction("Create", "Transacaos", new { Tday, TCount }));
        }
Example #10
0
        //create method
        public ActionResult PaymentWithPaypal()
        {
            APIContext apiContext = PaypalConfiguration.GetAPIContext();

            var order = (OrderVipDTO)Session["ordervip"];

            try
            {
                string payerID = Request.Params["PayerID"];
                if (string.IsNullOrEmpty(payerID))
                {
                    //create a payment
                    string baseUri        = Request.Url.Scheme + "://" + Request.Url.Authority + "/Client/Payment/PaymentWithPaypal?guid=";
                    string guid           = Convert.ToString((new Random()).Next(100000));
                    var    createdPayment = CreatePayment(apiContext, baseUri + guid, order);

                    var    link = createdPayment.links.GetEnumerator();
                    string paypalRedirectUrl = string.Empty;
                    while (link.MoveNext())
                    {
                        Links links = link.Current;
                        if (links.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            paypalRedirectUrl = links.href;
                        }
                    }
                    Session.Add(guid, createdPayment.id);
                    return(Redirect(paypalRedirectUrl));
                }
                else
                {
                    var guid           = Request.Params["guid"];
                    var executePayment = ExecutePayment(apiContext, payerID, Session[guid] as string);
                    if (executePayment.state.ToLower() != "approved")
                    {
                        SetAlert("Mua gói vip không thành công", "error");
                        return(RedirectToAction("Index"));
                    }
                }
            }
            catch (PayPal.PaymentsException ex)
            {
                PaypalLogger.Log("Error: " + ex.Message);
                SetAlert("Mua gói vip không thành công", "error");
                return(RedirectToAction("Index"));
            }

            ApiService.AcceptOrder(order);
            SetAlert("Mua gói vip thành công", "success");
            return(RedirectToAction("Success", "Payment", new { code = apiContext.AccessToken }));
        }
Example #11
0
        //create method
        public ActionResult PaymentWithPaypal()
        {
            var apiContext = PaypalConfiguration.GetAPIContext();
            var order      = (OrderData)Session[MessageConst.USER_SESSION];

            try
            {
                string payerID = Request.Params["PayerID"];
                if (string.IsNullOrEmpty(payerID))
                {
                    //create a payment
                    string baseUri        = Request.Url.Scheme + "://" + Request.Url.Authority + "/home/PaymentWithPaypal?guid=";
                    string guid           = Convert.ToString((new Random()).Next(100000));
                    var    createdPayment = CreatePayment(apiContext, baseUri + guid, order);

                    var    link = createdPayment.links.GetEnumerator();
                    string paypalRedirectUrl = string.Empty;
                    while (link.MoveNext())
                    {
                        Links links = link.Current;
                        if (links.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            paypalRedirectUrl = links.href;
                        }
                    }
                    Session.Add(guid, createdPayment.id);
                    return(Redirect(paypalRedirectUrl));
                }
                else
                {
                    var guid           = Request.Params["guid"];
                    var executePayment = ExecutePayment(apiContext, payerID, Session[guid] as string);
                    if (executePayment.state.ToLower() != "approved")
                    {
                        TempData[MessageConst.ERROR] = "Donate Failed !";
                        return(RedirectToAction("Donate"));
                    }
                }
            }
            catch (PayPal.PaymentsException ex)
            {
                PaypalLogger.Log("Error: " + ex.Message);
                TempData[MessageConst.ERROR] = "Donate Failed !";
                return(RedirectToAction("Donate"));
            }
            //save donate
            new DonateDao(_provider).AddUserDonate(order);
            TempData[MessageConst.SUCCESS] = "Donate Successfully!";
            return(RedirectToAction("Donate"));
        }
Example #12
0
        //create Payment Whit Paypal method
        public ActionResult PaymentWithPaypal()
        {
            //getying context from the paypal bases on clientId and clientSecret
            APIContext apiContext = PaypalConfiguration.GetAPIContext();

            try
            {
                string payerId = Request.Params["PayerID"];
                if (string.IsNullOrEmpty(payerId))
                {
                    string baseUrl       = Request.Url.Scheme + "://" + Request.Url.Authority + "/Home/PaymentWithPaypal?";
                    var    guid          = Convert.ToString((new Random()).Next(100000));
                    var    createPayment = CreatePayment(apiContext, baseUrl + "guid=" + guid);

                    //get links returned from paypal response to create cal function
                    var    links             = createPayment.links.GetEnumerator();
                    string paypalRedirectUrl = null;

                    while (links.MoveNext())
                    {
                        Links link = links.Current;
                        if (link.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            paypalRedirectUrl = link.href;
                        }
                    }
                    Session.Add(guid, createPayment.id);
                    return(Redirect(paypalRedirectUrl));
                }
                else
                {
                    var guid            = Request.Params["guid"];
                    var executedPayment = ExecutePayment(apiContext, payerId, Session[guid] as string);
                    if (executedPayment.state.ToLower() != "approved")
                    {
                        return(View("FailureView"));
                    }
                }
            }
            catch (Exception ex)
            {
                PaypalLogger.Log("Error: " + ex.Message);
                Session["Cart"] = null;
                return(View("FailureView"));
            }

            Session["Cart"] = null;
            return(RedirectToAction("SuccessView"));
        }
        //Create PaymentWithPaypal method
        public ActionResult PaymentWithPaypal()
        {
            //gettings context from the paypal bases on clientId and clientSecret for payment
            APIContext apiContext = PaypalConfiguration.GetAPIContext();

            try
            {
                string payerId = Request.Params["PayerID"];
                if (string.IsNullOrEmpty(payerId))
                {
                    //Create a payment
                    string baseURI        = Request.Url.Scheme + "://" + Request.Url.Authority + "/PaymentbyPayPal/PaymentWithPaypal?";
                    var    guid           = Convert.ToString((new Random()).Next(100000));
                    var    createdPayment = CreatePayment(apiContext, baseURI + "guid=" + guid);
                    //Get links returned from paypal response to create call function
                    var    links            = createdPayment.links.GetEnumerator();
                    string paypalRedirecUrl = string.Empty;

                    while (links.MoveNext())
                    {
                        Links link = links.Current;
                        if (link.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            paypalRedirecUrl = link.href;
                        }
                    }

                    Session.Add(guid, createdPayment.id);
                    return(Redirect(paypalRedirecUrl));
                }
                else
                {
                    // This one will be executed when we have received all payment params from previous call
                    var guid           = Request.Params["guid"];
                    var executePayment = ExecutePayment(apiContext, payerId, Session[guid] as string);
                    if (executePayment.state.ToLower() != "approved")
                    {
                        return(View("Failure"));
                    }
                }
            }
            catch (Exception ex)
            {
                PaypalLogger.Log("Error: " + ex.Message);
                return(View("Failure"));
            }

            return(RedirectToAction("PaymentSuccess", "Manage"));
        }
        //Payment with Paypal main method
        public ActionResult PaymentWithPaypal()
        {
            //Get Client credentials
            APIContext apiContext = PaypalConfiguration.GetAPIContext();

            try
            {
                string payerId = Request.Params["PayerID"];//"FHTFDERQPUYRC";
                if (string.IsNullOrEmpty(payerId))
                {
                    //Create a payment
                    string baseURI       = Request.Url.Scheme + "://" + Request.Url.Authority + "/PaypalPayment/PaymentWithPaypal?";
                    var    guid          = Convert.ToString((new Random()).Next(100000));
                    var    createPayment = CreatePayment(apiContext, baseURI + "guid=" + guid);

                    //Response calling
                    var    links             = createPayment.links.GetEnumerator();
                    string paypalRedirectUrl = string.Empty;

                    while (links.MoveNext())
                    {
                        Links link = links.Current;
                        if (link.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            paypalRedirectUrl = link.href;
                        }
                    }
                    Session.Add(guid, createPayment.id);
                    return(Redirect(paypalRedirectUrl));
                }
                else
                {
                    // this will execute when payment
                    var guid           = Request.Params["guid"];
                    var executePayment = ExecutePayment(apiContext, payerId, Session[guid] as string);
                    if (executePayment.state.ToLower() != "approved")
                    {
                        return(View("Failure"));
                    }
                }
            }
            catch (Exception ex)
            {
                PaypalLogger.Log("Error:" + ex.Message);
                return(View("Failure"));
            }
            return(View("Success"));
        }
        //create method
        public ActionResult PaymentWithPaypal()
        {
            APIContext apiContext = PaypalConfiguration.GetAPIContext();

            try
            {
                string payerID = Request.Params["PayerID"];
                if (string.IsNullOrEmpty(payerID))
                {
                    //create a payment
                    string baseUri        = Request.Url.Scheme + "://" + Request.Url.Authority + "/Paypal/PaymentWithPaypal?guid=";
                    string guid           = Convert.ToString((new Random()).Next(100000));
                    var    createdPayment = CreatePayment(apiContext, baseUri + guid);

                    var    link = createdPayment.links.GetEnumerator();
                    string paypalRedirectUrl = string.Empty;
                    while (link.MoveNext())
                    {
                        Links links = link.Current;
                        if (links.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            paypalRedirectUrl = links.href;
                        }
                    }
                    Session.Add(guid, createdPayment.id);
                    return(Redirect(paypalRedirectUrl));
                }
                else
                {
                    var guid           = Request.Params["guid"];
                    var executePayment = ExecutePayment(apiContext, payerID, Session[guid] as string);
                    if (executePayment.state.ToLower() != "approved")
                    {
                        return(View("Failure"));
                    }
                }
            }
            catch (PayPal.PaymentsException ex)
            {
                PaypalLogger.Log("Error: " + ex.Message);
                return(View("Failure"));
            }

            AddCustomerPolicy();
            return(RedirectToAction("Success"));
        }
Example #16
0
        // GET: Payment
        public ActionResult PaymentWithPapal()
        {
            APIContext apicontext = PaypalConfiguration.GetAPIContext();

            try
            {
                string PayerId = Request.Params["PayerID"];
                if (string.IsNullOrEmpty(PayerId))
                {
                    string baseURi           = Request.Url.Scheme + "://" + Request.Url.Authority + "/PaymentWithPapal/PaymentWithPapal?";
                    var    Guid              = Convert.ToString((new Random()).Next(10000000));
                    var    createdPayment    = CreatePayment(apicontext, baseURi + "guid=" + Guid);
                    var    links             = createdPayment.links.GetEnumerator();
                    string paypalRedirectURL = string.Empty;
                    while (links.MoveNext())
                    {
                        Links link = links.Current;

                        if (link.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            paypalRedirectURL = link.href;
                        }
                    }
                }
                else
                {
                    var guid           = Request.Params["guid"];
                    var executedPaymnt = ExecutePayment(apicontext, PayerId, Session[guid] as string);
                    if (executedPaymnt.ToString().ToLower() != "approved")
                    {
                        return(View("FailureView"));
                    }
                }
            }
            catch (Exception ex)
            {
                PaypalLogger.Log("Error: " + ex.Message);
                return(View("FailureView"));
                //throw;
            }
            return(View("SuccessView"));
        }
Example #17
0
        public ActionResult PaymentWithPaypal()
        {
            Cart cart = Session["Cart"] as Cart;

            APIContext apiContext = PaypalConfiguration.GetAPIContext();

            try
            {
                string payerId = Request.Params["PayerID"];
                if (string.IsNullOrEmpty(payerId))
                {
                    string baseURI        = Request.Url.Scheme + "://" + Request.Url.Authority + "/ShoppingCart/PaymentWithPaypal?";
                    var    guid           = Convert.ToString((new Random()).Next(100000));
                    var    createdPayment = CreatePayment(apiContext, baseURI + "guid=" + guid);

                    var    links             = createdPayment.links.GetEnumerator();
                    string paypalRedirectUrl = string.Empty;

                    while (links.MoveNext())
                    {
                        Links link = links.Current;
                        if (link.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            paypalRedirectUrl = link.href;
                        }
                    }
                    Session.Add(guid, createdPayment.id);

                    return(Redirect(paypalRedirectUrl));
                }
                else
                {
                    var guid           = Request.Params["guid"];
                    var executePayment = ExecutePayment(apiContext, payerId, Session[guid] as string);
                    if (executePayment.state.ToLower() != "approved")
                    {
                        cart.ClearCart();
                        return(View("Failure"));
                    }
                }
            }
            catch (Exception e)
            {
                PaypalLogger.Log("Error: " + e.Message);
                cart.ClearCart();
                return(View("Failure"));
            }
            if (User.Identity.IsAuthenticated)
            {
                //Orders
                var acc   = db.Orders.FirstOrDefault(x => x.Customer.Email == User.Identity.Name);
                var order = new Models.Order();
                order.Date         = DateTime.Now;
                order.TinhTrang    = "Dang cho";
                order.CustomerID   = acc.CustomerID;
                order.PhoneNumber  = acc.PhoneNumber;
                order.Email        = acc.Email;
                order.PhuongThuc   = "PayPal";
                order.Descriptions = "";
                db.Orders.Add(order);
                db.SaveChanges();

                //OrderDetail
                foreach (var item in cart.Items)
                {
                    OrderDetail orderDetail = new OrderDetail
                    {
                        QuantitySale  = item.Shopping_quantity,
                        UnitPriceSale = item.Shopping_quantity * item.Shopping_product.Price,
                        OrderID       = order.OrderID,
                        ProductID     = item.Shopping_product.ProductID,
                    };
                    db.OrderDetails.Add(orderDetail);
                    db.SaveChanges();

                    //giảm số lượng sp sau khi đặt
                    var product = db.Products.FirstOrDefault(x => x.ProductID == item.Shopping_product.ProductID);
                    product.Quantity        = product.Quantity - item.Shopping_quantity;
                    db.Entry(product).State = System.Data.Entity.EntityState.Modified;
                    db.SaveChanges();
                }
            }
            else
            {
                var order = new Models.Order();
                order.Date         = DateTime.Now;
                order.TinhTrang    = "Dang cho";
                order.CustomerID   = null;
                order.PhoneNumber  = "123";
                order.Email        = "123";
                order.PhuongThuc   = "PayPal";
                order.Descriptions = "";
                db.Orders.Add(order);
                db.SaveChanges();

                //OrderDetail
                foreach (var item in cart.Items)
                {
                    OrderDetail orderDetail = new OrderDetail
                    {
                        QuantitySale  = item.Shopping_quantity,
                        UnitPriceSale = item.Shopping_quantity * item.Shopping_product.Price,
                        OrderID       = order.OrderID,
                        ProductID     = item.Shopping_product.ProductID,
                    };
                    db.OrderDetails.Add(orderDetail);
                    db.SaveChanges();

                    //giảm số lượng sp sau khi đặt
                    var product = db.Products.FirstOrDefault(x => x.ProductID == item.Shopping_product.ProductID);
                    product.Quantity        = product.Quantity - item.Shopping_quantity;
                    db.Entry(product).State = System.Data.Entity.EntityState.Modified;
                    db.SaveChanges();
                }
            }
            cart.ClearCart();
            return(View("Success"));
        }
Example #18
0
        public ActionResult PaymentWithPaypal()
        {
            APIContext apiContext = PaypalConfiguration.GetAPIContext();

            try
            {
                string payerId = Request.Params["PayerID"];

                if (string.IsNullOrEmpty(payerId))
                {
                    string baseURI           = Request.Url.Scheme + "://" + Request.Url.Authority + "/Checkout/PaymentWithPayPal?";
                    var    guid              = Convert.ToString((new Random()).Next(100000));
                    var    model             = _checkOutService.GetSessionOrder(User.Identity.GetUserId(), Langs.English, EShop.Common.Currency.Dollar);
                    var    createdPayment    = _paypalService.CreatePayment(apiContext, baseURI + "guid=" + guid, model);
                    var    links             = createdPayment.links.GetEnumerator();
                    string paypalRedirectUrl = null;
                    while (links.MoveNext())
                    {
                        Links lnk = links.Current;

                        if (lnk.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            paypalRedirectUrl = lnk.href;
                        }
                    }

                    Session.Add(guid, createdPayment.id);

                    return(Redirect(paypalRedirectUrl));
                }
                else
                {
                    var guid            = Request.Params["guid"];
                    var executedPayment = _paypalService.ExecutePayment(apiContext, payerId, Session[guid] as string, ref payment);
                    if (executedPayment.state.ToLower() != "approved")
                    {
                        return(View("FailureView"));
                    }
                    else
                    {
                        //var model = Session["SubscriptionModel"] as PaypalTransactionViewModel;
                        //// SUCCESSFUL TRANSACTION
                        //SubscriptionInvoice inv = new SubscriptionInvoice()
                        //{
                        //    Amount = model.Amount,
                        //    CycleStartDate = DateTime.Now,
                        //    CycleEndDate = DateTime.Now.AddMonths(1),
                        //    Description = model.Description,
                        //    InvoiceDate = model.InvoiceDate,
                        //    InvoiceNo = model.InvoiceNo,
                        //    ItemCurrency = model.Items[0].Currency,
                        //    ItemDescription = model.Items[0].Description,
                        //    ItemName = model.Items[0].Name,
                        //    ItemPrice = model.Items[0].Price,
                        //    ItemQuantity = model.Items[0].Quantity,
                        //    Paid = true,
                        //    PayerID = executedPayment.payer.payer_info.payer_id,
                        //    PaymentId = executedPayment.id,
                        //    PaymentToken = executedPayment.token,
                        //    TransactionId = executedPayment.transactions[0].related_resources[0].sale.id,
                        //    UserId = model.AppUser.Id,
                        //    PayPalJSON = executedPayment.ConvertToJson()
                        //};
                        //_unitOfWork.SubscriptionInvoiceRepository.Insert(inv);
                        //_unitOfWork.Save();
                        //var user = UserManager.FindById(User.Identity.GetUserId());
                        //user.IsPremium = true;
                        //user.PremiumExpiryDate = inv.CycleEndDate;
                        //UserManager.Update(user);
                        //return View("SuccessView", inv);
                        return(View("SuccessView"));
                    }
                }
            }
            catch (PayPal.PaymentsException ex)
            {
                PaypalLogger.Log("Error" + ex.Details.ConvertToJson());
                return(View("FailureView"));
            }
            catch (Exception ex)
            {
                PaypalLogger.Log("Error" + ex.Message);
                return(View("FailureView"));
            }
            //return View("SuccessView");
        }
Example #19
0
        public ActionResult PaymentWithPaypal()
        {
            var session = Session[CommonConstants.USER_SESSION];

            if (session == null || session == " ")
            {
                return(RedirectToAction("Login", "User"));
            }

            List <CartItem> ListCart = (List <CartItem>)Session[strCart];

            // save order
            var       order = new WebApplication.Models.Order();
            UserLogin cus   = (UserLogin)Session[CommonConstants.USER_SESSION];

            order.Order_Date = DateTime.Now;

            order.Customer_ID = cus.Customer_ID;
            order.Status      = "Pending";



            // save od
            foreach (CartItem cart in ListCart)
            {
                OrderDetail orderdetail = new OrderDetail()
                {
                    Quantity         = cart.Quantity,
                    Product_Price    = cart.Product.Product_Price,
                    Product_Discount = cart.Product.Product_Discount,
                    Product_ID       = cart.Product.Product_ID,
                    Order_ID         = order.Order_ID
                };
                TempData["Quan"] = cart.Quantity;
                TempData["PN"]   = cart.Product.Product_Name;
                TempData["pri"]  = cart.Product.Product_Price - ((cart.Product.Product_Price * cart.Product.Product_Discount) / 100);
                TempData["Tot"]  = (cart.Product.Product_Price - ((cart.Product.Product_Price * cart.Product.Product_Discount) / 100)) * cart.Quantity;

                var model = db.Products.Single(x => x.Product_ID == cart.Product.Product_ID);

                if (cart.Quantity > model.Quantity)
                {
                    return(RedirectToAction("Fail", "Cart"));
                }

                db.OrderDetails.Add(orderdetail);
                model.Quantity = model.Quantity - orderdetail.Quantity;
            }
            APIContext apiContext = PaypalConfiguration.GetAPIContext();

            try
            {
                string payerId = Request.Params["PayerID"];
                if (string.IsNullOrEmpty(payerId))
                {
                    string baseURI        = Request.Url.Scheme + "://" + Request.Url.Authority + "/Cart/PaymentWithPaypal?";
                    var    guid           = Convert.ToString((new Random()).Next(100000));
                    var    createdPayment = CreatePayment(apiContext, baseURI + "guid=" + guid);

                    var    links             = createdPayment.links.GetEnumerator();
                    string paypalRedirectUrl = string.Empty;

                    while (links.MoveNext())
                    {
                        Links link = links.Current;
                        if (link.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            paypalRedirectUrl = link.href;
                        }
                    }
                    Session.Add(guid, createdPayment.id);
                    return(Redirect(paypalRedirectUrl));
                }
                else
                {
                    var guid           = Request.Params["guid"];
                    var executePayment = ExcutePayment(apiContext, payerId, Session[guid] as string);
                    if (executePayment.state.ToLower() != "approved")
                    {
                        return(View("Fail"));
                    }
                }
            }
            catch (Exception ex)
            {
                PaypalLogger.Log("Error: " + ex.Message);
                return(View("Fail"));
            }
            Session.Remove(strCart);
            // Send mail
            db.Orders.Add(order);
            string content = System.IO.File.ReadAllText(Server.MapPath("~/Theme/client/template/order.html"));

            content = content.Replace("{{ProductName}}", TempData["PN"].ToString());
            content = content.Replace("{{Quantity}}", TempData["Quan"].ToString());
            content = content.Replace("{{Price}}", TempData["pri"].ToString());
            content = content.Replace("{{Total}}", TempData["Tot"].ToString());
            content = content.Replace("{{Date}}", DateTime.Now.ToString());
            content = content.Replace("{{CustomerName}}", cus.Username);
            content = content.Replace("{{FullName}}", cus.Customer_Name);
            var toEmail = cus.Email;


            new MailHelper().SendMail(toEmail, "Jordan Shop Receipt", content);
            db.SaveChanges();



            return(View("Success"));
        }
        public ActionResult PaymentWithPaypal(Order order)
        {
            CloseOrder(order);

            //getting the apiContext as earlier
            APIContext apiContext = PaypalConfiguration.GetAPIContext();

            try
            {
                string payerId = Request.Params["PayerID"];

                if (string.IsNullOrEmpty(payerId))
                {
                    //this section will be executed first because PayerID doesn't exist

                    //it is returned by the create function call of the payment class

                    // Creating a payment

                    // baseURL is the url on which paypal sendsback the data.

                    // So we have provided URL of this controller only

                    string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/Paypal/PaymentWithPayPal?";

                    //guid we are generating for storing the paymentID received in session

                    //after calling the create function and it is used in the payment execution

                    var guid = Convert.ToString((new Random()).Next(100000));

                    //CreatePayment function gives us the payment approval url

                    //on which payer is redirected for paypal acccount payment

                    var createdPayment = this.CreatePayment(apiContext, baseURI + "guid=" + guid);

                    //get links returned from paypal in response to Create function call

                    var links = createdPayment.links.GetEnumerator();

                    string paypalRedirectUrl = null;

                    while (links.MoveNext())
                    {
                        Links lnk = links.Current;

                        if (lnk.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            //saving the payapalredirect URL to which user will be redirected for payment
                            paypalRedirectUrl = lnk.href;
                        }
                    }

                    // saving the paymentID in the key guid
                    Session.Add(guid, createdPayment.id);

                    return(Redirect(paypalRedirectUrl));
                }
                else
                {
                    // This section is executed when we have received all the payments parameters

                    // from the previous call to the function Create

                    // Executing a payment

                    var guid = Request.Params["guid"];

                    var executedPayment = ExecutePayment(apiContext, payerId, Session[guid] as string);

                    if (executedPayment.state.ToLower() != "approved")
                    {
                        return(View("FailureView"));
                    }
                }
            }
            catch (Exception ex)
            {
                PaypalLogger.Log("Error: " + ex.Message);
                return(View("FailureView"));
            }

            return(View("SuccessView"));
        }
Example #21
0
        public ActionResult PaymentWithPaypal()
        {
            APIContext apiContext = PaypalConfiguration.GetAPIContext();

            try
            {
                string payerId = Request.Params["PayerID"];
                if (string.IsNullOrEmpty(payerId))
                {
                    //Creating Payment
                    string baseURI        = Request.Url.Scheme + "://" + Request.Url.Authority + "ShoppingCart/PaymentWithPaypal?";
                    var    guid           = Convert.ToString((new Random()).Next(100000));
                    var    createdPayment = CreatePayment(apiContext, baseURI + "guid=" + guid);

                    //Get Links returned from paypal response to create call function
                    var    links             = createdPayment.links.GetEnumerator();
                    string paypalRedirectUrl = string.Empty;

                    while (links.MoveNext())
                    {
                        Links link = links.Current;
                        if (link.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            paypalRedirectUrl = link.href;
                        }
                    }



                    MVCWEF.Models.Order order = new MVCWEF.Models.Order();
                    User user = new User();
                    user = (User)@Session["User"];
                    List <Cart> lsCart = (List <Cart>)Session[strCart];
                    using (MvcCrudDBEntities1 db = new MvcCrudDBEntities1())
                    {
                        order.UserID          = user.UserID;
                        order.CustomerAddress = user.Address;
                        order.CustomerPhone   = user.Phone;
                        order.OrderDate       = DateTime.Now;
                        order.PaymentType     = "Paypal";
                        order.StatusID        = 6;
                        db.Orders.Add(order);
                        db.SaveChanges();
                    }
                    foreach (Cart cart in lsCart)
                    {
                        OrderDetail orderdetail = new OrderDetail()
                        {
                            OrderId    = order.OrderId,
                            ProductId  = cart.Product.ProuductID,
                            Quantity   = cart.Quantity,
                            TotalPrice = ((double)cart.Product.Price * (double)cart.Quantity) + 3
                        };
                        db.OrderDetails.Add(orderdetail);
                        db.SaveChanges();
                    }
                    Session.Remove(strCart);

                    Session.Add(guid, createdPayment.id);
                    return(Redirect(paypalRedirectUrl));
                }
                else
                {
                    var guid            = Request.Params["guid"];
                    var executedPayment = ExecutePayment(apiContext, payerId, Session[guid] as string);

                    if (executedPayment.state.ToLower() != "approval")
                    {
                        return(View("Failure"));
                    }
                }
            }catch (Exception ex)
            {
                PaypalLogger.Log("Error :" + ex.Message);
                return(View("Failure"));
            }



            return(View("Success"));
        }
Example #22
0
        public async Task <ActionResult> PagoConPaypal(double?totalPagoPyapal, string totalship, string Cancel = null)
        {
            //getting the apiContext
            APIContext apiContext = PaypalConfiguration.GetAPIContext();
            var        persona    = DbModel.Personas.First(x => x.Correo == User.Identity.Name);

            try
            {
                if (totalship == "Gratis")
                {
                    totalship = "0";
                }
                string payerId = Request.Params["PayerID"];
                totalPagoPyapal -= Convert.ToInt32(totalship);
                if (string.IsNullOrEmpty(payerId))
                {
                    string baseURI   = Request.Url.Scheme + "://" + Request.Url.Authority + "/Tienda/PagoConPaypal?";
                    var    guid      = Convert.ToString((new Random()).Next(100000000));
                    var    CrearPago = this.CrearPago(apiContext, baseURI + "guid=" + guid, totalPagoPyapal, totalship);

                    var    links             = CrearPago.links.GetEnumerator();
                    string paypalRedirectURL = string.Empty;

                    while (links.MoveNext())
                    {
                        Links link = links.Current;
                        if (link.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            paypalRedirectURL = link.href;
                        }
                    }

                    Session.Add(guid, CrearPago.id);
                    return(Redirect(paypalRedirectURL));
                }
                else
                {
                    var guid            = Request.Params["guid"];
                    var executedPayment = ExecutePayment(apiContext, payerId, Session[guid] as string);
                    if (executedPayment.state.ToLower() != "approved")
                    {
                        return(View("Failure"));
                    }
                }
            }
            catch (Exception ex)
            {
                PaypalLogger.Log("Error" + ex.Message);
                return(View("Failure"));
            }
            var orderId          = DbModel.Orders.First(x => x.idPersona == persona.idPersona && x.Estatus == "Procesando");
            var orderDetails     = DbModel.OrdersDetails.Where(x => x.idOrder == orderId.IdOrder).OrderBy(x => x.idColor).ToList();
            var productos        = DbModel.Productos.ToList();
            var colores          = DbModel.Colores.ToList();
            var productosList    = DbModel.Productos.ToList();
            var inventarioDetail = DbModel.Inventarios.OrderBy(x => x.Producto.Id).ToList();


            var carritoBorrar = DbModel.CarritoCompras.Where(x => x.idPersona == persona.idPersona).ToList();


            Guid Newguid = Guid.NewGuid();

            for (int i = 0; i < carritoBorrar.Count; i++)
            {
                int idInventario = 0;
                for (int j = 1; j <= carritoBorrar[i].Cantidad; j++)
                {
                    int idProducto = carritoBorrar[i].idProducto;
                    int idColor    = carritoBorrar[i].idColor;
                    int idMaterial = carritoBorrar[i].idMaterial;

                    Proceso procesoCrear = new Proceso();
                    procesoCrear.Inventario = new Inventario();
                    procesoCrear.Order      = new Orders();
                    Inventario inventario = new Inventario();
                    inventario.Color    = new Color();
                    inventario.Material = new Material();
                    inventario.Producto = new Producto();

                    //if (carritoBorrar[i].idMaterial > 0 && carritoBorrar[i].idColor > 0)
                    //{
                    //    var ExistInv = DbModel.Inventarios.Where(x => x.Id == idInventario).ToList();

                    //    if (ExistInv.Count == 0)
                    //    {

                    //        inventario.Color = DbModel.Colores.FirstOrDefault(x => x.Id == idColor);
                    //        inventario.Producto = DbModel.Productos.FirstOrDefault(x => x.Id == idProducto);
                    //        inventario.Material = DbModel.Materiales.FirstOrDefault(x => x.Id == idMaterial);
                    //        inventario.Cantidad = 0;

                    //        DbModel.Inventarios.Add(inventario);
                    //        DbModel.SaveChanges();

                    //        idInventario = inventario.Id;

                    //    }

                    //}
                    //else
                    //{
                    idInventario = DbModel.Inventarios.FirstOrDefault(x => x.Producto.Id == idProducto && x.Color.Id == idColor).Id;
                    //}

                    procesoCrear.Id         = Guid.NewGuid().ToString();
                    procesoCrear.Nombre     = "Corte";
                    procesoCrear.Estado     = "En espera";
                    procesoCrear.Tiempo     = DateTime.Now;
                    procesoCrear.Registro   = DateTime.Now;
                    procesoCrear.Inventario = DbModel.Inventarios.FirstOrDefault(x => x.Id == idInventario);
                    procesoCrear.Order      = orderId;
                    DbModel.Procesos.Add(procesoCrear);
                    DbModel.SaveChanges();

                    DetallePedido detallePedido = new DetallePedido();
                    detallePedido.IdPedidoDetalle = Newguid.ToString();
                    detallePedido.IdProceso       = procesoCrear.Id;

                    DbModel.DetallePedidos.Add(detallePedido);
                    DbModel.SaveChanges();
                }
            }



            foreach (var item in carritoBorrar)
            {
                DbModel.CarritoCompras.Remove(item);
                DbModel.SaveChanges();
            }

            var orderPgado = DbModel.Orders.FirstOrDefault(x => x.idPersona == persona.idPersona && x.Estatus == "Procesando");

            orderPgado.Estatus = "Pagado";
            DbModel.Orders.AddOrUpdate(orderPgado);
            DbModel.SaveChanges();



            //string code = await UserManager.GenerateEmailConfirmationTokenAsync(User.Identity.GetUserId());
            var callbackUrl = Url.Action("ConsultarPedido", "Proceso", new { Id = Newguid.ToString() }, protocol: Request.Url.Scheme);
            await UserManager.SendEmailAsync(User.Identity.GetUserId(), "Pedido", callbackUrl);

            return(RedirectToAction("IndexTienda", new { pagoRealizado = "True" }));
        }
Example #23
0
        public ActionResult PaymentWithPaypal()
        {
            //
            if (Session["TaiKhoan"] == null || Session["TaiKhoan"].ToString() == "")
            {
                return(RedirectToAction("DangNhap", "KhachHang"));
            }
            if (Session["GioHang"] == null)
            {
                return(RedirectToAction("Index", "Home"));
            }
            APIContext apiContext = PaypalConfiguration.GetAPIContext();

            try
            {
                //string payerId = Request.Params["PayerID"];
                string payerId = Request.Params["PayerID"];
                if (string.IsNullOrEmpty(payerId))
                {
                    string baseURI           = Request.Url.Scheme + "://" + Request.Url.Authority + "/GioHang/PaymentWithPaypal?";
                    var    guid              = Convert.ToString((new Random()).Next(100000));
                    var    createdPayment    = CreatePayment(apiContext, baseURI + "guid=" + guid);
                    var    links             = createdPayment.links.GetEnumerator();
                    string paypalRedirectUrl = string.Empty;

                    while (links.MoveNext())
                    {
                        Links link = links.Current;
                        if (link.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            paypalRedirectUrl = link.href;
                        }
                    }
                    Session.Add(guid, createdPayment.id);
                    return(Redirect(paypalRedirectUrl));
                }
                else
                {
                    var guid            = Request.Params["guid"];
                    var executedPayment = ExecutePayment(apiContext, payerId, Session[guid] as string);
                    if (executedPayment.state.ToLower() != "approved")
                    {
                        return(View("Failure"));
                    }
                }
            }
            catch (Exception ex)
            {
                PaypalLogger.Log("Error: " + ex.Message);
                return(View("Failure"));
            }

            //Kiểm tra Giỏ hàng

            //Thêm đơn hàng
            DonHang        ddh = new DonHang();
            KhachHang      kh  = (KhachHang)Session["KhachHang"];
            List <GioHang> gh  = LayGioHang();

            ddh.maKH        = kh.maKH;
            ddh.dathanhtoan = "Đã thanh toán";
            ddh.ngaydat     = DateTime.Now;
            db.DonHang.Add(ddh);
            db.SaveChanges();
            foreach (var item in gh)
            {
                ChiTietDonHang ct = new ChiTietDonHang();

                ct.madonhang = ddh.madonhang;
                ct.maSP      = item.sMaSP;
                ct.soluong   = item.iSoLuong;
                ct.dongia    = (int)item.dGia;

                db.ChiTietDonHang.Add(ct);
            }
            db.SaveChanges();
            Session["GioHang"] = null;
            return(RedirectToAction("ThanhToanThanhCong", "GioHang"));
        }
        public ActionResult PaymentWithPaypal(int?phoneNumber, string email, string address)
        {
            List <Models.Item> cart = (List <Models.Item>)Session["cart"];

            if (phoneNumber != null)
            {
                if (User.Identity.IsAuthenticated)
                {
                    //Orders
                    var acc   = db.account.FirstOrDefault(x => x.UserName == User.Identity.Name);
                    var order = new Models.Domain.Order();
                    order.DateTimeOrder    = DateTime.Now;
                    order.Status           = null;
                    order.UserID           = acc.UserID;
                    order.OrderPhoneNumber = phoneNumber;
                    order.Address          = address;
                    order.Email            = email;
                    order.TypePayment      = 3;
                    db.order.Add(order);
                    db.SaveChanges();

                    //OrderDetail
                    foreach (var item in cart)
                    {
                        OrderDetail orderDetail = new OrderDetail
                        {
                            QuantityBuy = item.QuantityBuy,
                            Price       = item.QuantityBuy * item.product.Price,
                            OrderID     = order.OrderID,
                            ProductID   = item.product.ProductID,
                        };
                        db.orderDetail.Add(orderDetail);
                        db.SaveChanges();

                        //giảm số lượng sp sau khi đặt
                        var product = db.product.FirstOrDefault(x => x.ProductID == item.product.ProductID);
                        product.Quantity        = product.Quantity - item.QuantityBuy;
                        db.Entry(product).State = System.Data.Entity.EntityState.Modified;
                        db.SaveChanges();
                    }
                }
                else
                {
                    //Orders
                    var order = new Models.Domain.Order();
                    order.DateTimeOrder    = DateTime.Now;
                    order.Status           = null;
                    order.UserID           = null;
                    order.OrderPhoneNumber = phoneNumber;
                    order.Address          = address;
                    order.Email            = email;
                    order.TypePayment      = 3;
                    db.order.Add(order);
                    db.SaveChanges();

                    //OrderDetail
                    foreach (var item in cart)
                    {
                        OrderDetail orderDetail = new OrderDetail
                        {
                            QuantityBuy = item.QuantityBuy,
                            Price       = item.QuantityBuy * item.product.Price,
                            OrderID     = order.OrderID,
                            ProductID   = item.product.ProductID,
                        };
                        db.orderDetail.Add(orderDetail);
                        db.SaveChanges();

                        //giảm số lượng sp sau khi đặt
                        var product = db.product.FirstOrDefault(x => x.ProductID == item.product.ProductID);
                        product.Quantity        = product.Quantity - item.QuantityBuy;
                        db.Entry(product).State = System.Data.Entity.EntityState.Modified;
                        db.SaveChanges();
                    }
                }
            }
            APIContext apiContext = PaypalConfiguration.GetAPIContext();

            try
            {
                string payerId = Request.Params["PayerID"];
                if (string.IsNullOrEmpty(payerId))
                {
                    string baseURI        = Request.Url.Scheme + "://" + Request.Url.Authority + "/Cart/PaymentWithPaypal?";
                    var    guid           = Convert.ToString((new Random()).Next(100000));
                    var    createdPayment = CreatePayment(apiContext, baseURI + "guid=" + guid);

                    var    links             = createdPayment.links.GetEnumerator();
                    string paypalRedirectUrl = string.Empty;

                    while (links.MoveNext())
                    {
                        Links link = links.Current;
                        if (link.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            paypalRedirectUrl = link.href;
                        }
                    }
                    Session.Add(guid, createdPayment.id);

                    return(Redirect(paypalRedirectUrl));
                }
                else
                {
                    var guid           = Request.Params["guid"];
                    var executePayment = ExecutePayment(apiContext, payerId, Session[guid] as string);
                    if (executePayment.state.ToLower() != "approved")
                    {
                        cart.Clear();
                        return(View("Failure"));
                    }
                }
            }
            catch (Exception e)
            {
                PaypalLogger.Log("Error: " + e.Message);
                cart.Clear();
                return(View("Failure"));
            }
            cart.Clear();
            return(View("Success"));
        }
        //  Handle Payment below:


        public ActionResult PaymentWithCreditCard(Order order)
        {
            CloseOrder(order);

            //create and item for which you are taking payment
            //if you need to add more items in the list
            //Then you will need to create multiple item objects or use some loop to instantiate object
            Item item = new Item();

            item.name = "Demo Item";
            //item.currency = "USD";
            item.price    = "5";
            item.quantity = "1";
            item.sku      = "sku";

            //Now make a List of Item and add the above item to it
            //you can create as many items as you want and add to this list
            List <Item> itms = new List <Item>();

            itms.Add(item);
            ItemList itemList = new ItemList();

            itemList.items = itms;

            //Address for the payment
            Address billingAddress = new Address();

            billingAddress.city         = "NewYork";
            billingAddress.country_code = "US";
            billingAddress.line1        = "23rd street kew gardens";
            billingAddress.postal_code  = "43210";
            billingAddress.state        = "NY";


            //Now Create an object of credit card and add above details to it
            CreditCard crdtCard = new CreditCard();

            crdtCard.billing_address = billingAddress;
            crdtCard.cvv2            = "874";
            crdtCard.expire_month    = 1;
            crdtCard.expire_year     = 2020;
            crdtCard.first_name      = "Aman";
            crdtCard.last_name       = "Thakur";
            crdtCard.number          = "1234567890123456";
            crdtCard.type            = "discover";

            // Specify details of your payment amount.
            Details details = new Details();

            details.shipping = "1";
            details.subtotal = "5";
            details.tax      = "1";

            // Specify your total payment amount and assign the details object
            Amount amnt = new Amount();

            amnt.currency = "USD";
            // Total = shipping tax + subtotal.
            amnt.total   = "7";
            amnt.details = details;

            // Now make a trasaction object and assign the Amount object
            Transaction tran = new Transaction();

            tran.amount         = amnt;
            tran.description    = "Description about the payment amount.";
            tran.item_list      = itemList;
            tran.invoice_number = "your invoice number which you are generating";

            // Now, we have to make a list of trasaction and add the trasactions object
            // to this list. You can create one or more object as per your requirements

            List <Transaction> transactions = new List <Transaction>();

            transactions.Add(tran);

            // Now we need to specify the FundingInstrument of the Payer
            // for credit card payments, set the CreditCard which we made above

            FundingInstrument fundInstrument = new FundingInstrument();

            fundInstrument.credit_card = crdtCard;

            // The Payment creation API requires a list of FundingIntrument

            List <FundingInstrument> fundingInstrumentList = new List <FundingInstrument>();

            fundingInstrumentList.Add(fundInstrument);

            // Now create Payer object and assign the fundinginstrument list to the object
            Payer payr = new Payer();

            payr.funding_instruments = fundingInstrumentList;
            payr.payment_method      = "credit_card";

            // finally create the payment object and assign the payer object & transaction list to it
            Payment pymnt = new Payment();

            pymnt.intent       = "sale";
            pymnt.payer        = payr;
            pymnt.transactions = transactions;

            try
            {
                //getting context from the paypal, basically we are sending the clientID and clientSecret key in this function
                //to the get the context from the paypal API to make the payment for which we have created the object above.

                //Code for the configuration class is provided next

                // Basically, apiContext has a accesstoken which is sent by the paypal to authenticate the payment to facilitator account. An access token could be an alphanumeric string

                APIContext apiContext = PaypalConfiguration.GetAPIContext();

                // Create is a Payment class function which actually sends the payment details to the paypal API for the payment. The function is passed with the ApiContext which we received above.

                Payment createdPayment = pymnt.Create(apiContext);

                //if the createdPayment.State is "approved" it means the payment was successfull else not

                if (createdPayment.state.ToLower() != "approved")
                {
                    return(View("FailureView"));
                }
            }
            catch (PayPal.PayPalException ex)
            {
                PaypalLogger.Log("Error: " + ex.Message);
                return(View("FailureView"));
            }

            return(View("SuccessView"));
        }