예제 #1
0
        protected void Page_Load(object sender, EventArgs e)
        {
            NVPAPICaller payPalCaller = new NVPAPICaller();
            string retMsg = "";
            string token = "";

            if (Session["payment_amt"] != null)
            {
                string amt = Session["payment_amt"].ToString();

                bool ret = payPalCaller.ShortcutExpressCheckout(amt, ref token, ref 
retMsg);
                if (ret)
                {
                    Session["token"] = token;
                    Response.Redirect(retMsg);
                }
                else
                {
                    Response.Redirect("CheckoutError.aspx?" + retMsg);
                }
            }
            else
            {
                Response.Redirect("CheckoutError.aspx?ErrorCode=AmtMissing");
            }
        }
예제 #2
0
    //calls paypal API
    protected void btnConfirm_Click(object sender, EventArgs e)
    {
        Customer aCustomer = (Customer)Session["Customer"];

        NVPAPICaller payPalCaller = new NVPAPICaller();
        string retMsg = "";
        string token = "";
        string amt = "";
        string shippingAmt = "";
        string subAmt = "";

        shippingAmt = shipping.ToString();
        subAmt = subTotal.ToString();
        amt = total.ToString();
        Session["payment_amt"] = total;

        bool ret = payPalCaller.ShortcutExpressCheckout(subAmt, shippingAmt, amt, ref token, ref retMsg, aCustomer);
        if (ret)
        {
            Session["token"] = token;
            Response.Redirect(retMsg);
        }
        else
        {
            Response.Redirect("CheckoutError.aspx?" + retMsg);
        }
    }
예제 #3
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // Verify user has completed the checkout process.
            if ((string)Session["userCheckoutCompleted"] != "true")
            {
                Session["userCheckoutCompleted"] = string.Empty;
                Response.Redirect(PrizeConstants.URL_CHECKOUT_ERROR + "?" + "Desc=Unvalidated%20Checkout.");
            }

            NVPAPICaller payPalCaller = new NVPAPICaller();
            payPalCaller.SetCredentials(PrizeConstants.WALLET_USER_NAME,
                                        PrizeConstants.WALLET_PASSWORD,
                                        PrizeConstants.WALLET_SIGNATURE);

            string   retMsg             = "";
            string   token              = "";
            string   finalPaymentAmount = "";
            string   PayerID            = "";
            NVPCodec decoder            = new NVPCodec();

            token              = Session["token"].ToString();
            PayerID            = Session["payerId"].ToString();
            finalPaymentAmount = Session["payment_amt"].ToString();

            bool ret = payPalCaller.DoCheckoutPayment(finalPaymentAmount, token, PayerID, ref decoder, ref retMsg);
            if (ret)
            {
                // Retrieve PayPal confirmation value.
                string PaymentConfirmation = decoder["PAYMENTINFO_0_TRANSACTIONID"].ToString();

                TransactionId.Text = PaymentConfirmation;

                int currentOrderId = -1;
                if (Session["currentOrderId"] != string.Empty)
                {
                    currentOrderId = Convert.ToInt32(Session["currentOrderID"]);
                }

                PrizeMemberPlanManager planManager = new PrizeMemberPlanManager();
                planManager.PayMemberPlans(currentOrderId, PaymentConfirmation);

                // Clear order id.
                Session["currentOrderId"] = string.Empty;
            }
            else
            {
                Response.Redirect(PrizeConstants.URL_CHECKOUT_ERROR + "?" + retMsg);
            }
        }
    }
예제 #4
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // Verify user has completed the checkout process.
            if (Session["userCheckoutCompleted"] != "true")
            {
                Session["userCheckoutCompleted"] = "";
                Response.Redirect("CheckoutError.aspx?" + "Desc=Unvalidated%20Checkout.");
            }

            NVPAPICaller payPalCaller = new NVPAPICaller();

            string retMsg = "";
            string token = "";
            string finalPaymentAmount = "";
            string PayerID = "";
            NVPCodec decoder = new NVPCodec();

            token = Session["token"].ToString();
            PayerID = Session["payerId"].ToString();
            finalPaymentAmount = Session["payment_amt"].ToString();

            bool ret = payPalCaller.DoCheckoutPayment(finalPaymentAmount, token, PayerID, ref decoder, ref retMsg);
            if (ret)
            {
                // Retrieve PayPal confirmation value.
                string PaymentConfirmation = decoder["PAYMENTINFO_0_TRANSACTIONID"].ToString();
                TransactionId.Text = PaymentConfirmation;

                // Get dataaccess context.
                DataAccess da = new DataAccess();
                Customer aCustomer = (Customer)Session["Customer"];
                aCustomer.Orders[0].OrderID = PaymentConfirmation;
                aCustomer = CartFunctions.setOrderId(aCustomer, PaymentConfirmation);
                // Add order to DB.

                da.addCustomer(aCustomer);
                da.addOrder(aCustomer);
                da.addOrderline(aCustomer);

                // Clear Order

                aCustomer = CartFunctions.clearOrder(aCustomer);

            }
            else
            {
                Response.Redirect("CheckoutError.aspx?" + retMsg);
            }
        }
    }
예제 #5
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // Verify user has completed the checkout process.
            if (Session["userCheckoutCompleted"] != "true")
            {
                Session["userCheckoutCompleted"] = "";
                Response.Redirect("CheckoutError.aspx?" + "Desc=Unvalidated%20Checkout.");
            }

            NVPAPICaller payPalCaller = new NVPAPICaller();

            string   retMsg             = "";
            string   token              = "";
            string   finalPaymentAmount = "";
            string   PayerID            = "";
            NVPCodec decoder            = new NVPCodec();

            token              = Session["token"].ToString();
            PayerID            = Session["payerId"].ToString();
            finalPaymentAmount = Session["payment_amt"].ToString();

            bool ret = payPalCaller.DoCheckoutPayment(finalPaymentAmount, token, PayerID, ref decoder, ref retMsg);
            if (ret)
            {
                // Retrieve PayPal confirmation value.
                string PaymentConfirmation = decoder["PAYMENTINFO_0_TRANSACTIONID"].ToString();
                TransactionId.Text = PaymentConfirmation;

                // Get dataaccess context.
                DataAccess da        = new DataAccess();
                Customer   aCustomer = (Customer)Session["Customer"];
                aCustomer.Orders[0].OrderID = PaymentConfirmation;
                aCustomer = CartFunctions.setOrderId(aCustomer, PaymentConfirmation);
                // Add order to DB.

                da.addCustomer(aCustomer);
                da.addOrder(aCustomer);
                da.addOrderline(aCustomer);

                // Clear Order

                aCustomer = CartFunctions.clearOrder(aCustomer);
            }
            else
            {
                Response.Redirect("CheckoutError.aspx?" + retMsg);
            }
        }
    }
예제 #6
0
        public ActionResult PayPalCheckOut()
        {
            var    cart   = RentalCart.GetCart(this.HttpContext);
            string retMsg = "";
            string token  = "";

            if (cart.GetCartItems().Count == 0)
            {
                return(RedirectToAction("ErrorMessage", "Checkout", new { ErrorCode = ErrorCode.EMPTY_CART }));
            }

            foreach (CartItemModel c in cart.GetCartItems())
            {
                if (c.Item.Owner.Email == User.Identity.Name)
                {
                    return(RedirectToAction("ErrorMessage", "Checkout", new { ErrorCode = ErrorCode.OWNER_ITEM_IN_CART }));
                }
            }

            NVPAPICaller checkout = new NVPAPICaller(complete: Url.Action("Complete", "CheckOut", null, Request.Url.Scheme, Request.Url.Host), cancel: Url.Action("Cancel", "CheckOut", null, Request.Url.Scheme, Request.Url.Host));

            var order = new Order()
            {
                OrderId   = System.Guid.NewGuid().ToString(),
                OrderDate = DateTime.Now,
                User      = market.Users.Find(User.Identity.Name),
                Confirmed = false
            };

            market.Orders.Add(order);
            market.SaveChanges();
            cart.CreateOrder(order);

            string amt = order.Total.ToString();
            bool   ret = checkout.ShortcutExpressCheckout(amt, checkout.GetNVPFromOrder(order), ref token, ref retMsg);

            if (ret)
            {
                order.PayPalToken         = token;
                market.Entry(order).State = System.Data.EntityState.Modified;
                market.SaveChanges();
                return(Redirect(retMsg));
            }
            else
            {
                return(Redirect(Url.Action("ErrorMessage", "Checkout") + retMsg + "&Order=" + order.OrderId));
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // Verify user has completed the checkout process.
                if ((string)Session["userCheckoutCompleted"] != "true")
                {
                    Session["userCheckoutCompleted"] = string.Empty;
                    Response.Redirect("CheckoutError.aspx?" + "Desc=Unvalidated%20Checkout.");
                }

                NVPAPICaller payPalCaller = new NVPAPICaller();

                string   retMsg             = "";
                string   token              = "";
                string   finalPaymentAmount = "";
                string   PayerID            = "";
                NVPCodec decoder            = new NVPCodec();

                token              = Session["token"].ToString();
                PayerID            = Session["payerId"].ToString();
                finalPaymentAmount = Session["payment_amt"].ToString();

                bool ret = payPalCaller.DoCheckoutPayment(finalPaymentAmount, token, PayerID, ref decoder, ref retMsg);
                if (ret)
                {
                    // Retrieve PayPal confirmation value.
                    string PaymentConfirmation = decoder["PAYMENTINFO_0_TRANSACTIONID"].ToString();
                    TransactionId.Text = PaymentConfirmation;

                    var cartManager = new Logic.CartManager();
                    if (int.TryParse(Session["currentOrderID"].ToString(), out int orderId))
                    {
                        cartManager.UpdateOrderPaymentTransactionId(orderId, PaymentConfirmation);
                    }

                    // Empty the Cart
                    cartManager.EmptyCart(ShoppingCartActions.GetCartId());

                    // Clear order id.
                    Session["currentOrderId"] = string.Empty;
                }
                else
                {
                    Response.Redirect("CheckoutError.aspx?" + retMsg);
                }
            }
        }
예제 #8
0
        protected void Page_Load(object sender, EventArgs e)
        {
            NVPAPICaller payPalCaller = new NVPAPICaller();
            string       retMsg       = "";
            string       token        = "";

            List <int> ids  = new List <int>();
            Cart       cart = (Cart)Session["Cart"];

            ids = cart.getList();
            List <CartItem> ci = new List <CartItem>();

            foreach (int i in ids)
            {
                ci.Add(Connection.GetCartinfo(i));
            }
            Session["CartItems"] = ci;
            decimal amt = 0;

            foreach (CartItem c in ci)
            {
                amt += c.Price;
            }

            Session["payment_amt"] = amt;

            if (Session["payment_amt"] != null)
            {
                string amount = Session["payment_amt"].ToString();

                bool ret = payPalCaller.ShortcutExpressCheckout(amount, ref token, ref retMsg);
                if (ret)
                {
                    Session["token"] = token;
                    Response.Redirect(retMsg);
                }
                else
                {
                    Response.Redirect("CheckoutError.aspx?" + retMsg);
                }
            }
            //  else
            //{
            //    Response.Redirect("CheckoutError.aspx?ErrorCode=AmtMissing");
            // }
        }
    protected void btn_confirm_Click(object sender, EventArgs e)
    {
        NVPAPICaller test = new NVPAPICaller();

        string   retMsg             = "";
        string   token              = "";
        string   finalPaymentAmount = "";
        string   payerId            = "";
        NVPCodec decoder            = new NVPCodec();

        token              = Session["token"].ToString();
        payerId            = Session["payerId"].ToString();
        finalPaymentAmount = Session["payment_amt"].ToString();

        bool ret = test.ConfirmPayment(finalPaymentAmount, token, payerId, ref decoder, ref retMsg);

        if (ret)
        {
            // Unique transaction ID of the payment.
            string transactionId = decoder["TRANSACTIONID"];
            ViewState["trans"] = transactionId;
            // Returns "instant" if the payment is instant or "echeck" if the payment is delayed.
            string paymentType = decoder["PAYMENTTYPE"];

            // The final amount charged, including any shipping and taxes from your Merchant Profile.
            string amt = decoder["AMT"];

            // PayPal fee amount charged for the transaction
            string feeAmt = decoder["FEEAMT"];

            // Tax charged on the transaction.
            string taxAmt = decoder["TAXAMT"];

            // PayPal Manager Transaction ID that is used by PayPal to identify this transaction in PayPal Manager reports.
            //string pnref = decoder["PNREF"];
            insertbill();
            // Response.Write(transactionId + " " + paymentType + " " +amt);
            Response.Redirect("OrderConfirmation.aspx?transid=" + transactionId);
            /*caall sp*/
        }
        else
        {
            Response.Redirect("APIError.aspx?" + retMsg);
        }
    }
예제 #10
0
    public void VerifyPayment()
    {
        NVPAPICaller payPalCaller = new NVPAPICaller();
        string       retMsg       = "";
        string       token        = "";
        string       PayerID      = "";
        NVPCodec     decoder      = new NVPCodec();

        token = Session["token"].ToString();
        string currency_code = Session["currency_code"].ToString();
        bool   ret           = payPalCaller.GetCheckoutDetails(token, ref PayerID, ref decoder, ref retMsg);

        if (ret)
        {
            // Verify total payment amount as set on CheckoutStart.aspx.
            try
            {
                decimal paymentAmountOnCheckout = Convert.ToDecimal(Session["new_payment_amt"].ToString());
                decimal paymentAmoutFromPayPal  = Convert.ToDecimal(decoder["AMT"].ToString());
                if (paymentAmountOnCheckout != paymentAmoutFromPayPal)
                {
                    Response.Redirect("CheckoutError.aspx?" + "Desc=Amount%20total%20mismatch.");
                }
            }
            catch (Exception)
            {
                Response.Redirect("CheckoutError.aspx?" + "Desc=Amount%20total%20mismatch.");
            }
        }
        string finalPaymentAmount = Session["new_payment_amt"].ToString();
        bool   res = payPalCaller.DoCheckoutPayment(finalPaymentAmount, currency_code, token, PayerID, ref decoder, ref retMsg);

        if (res)
        {
            // Retrieve PayPal confirmation value.
            PaymentConfirmation = decoder["PAYMENTINFO_0_TRANSACTIONID"].ToString();
            TransactionId.Text  = " " + PaymentConfirmation;
            amountlb.Text       = " " + Session["new_payment_amt"].ToString();
            descriptionlb.Text  = " " + Session["new_item_name"].ToString();
        }
        else
        {
            Response.Redirect("CheckoutError.aspx?" + retMsg);
        }
    }
예제 #11
0
        public ActionResult ProceedCheckout()
        {
            NVPAPICaller test    = new NVPAPICaller();
            string       retMsg  = "";
            string       token   = Request.Form["Token"];
            string       PayerId = Request.Form["PayerId"];
            string       total   = Request.Form["Total"];

            var  decoder = new NVPCodec();
            bool ret     = test.ConfirmPayment(total, token, PayerId, ref decoder, ref retMsg);

            if (ret)
            {
                string paypalref        = decoder["PAYMENTINFO_0_TRANSACTIONID"];
                var    usersubscription = new UserSubscription();
                using (var db = new ApplicationDbContext())
                {
                    usersubscription.CreatedDate    = DateTime.Now;
                    usersubscription.SubscriptionId = int.Parse(TempData["SubscriptionId"].ToString());
                    usersubscription.Price          = decimal.Parse(TempData["Price"].ToString());
                    usersubscription.Month          = int.Parse(TempData["Month"].ToString());
                    usersubscription.ItemName       = TempData["ItemName"].ToString();
                    usersubscription.PaypalRef      = paypalref;
                    usersubscription.UserId         = User.Identity.Name;
                    db.UserSubscriptions.Add(usersubscription);
                    db.SaveChanges();
                }

                var taskemail = SendPaymentEmail(User.Identity.Name, usersubscription.ItemName, usersubscription.Price.ToString()
                                                 , usersubscription.Month.ToString()
                                                 , (usersubscription.Price * usersubscription.Month).ToString(), usersubscription.PaypalRef);
                // taskemail.Start();
                TempData["Success"] = "Payment Successful";
                //Response.Redirect(retMsg);
                return(RedirectToAction("Index"));
            }
            else
            {
                TempData["ConfirmError"] = retMsg;
                TempData["Total"]        = total;
                return(RedirectToAction("ConfirmCheckout", new { @token = token, @PayerID = PayerId }));
            }
        }
예제 #12
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // Verify user has completed the checkout process.
                if ((string)Session["userCheckoutCompleted"] != "true")
                {
                    Session["userCheckoutCompleted"] = string.Empty;
                    Response.Redirect("CheckoutError.aspx?" + "Desc=Unvalidated%20Checkout.");
                }
                NVPAPICaller payPalCaller       = new NVPAPICaller();
                string       retMsg             = "";
                string       token              = "";
                string       finalPaymentAmount = "";
                string       PayerID            = "";
                NVPCodec     decoder            = new NVPCodec();
                //token = Session["token"].ToString();
                PayerID            = Session["payerId"].ToString();
                finalPaymentAmount = GetFromCookie("total", null).ToString();
                //bool ret = payPalCaller.DoCheckoutPayment(finalPaymentAmount, token, PayerID, ref decoder, ref retMsg);
                if (true)
                {
                    // Retrieve PayPal confirmation value.
                    string PaymentConfirmation = GetFromCookie("transactionID", null).ToString();
                    TransactionId.Text = PaymentConfirmation;
                    ProductContext _db = new ProductContext();
                    // Get the current order id.

                    // Clear shopping cart.
                    using (WingtipToys.Logic.ShoppingCartActions usersShoppingCart = new WingtipToys.Logic.ShoppingCartActions())
                    {
                        usersShoppingCart.EmptyCart();
                    }
                    // Clear order id.
                    Session["currentOrderId"] = string.Empty;
                }
                else
                {
                    Response.Redirect("CheckoutError.aspx?" + retMsg);
                }
            }
        }
예제 #13
0
    protected void Page_Load(object sender, EventArgs e)
    {
        NVPAPICaller PayPalCaller = new NVPAPICaller();
        string retMsg = "";
        string token = "";
        string baseUrl = "";

        if (HttpContext.Current.Request.IsLocal)
        {
            baseUrl = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) +
                            HttpContext.Current.Request.ApplicationPath + "/";
        }

        if (Session["payment_amt"] != null)
        {
           // string tax = String.Format("{0:0.00}", Session["payment_tax"]);
           // string itemAmt = String.Format("{0:0.00}", Session["payment_subtotal"]);
            string amt = String.Format("{0:0.00}", Session["payment_amt"]);
            List<Items> itemList = (List<Items>)Session["shoppingCart"];
            string shipping = "";
            if(Request.QueryString["shipping"] != null)
            {
                shipping = Request.QueryString["shipping"];
                Session["shipping"] = shipping;
            }
            bool ret = PayPalCaller.ShortcutExpressCheckout(itemList, amt, baseUrl, 
                            ref token, ref retMsg, shipping);
            if (ret)
            {
				Session["token"] = token;
                Response.Redirect( retMsg );
            }
            else
            {
                Response.Redirect("APIError.aspx?" + retMsg);
            }
        }
        else
        {
            Response.Redirect( "APIError.aspx?ErrorCode=AmtMissing" );
        }
    }
예제 #14
0
        public ActionResult ProceedCheckout()
        {
            NVPAPICaller test    = new NVPAPICaller();
            string       retMsg  = "";
            string       token   = Request.Form["Token"];
            string       PayerId = Request.Form["PayerId"];

            var  decoder = new NVPCodec();
            bool ret     = test.ConfirmPayment("10", token, PayerId, ref decoder, ref retMsg);

            if (ret)
            {
                Response.Redirect(retMsg);
            }
            else
            {
                Response.Redirect("APIError.aspx?" + retMsg);
            }
            return(View());
        }
예제 #15
0
        private ActionResult PreparePayPalPayment(AspNetUser oModel)
        {
            string token  = string.Empty;
            string retMsg = string.Empty;

            NVPAPICaller PPCaller = new NVPAPICaller();
            bool         ret      = PPCaller.ExpressCheckout(oModel.FirstName + " " + oModel.LastName + " Basic Product", "BASIC", "220", "1", "USD", oModel.Email, ref token, ref retMsg);

            if (ret)
            {
                Session["token"] = token;
                return(Redirect(retMsg));
            }
            else
            {
                //PayPal has not responded successfully, let user know
                //lblError.Text = "PayPal is not responding, please try again in a few moments.";
                return(RedirectToAction("Index", "Home"));
            }

            //string IP = ConfigurationManager.AppSettings["PayPalBaseUrl"];
            //string businessPaypalId = ConfigurationManager.AppSettings["BusinessPayPalId"];
            //string businessPaypalTransction = ConfigurationManager.AppSettings["PayPalTxnUrl"];
            //double itemCost = 10.00;
            //string redirect2 = IP + @"Account/Thankyou";
            //string IPN = IP + @"Account/PayPalIPN";
            //string Cancel = IP + @"Home/Index";
            //string redirect = businessPaypalTransction+"&business=" + businessPaypalId;
            //redirect += "&amount=" + itemCost;
            //redirect += "&custom=" + oModel.Email;
            //redirect += "&address1=" + oModel.Address;
            //redirect += "&email=" + oModel.Email;
            //redirect += "&item_number=1";
            //redirect += "&currency_code= USD";
            //redirect += "&return=" + redirect2;
            //redirect += "&cancel_return=" + Cancel;
            //redirect += "&item_name=" + "Basic Package";

            //redirect += "&notify_url=" + IPN;
            //return Redirect(redirect);
        }
예제 #16
0
    //protected void btn_checkout_Click(object sender, EventArgs e)
    //{
    //   // Response.Write("<script>alert('gokul')</script>");
    //    //DataTable shipdt = (DataTable)Session["ship"];
    //    //if (shipdt == null)
    //    //{
    //    //    shipdt = new DataTable();
    //    //    shipdt.Columns.Add("FirstName");
    //    //    shipdt.Columns.Add("LastName");
    //    //    shipdt.Columns.Add("Address");
    //    //    shipdt.Columns.Add("City");
    //    //    shipdt.Columns.Add("State");
    //    //    shipdt.Columns.Add("Pincode");
    //    //    shipdt.Columns.Add("Country");
    //    //    shipdt.Columns.Add("MobileNo");
    //    //    shipdt.Columns.Add("GiftMsg");
    //    //    shipdt.Rows.Add(txtship_fname.Text, txtship_lname.Text, txtship_add1.Text, txtship_city.Text, txtship_state.Text, txtship_pin.Text, ddlship_country.SelectedItem, txtship_mno.Text,txt_giftmsg.Text);
    //    //    Session["ship"] = shipdt;
    //    //}
    //    //else
    //    //{
    //    //    shipdt.Rows.Add(txtship_fname.Text, txtship_lname.Text, txtship_add1.Text, txtship_city.Text, txtship_state.Text, txtship_pin.Text, ddlship_country.SelectedItem, txtship_mno.Text);
    //    //    if (shipdt.Rows.Count == 2) { shipdt.Rows.RemoveAt(0); }
    //    //    Session["ship"] = shipdt;
    //    //}

    // //  fvshipfill();
    ////   paypal();
    //}
    void paypal()
    {
        NVPAPICaller test = new NVPAPICaller();

        string retMsg = "";
        string token  = "";

        if (Session["payment_amt"] != null)
        {
            string amt = Session["payment_amt"].ToString();

            //Optional Shipping Address entered on the merchant site
            DataTable dt = (DataTable)Session["ship"];
            //Optional Shipping Address entered on the merchant site
            string shipToName        = dt.Rows[0]["FirstName"].ToString() + dt.Rows[0]["LastName"].ToString();
            string shipToStreet      = dt.Rows[0]["Address"].ToString();
            string shipToStreet2     = dt.Rows[0]["Address"].ToString();
            string shipToCity        = dt.Rows[0]["City"].ToString();
            string shipToState       = dt.Rows[0]["State"].ToString();
            string shipToZip         = dt.Rows[0]["Pincode"].ToString();
            string shipToCountryCode = "NULL";

            bool ret = test.MarkExpressCheckout(amt, shipToName, shipToStreet, shipToStreet2,
                                                shipToCity, shipToState, shipToZip, shipToCountryCode,
                                                ref token, ref retMsg);
            if (ret)
            {
                Session["token"] = token;
                Response.Redirect(retMsg);
            }
            else
            {
                Response.Redirect("APIError.aspx?" + retMsg);
            }
        }
        else
        {
            Response.Redirect("APIError.aspx?ErrorCode=AmtMissing");
        }
    }
예제 #17
0
        /// <summary>
        ///  Stores the information and proceeds to PayPal payment page.
        /// </summary>
        protected void PayPalBtn_Click(object sender, EventArgs e)
        {
            try
            {
                AddressManager address;
                long           vehicleAvailableID, locationID, customerID;
                DateTime       hireStart, hireEnd;
                NVPAPICaller   payPalCaller = new NVPAPICaller();
                string         retMsg = "";
                string         token = "";
                double         totalDays, totalCost;

                address            = (AddressManager)Session["Address"];
                vehicleAvailableID = (long)Session["VehicleAvailableID"];
                locationID         = (long)Session["LocationID"];
                hireStart          = (DateTime)Session["StartTime"];
                hireEnd            = (DateTime)Session["EndTime"];
                customerID         = (long)Session["CustomerID"];

                VehicleManager vehicle = VehicleManager.GetAvailableVehicles(locationID).Where(x => x.VehicleAvailableID == vehicleAvailableID).SingleOrDefault();

                totalDays = (hireEnd - hireStart).TotalDays;
                totalCost = totalDays * vehicle.BasePrice;
                totalCost = Math.Round(totalCost, 2); //Round to 2 dp

                bool ret = payPalCaller.ShortcutExpressCheckout(totalCost.ToString(), ref token, ref retMsg, vehicle.Manufacturer + " " + vehicle.Model, vehicle.Currency);
                if (ret)
                {
                    Session["token"] = token;
                    Response.Redirect(retMsg, false);
                }

                orderConfirmedLbl.Text = "Order Created";
            }
            catch (Exception ex)
            {
                generalErrorLbl.Text = "An error has occured saying: " + ex.Message + " Please contact your system administrator.";
            }
        }
    protected void paypalorderreview()
    {
        NVPAPICaller test = new NVPAPICaller();

        string retMsg          = "";
        string token           = "";
        string payerId         = "";
        string shippingAddress = "";

        token = Session["token"].ToString();

        //bool ret = test.GetShippingDetails(token, ref payerId, ref shippingAddress, ref retMsg);
        //if (ret)
        // {
        Session["payerId"] = Request.QueryString["PayerID"];
        //    Response.Write(shippingAddress);
        //}
        //else
        //{
        //    Response.Redirect("APIError.aspx?" + retMsg);
        //}
    }
예제 #19
0
        /// <summary>
        ///  Completes the PayPal transaction.
        /// </summary>
        private bool CompletePayment(double totalCost, string currency, ref string payerID)
        {
            NVPAPICaller payPalCaller = new NVPAPICaller();

            string   retMsg  = "";
            string   token   = "";
            NVPCodec decoder = new NVPCodec();

            if (Session["token"] != null)
            {
                token = Session["token"].ToString();
            }

            bool ret = payPalCaller.GetCheckoutDetails(token, ref payerID, ref decoder, ref retMsg);

            if (ret == false)
            {
                Response.Redirect("~/Account/InformUser.aspx?InfoString=Please+complete+PayPal+payment.", false);
            }

            ret = payPalCaller.DoCheckoutPayment(totalCost.ToString(), token, payerID, ref decoder, ref retMsg, currency);

            return(ret);
        }
예제 #20
0
    protected void Page_Load(object sender, EventArgs e)
    {
        NVPAPICaller payPalAPI          = new NVPAPICaller();
        decimal      finalAmountDec     = Convert.ToDecimal(HttpContext.Current.Session["payment_amt"]);
        decimal      shipping           = Convert.ToDecimal(HttpContext.Current.Session["shipping_amt"]);
        string       finalAmount        = (finalAmountDec + shipping).ToString("#.##");
        string       productDescription = HttpContext.Current.Session["product_description"].ToString();
        //string token = HttpContext.Current.Session["token"].ToString();
        string   token    = HttpContext.Current.Request.QueryString["token"].ToString();
        string   payerID  = HttpContext.Current.Request.QueryString["PayerID"].ToString();
        string   retMsg   = "Transaction was a success, enjoy your SkiChair product!";
        NVPCodec nvpCodec = new NVPCodec();

        bool ret = payPalAPI.ConfirmPayment(finalAmount, productDescription, token, payerID, ref nvpCodec, ref retMsg);

        if (ret)
        {
            // send order success email
            MailMessage eMail = new MailMessage();
            eMail.To.Add(ConfigurationManager.AppSettings["SMTPEmail"]);
            eMail.Subject = "SkiChair.com Order";
            eMail.Body    = DateTime.Now + " - Order from SkiChair.com <br /><br />" + productDescription + "<br /><br />Phone Number: <br />" + HttpContext.Current.Session["PhoneNumber"];
            //eMail.From = new MailAddress(txtEmail.Text, txtName.Text);
            eMail.IsBodyHtml = true;
            SmtpClient smtp = new SmtpClient(ConfigurationManager.AppSettings["SMTPHost"]);
            smtp.Send(eMail);

            //Response.Redirect("OrderSuccess.aspx&msg=" + retMsg);
            Response.Redirect("OrderSuccess.aspx");
        }
        else
        {
            //Response.Redirect("OrderError.aspx&msg=" + retMsg);
            Response.Redirect("OrderError.aspx");
        }
    }
예제 #21
0
    //private double tax;
    //private double total;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["shoppingCart"] != null && Session["token"] != null && Session["payment_amt"] != null
                && Session["shipping"] != null)
        {
            shoppingList = (List<Items>)Session["shoppingCart"];
            shippingPrice = Convert.ToDouble(Session["shipping"]);

            NVPAPICaller test = new NVPAPICaller();

            string retMsg = "";
            string token = "";
            string payerID = "";
            string shippingAddress = "";

            token = Session["token"].ToString();

            bool ret = test.GetShippingDetails(token, ref payerID, ref shippingAddress, ref retMsg);
            if (ret)
            {
                Session["payerId"] = payerID;

                tableBuilder += shippingAddress;

                tableBuilder += "<br /><table class=\"fullSize\"><tr><td class=\"tdOrderReviewHeader\">" +
                        "<div class=\"divOrderReviewHeaderBiggerDetails\">Product</div>" +
                        "<div class=\"divOrderReviewHeaderBiggerDetails\">Description</div>" +
                        "<div class=\"divOrderReviewHeaderSmallerDetails\">Item Price</div>" +
                        "<div class=\"divOrderReviewHeaderSmallerDetails\">Qty</div>" +
                        "<div style=\"padding-left: 5px\" class=\"divOrderReviewHeaderSmallerDetails\">Item Total</div>" +
                    "</td></tr>";

                foreach (Items item in shoppingList)
                {
                    string index = shoppingList.IndexOf(item).ToString();
                    string itemType = item.GetType().ToString();

                    if (item.GetType().ToString() == "Frames")
                    {
                        string glassesID = ((Frames)item).glassesID;
                        string name = ((Frames)item).name;
                        string rightSph = ((Frames)item).rightSph;
                        string rightCyl = ((Frames)item).rightCyl;
                        string rightAxis = ((Frames)item).rightAxis;
                        string rightPd = ((Frames)item).rightPd;
                        string leftSph = ((Frames)item).leftSph;
                        string leftCyl = ((Frames)item).leftCyl;
                        string leftAxis = ((Frames)item).leftAxis;
                        string leftPd = ((Frames)item).leftPd;
                        string lensIndex = ((Frames)item).lensIndex;
                        double price = ((Frames)item).price;
                        string image1 = ((Frames)item).image1;
                        subtotal += price;

                        tableBuilder += "<tr><td class=\"tdOrderReviewMain\">" +
                        "<div class=\"divOrderReviewHeaderBiggerDetails\"><a href=\"Product/Frame.aspx?id=" + glassesID + "\">" + name + "</a></div>" +
                        "<div class=\"divOrderReviewHeaderBiggerDetails\">Left eye: (" + leftSph + " SPH) (" + leftCyl + " CYL) (" + leftAxis + " AXIS) <br/> (" + leftPd + " MPD)<br />" +
                            "Right eye: (" + rightSph + " SPH) (" + rightCyl + " CYL) (" + rightAxis + " AXIS) <br/> (" + rightPd + " MPD)<br /> Lens option : " + lensIndex +"</div>" +
                        "<div class=\"divOrderReviewHeaderSmallerDetails\">" + String.Format("{0:C}", price) + "</div>" +
                        "<div class=\"divOrderReviewHeaderSmallerDetails\">1</div>" +
                        "<div style=\"padding-left: 5px\" class=\"divOrderReviewHeaderSmallerDetails\">" + String.Format("{0:C}", price) + "</div>";
                    }
                    else if (item.GetType().ToString().Contains("Sunglasses"))
                    {
                        string id = item.id;
                        string name = item.name;
                        string image1 = item.image1;
                        int qty = item.qty;
                        double price = Convert.ToDouble(item.price);
                        double totalPrice = Convert.ToDouble(price * item.qty);
                        subtotal += totalPrice;

                        tableBuilder += "<tr><td class=\"tdOrderReviewMain\">" +
                        "<div class=\"divOrderReviewHeaderBiggerDetails\"><a href=\"Product/Sunglass.aspx?id=" + id + "\">" + name + "</a></div>" +
                        "<div class=\"divOrderReviewHeaderBiggerDetails\">&nbsp;</div>" +
                        "<div class=\"divOrderReviewHeaderSmallerDetails\">" + String.Format("{0:C}", price) + "</div>" +
                        "<div class=\"divOrderReviewHeaderSmallerDetails\">" + qty + "</div>" +
                        "<div style=\"padding-left: 5px\" class=\"divOrderReviewHeaderSmallerDetails\">" + String.Format("{0:C}", totalPrice) + "</div>";
                    }
                    else if (item.GetType().ToString().Contains("ReadyReaders"))
                    {
                        string id = item.id;
                        string name = item.name;
                        string power = item.power;
                        string image1 = item.image1;
                        int qty = item.qty;
                        double price = Convert.ToDouble(item.price);
                        double totalPrice = Convert.ToDouble(price * item.qty);
                        subtotal += totalPrice;

                        tableBuilder += "<tr><td class=\"tdOrderReviewMain\">" +
                        "<div class=\"divOrderReviewHeaderBiggerDetails\"><a href=\"Product/ReadyReader.aspx?id=" + id + "\">" + name + "</a></div>" +
                        "<div class=\"divOrderReviewHeaderBiggerDetails\">Power: (" + power + ")</div>" +
                        "<div class=\"divOrderReviewHeaderSmallerDetails\">" + String.Format("{0:C}", price) + "</div>" +
                        "<div class=\"divOrderReviewHeaderSmallerDetails\">" + qty + "</div>" +
                        "<div style=\"padding-left: 5px\" class=\"divOrderReviewHeaderSmallerDetails\">" + String.Format("{0:C}", totalPrice) + "</div>";
                    }

                    else if (item.GetType().ToString().Contains("Solutions"))
                    {
                        string id = item.id;
                        string name = item.name;
                        string image1 = item.image1;
                        int qty = item.qty;
                        double price = Convert.ToDouble(item.price);
                        double totalPrice = Convert.ToDouble(price * item.qty);
                        subtotal += totalPrice;

                        tableBuilder += "<tr><td class=\"tdOrderReviewMain\">" +
                        "<div class=\"divOrderReviewHeaderBiggerDetails\"><a href=\"Product/Solution.aspx?id=" + id + "\">" + name + "</a></div>" +
                        "<div class=\"divOrderReviewHeaderBiggerDetails\">&nbsp;</div>" +
                        "<div class=\"divOrderReviewHeaderSmallerDetails\">" + String.Format("{0:C}", price) + "</div>" +
                        "<div class=\"divOrderReviewHeaderSmallerDetails\">" + qty + "</div>" +
                        "<div style=\"padding-left: 5px\" class=\"divOrderReviewHeaderSmallerDetails\">" + String.Format("{0:C}", totalPrice) + "</div>";
                    }
                    else if (item.GetType().ToString().Contains("Accessories"))
                    {
                        string id = item.id;
                        string name = item.name;
                        string image1 = item.image1;
                        int qty = item.qty;
                        double price = Convert.ToDouble(item.price);
                        double totalPrice = Convert.ToDouble(price * item.qty);
                        subtotal += totalPrice;

                        tableBuilder += "<tr><td class=\"tdOrderReviewMain\">" +
                        "<div class=\"divOrderReviewHeaderBiggerDetails\"><a href=\"Product/Accessory.aspx?id=" + id + "\">" + name + "</a></div>" +
                        "<div class=\"divOrderReviewHeaderBiggerDetails\">&nbsp;</div>" +
                        "<div class=\"divOrderReviewHeaderSmallerDetails\">" + String.Format("{0:C}", price) + "</div>" +
                        "<div class=\"divOrderReviewHeaderSmallerDetails\">" + qty + "</div>" +
                        "<div style=\"padding-left: 5px\" class=\"divOrderReviewHeaderSmallerDetails\">" + String.Format("{0:C}", totalPrice) + "</div>";
                    }
                    else if (item.GetType().ToString() == "Contacts")
                    {
                        string id = ((Contacts)item).id;
                        string name = ((Contacts)item).name;
                        int leftQty = ((Contacts)item).leftQty;
                        string leftPower = ((Contacts)item).leftPower;
                        string leftBaseCurve = ((Contacts)item).leftBaseCurve;
                        string leftDiameter = ((Contacts)item).leftDiameter;
                        int rightQty = ((Contacts)item).rightQty;
                        string rightPower = ((Contacts)item).rightPower;
                        string rightBaseCurve = ((Contacts)item).rightBaseCurve;
                        string rightDiameter = ((Contacts)item).rightDiameter;
                        double price = ((Contacts)item).price;
                        string image = ((Contacts)item).image;
                        double leftPrice = Convert.ToDouble(leftQty * price);
                        double rightPrice = Convert.ToDouble(rightQty * price);
                        double totalPrice = leftPrice + rightPrice;
                        subtotal += totalPrice;

                        tableBuilder += "<tr><td class=\"tdOrderReviewMain\">" +
                        "<div class=\"divOrderReviewHeaderBiggerDetails\"><a href=\"Product/ContactLens.aspx?id=" + id + "\">" + name + "</a></div>" +
                        "<div class=\"divOrderReviewHeaderBiggerDetails\">Left eye: (" + leftPower + " Power) | (" + leftBaseCurve + " BC) | (" + leftDiameter + " Diameter)<br />" +
                            "Right eye: (" + rightPower + " Power) | (" + rightBaseCurve + " BC) | (" + rightDiameter + " Diameter)</div>" +
                        "<div class=\"divOrderReviewHeaderSmallerDetails\">" + String.Format("{0:C}", price) + "<br /> " + String.Format("{0:C}", price) + "</div>" +
                        "<div class=\"divOrderReviewHeaderSmallerDetails\">" + leftQty + "<br />" + rightQty + "</div>" +
                        "<div style=\"padding-left: 5px\" class=\"divOrderReviewHeaderSmallerDetails\">" + String.Format("{0:C}", rightPrice) + "<br /> " + String.Format("{0:C}", leftPrice) + "</div>";
                    }
                }

                orderTotalPrice = shippingPrice + subtotal;

                tableBuilder += "<tr><td class=\"tdOrderReviewFooter\">" +
                        "<div class=\"divOrderReviewFooter1\">&nbsp;</div>" +
                        "<div style=\"padding-top: 5px\" class=\"divOrderReviewFooter2\">Merchandise Subtotal:</div>" +
                        "<div style=\"padding-top: 5px\" class=\"divOrderReviewFooter3\">" + String.Format("{0:C}", subtotal) + " CAD</div>" +
                        "<div class=\"divOrderReviewFooter4\">&nbsp;</div>" +
                        "<div class=\"divOrderReviewFooter1\">&nbsp;</div>" +
                        "<div class=\"divOrderReviewFooter2\">Shipping:</div>" +
                        "<div class=\"divOrderReviewFooter3\">" + String.Format("{0:C}", shippingPrice) + " CAD</div>" +
                        "<div class=\"divOrderReviewFooter4\">&nbsp;</div>" +
                        "<div class=\"divOrderReviewFooter1\">&nbsp;</div>" +
                        "<div style=\"padding-bottom: 5px\" class=\"divOrderReviewFooter2\">Total:</div>" +
                        "<div style=\"padding-bottom: 5px\" class=\"divOrderReviewFooter3\">" + String.Format("{0:C}", orderTotalPrice) + " CAD</div>" +
                        "<div class=\"divOrderReviewFooter4\">&nbsp;</div>" +
                        "</td></tr></table>";
                lblShippingAddress.Text = tableBuilder;
            }
            else
            {
                Response.Redirect("APIError.aspx?" + retMsg);
            }
        }
        else
        {
            Response.Redirect("Home.aspx");
        }
    }
        public async Task<ActionResult> Complete(OrderModel order)
        {
            try
            {
                // TODO: Complete the payment processing via the gateway and update the order...
                var gatewayCaller = new NVPAPICaller(_config, HttpContext);
                var finalPaymentAmount = string.Empty;
                var decoder = new NVPCodec();

                var token = HttpContext.Session.GetString("token");
                //PayerID = Session["payerId"].ToString();
                //finalPaymentAmount = Session["payment_amt"].ToString();
                finalPaymentAmount = order.Total.ToString("C2");

                var ret = gatewayCaller.DoCheckoutPayment(finalPaymentAmount, token, ref decoder);
                if (ret)
                {
                    // Retrieve PayPal confirmation value.
                    string PaymentConfirmation = decoder[NVPProperties.Properties.TRANSACTIONID].ToString();
                    order.PaymentTransactionId = PaymentConfirmation;

                    // Get the current order id.
                    int currentOrderId = -1;
                    if (HttpContext.Session.GetInt32("currentOrderId") != null && HttpContext.Session.GetInt32("currentOrderId")?.ToString() != string.Empty)
                    {
                        currentOrderId = Convert.ToInt32(HttpContext.Session.GetInt32("currentOrderId"));
                    }
                    Order myCurrentOrder;
                    if (currentOrderId >= 0)
                    {
                        // Get the order based on order id.
                        myCurrentOrder = _db.Orders.Single(o => o.OrderId == currentOrderId);
                        // Update the order to reflect payment has been completed.
                        myCurrentOrder.PaymentTransactionId = PaymentConfirmation;
                        // Save to DB.
                        await _db.SaveChangesAsync();

                        // Queue up a receipt generation request, asynchronously.
                        await new AzureQueueHelper(_config).QueueReceiptRequest(myCurrentOrder);

                        // Report successful event to Application Insights.
                        var eventProperties = new Dictionary<string, string>();
                        eventProperties.Add("CustomerEmail", myCurrentOrder.Email);
                        eventProperties.Add("OrderTotal", finalPaymentAmount);
                        eventProperties.Add("PaymentTransactionId", PaymentConfirmation);
                        TelemetryHelper.TrackEvent("OrderCompleted", eventProperties);
                    }

                    // Clear shopping cart.
                    var usersShoppingCart = new ShoppingCartActions(_db, CartId);
                    
                    await usersShoppingCart.EmptyCart();
                    

                    // Clear order id.
                    HttpContext.Session.Remove("currentOrderId");
                }
                else
                {
                    var error = gatewayCaller.PopulateGatewayErrorModel(decoder);

                    // Report failed event to Application Insights.
                    Exception ex = new Exception(error.ToString());
                    ex.Source = "Contoso.Apps.SportsLeague.Web.CheckoutController.cs";
                    TelemetryHelper.TrackException(ex);

                    // Redirect to the checkout error view:
                    return RedirectToAction("Error", error);
                }
            }
            catch (WebException wex)
            {
                ExceptionUtility.LogException(wex, "CheckoutController.cs Complete Action");

                var error = new CheckoutErrorModel
                {
                    ErrorCode = wex.Message
                };

                if (wex.Response != null && wex.Response.GetType() == typeof(HttpWebResponse))
                {
                    // Extract the response body from the WebException's HttpWebResponse:
                    error.LongMessage = ((HttpWebResponse)wex.Response).StatusDescription;
                }

                // Redirect to the checkout error view:
                return RedirectToAction("Error", error);
            }
            catch (Exception ex)
            {
                ExceptionUtility.LogException(ex, "CheckoutController.cs Complete Action");

                var error = new CheckoutErrorModel
                {
                    ErrorCode = ex.Message
                };

                // Redirect to the checkout error view:
                return RedirectToAction("Error", error);
            }

            return View(order);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                NVPAPICaller payPalCaller = new NVPAPICaller();

                string retMsg = "";
                string token = "";
                string PayerID = "";
                NVPCodec decoder = new NVPCodec();
                token = Session["token"].ToString();

                bool ret = payPalCaller.GetCheckoutDetails(token, ref PayerID, ref decoder, ref retMsg);
                if (ret)
                {
                    Session["payerID"] = PayerID;

                    var myOrder = new Order();
                    myOrder.OrderDate = Convert.ToDateTime(decoder["TIMESTAMP"].ToString());
                    myOrder.Username = User.Identity.Name;
                    myOrder.FirstName = decoder["FIRSTNAME"].ToString();
                    myOrder.LastName = decoder["LASTNAME"].ToString();
                    myOrder.Address = decoder["STREETADDRESS"].ToString();
                    myOrder.City = decoder["CITY"].ToString();
                    myOrder.County = decoder["COUNTY"].ToString();
                    myOrder.Postcode = decoder["POSTCODE"].ToString();
                    myOrder.Country = decoder["COUNTRY"].ToString();
                    myOrder.Email = decoder["EMAIL"].ToString();
                    myOrder.Total = Convert.ToDecimal(decoder["AMT"].ToString());

                    //verify total payment amount as set on checkoutstart.aspx
                    try
                    {
                        decimal paymentAmountOnCheckout = Convert.ToDecimal(Session["payment_amt"].ToString());
                        decimal paymentAmountFromPaypal = Convert.ToDecimal(decoder["AMT"].ToString());
                        if (paymentAmountOnCheckout != paymentAmountFromPaypal)
                        {
                            Response.Redirect("CheckoutError.aspx?" + "Desc=Amount%20total%20mismatch.");
                        }
                    }
                    catch (Exception)
                    {
                        Response.Redirect("CheckoutError.aspx?" + "Desc=Amount%20total%20mismatch.");
                    }

                    //Get DB context
                    CarContext _db = new CarContext();

                    //Add order to DB
                    _db.Orders.Add(myOrder);
                    _db.SaveChanges();

                    //Get the shopping cart items and then process them
                    using (NewportCars.Logic.ShoppingCartActions usersShoppingCart = new NewportCars.Logic.ShoppingCartActions())
                    {
                        List<CartItem> myOrderList = usersShoppingCart.GetCartItems();

                        //add orderdetail information to the db for each car bought
                        for (int i = 0; i < myOrderList.Count; i++)
                        {
                            //create a new orderdetail object
                            var myOrderDetail = new OrderDetail();
                            myOrderDetail.OrderId = myOrder.OrderId;
                            myOrderDetail.Username = User.Identity.Name;
                            myOrderDetail.CarId = myOrderList[i].CarID;
                            myOrderDetail.CarPrice = myOrderList[i].Car.CarPrice;

                            //add order detail to db
                            _db.OrderDetails.Add(myOrderDetail);
                            _db.SaveChanges();
                        }

                        //set OrderId
                        Session["currentOrderId"] = myOrder.OrderId;

                        //display order information
                        List<Order> orderList = new List<Order>();
                        orderList.Add(myOrder);
                        DeliveryInfo.DataSource = orderList;
                        DeliveryInfo.DataBind();

                        //display orderdetails
                        OrderItemList.DataSource = myOrderList;
                        OrderItemList.DataBind();
                    }
                }
                else
                {
                    Response.Redirect("CheckoutError.aspx?" + retMsg);
                }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // Verify user has completed the checkout process.
                if ((string)Session["userCheckoutCompleted"] != "true")
                {
                    Session["userCheckoutCompleted"] = string.Empty;
                    Response.Redirect("CheckoutError.aspx?" + "Desc=Unvalidated%20Checkout.");
                }

                NVPAPICaller payPalCaller = new NVPAPICaller();

                string retMsg = "";
                string token = "";
                string finalPaymentAmount = "";
                string PayerID = "";
                NVPCodec decoder = new NVPCodec();

                token = Session["token"].ToString();
                PayerID = Session["payerId"].ToString();
                finalPaymentAmount = Session["payment_amt"].ToString();

                bool ret = payPalCaller.DoCheckoutPayment(finalPaymentAmount, token, PayerID, ref decoder, ref retMsg);
                if (ret)
                {
                    // Retrieve PayPal confirmation value.
                    string PaymentConfirmation = decoder["PAYMENTINFO_0_TRANSACTIONID"].ToString();
                    TransactionId.Text = PaymentConfirmation;


                    ProductContext _db = new ProductContext();
                    // Get the current order id.
                    int currentOrderId = -1;
                    if (Session["currentOrderId"] != string.Empty)
                    {
                        currentOrderId = Convert.ToInt32(Session["currentOrderID"]);
                    }
                    Order myCurrentOrder;
                    if (currentOrderId >= 0)
                    {
                        // Get the order based on order id.
                        myCurrentOrder = _db.Orders.Single(o => o.OrderId == currentOrderId);
                        // Update the order to reflect payment has been completed.
                        myCurrentOrder.PaymentTransactionId = PaymentConfirmation;
                        // Save to DB.
                        _db.SaveChanges();
                    }

                    // Clear shopping cart.
                    using (WingTipToys.Logic.ShoppingCartActions usersShoppingCart =
                        new WingTipToys.Logic.ShoppingCartActions())
                    {
                        usersShoppingCart.EmptyCart();
                    }

                    // Clear order id.
                    Session["currentOrderId"] = string.Empty;
                }
                else
                {
                    Response.Redirect("CheckoutError.aspx?" + retMsg);
                }
            }
        }
예제 #25
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                NVPAPICaller payPalCaller = new NVPAPICaller();

                string   retMsg  = "";
                string   token   = "";
                string   PayerID = "";
                NVPCodec decoder = new NVPCodec();
                token = Session["token"].ToString();

                bool ret = payPalCaller.GetCheckoutDetails(token, ref PayerID, ref decoder, ref retMsg);
                if (ret)
                {
                    Session["payerId"] = PayerID;

                    var myOrder = new Order1();
                    myOrder.OrderDate  = Convert.ToDateTime(decoder["TIMESTAMP"].ToString());
                    myOrder.Username   = User.Identity.Name;
                    myOrder.FirstName  = decoder["FIRSTNAME"].ToString();
                    myOrder.LastName   = decoder["LASTNAME"].ToString();
                    myOrder.Address    = decoder["SHIPTOSTREET"].ToString();
                    myOrder.City       = decoder["SHIPTOCITY"].ToString();
                    myOrder.State      = decoder["SHIPTOSTATE"].ToString();
                    myOrder.PostalCode = decoder["SHIPTOZIP"].ToString();
                    myOrder.Country    = decoder["SHIPTOCOUNTRYCODE"].ToString();
                    myOrder.Email      = decoder["EMAIL"].ToString();
                    // myOrder.Total = Convert.ToDecimal(decoder["AMT"].ToString());
                    //myOrder.Total = decimal.Parse(decoder["AMT"].ToString());
                    var culture = CultureInfo.InvariantCulture;


                    //   int total = Convert.ToInt32(decoder["AMT"].ToString());
                    myOrder.Total = Decimal.Parse(decoder["AMT"].ToString(), culture);


                    // Verify total payment amount as set on CheckoutStart.aspx.
                    try
                    {
                        decimal paymentAmountOnCheckout = Convert.ToDecimal(Session["TotalPrice"].ToString());
                        //  decimal paymentAmoutFromPayPal = Convert.ToDecimal(decoder["AMT"].ToString());
                        decimal paymentAmountFromPayPal = myOrder.Total;
                        if (paymentAmountOnCheckout != paymentAmountFromPayPal)
                        {
                            Response.Redirect("~/Checkout/CheckoutError.aspx?" + "Desc=Amount%20total%20mismatch.");
                        }
                    }
                    catch (Exception)
                    {
                        Response.Redirect("~/Checkout/CheckoutError.aspx?" + "Desc=Amount%20total%20mismatch.");
                    }

                    //// Calling ShoppingCart object here

                    ShoppingCart k = new ShoppingCart();

                    //// Save orderDetails  and CustomerDetails to the DB.

                    k.SaveOrderDetails(myOrder);
                    k.SaveCustomerDetails();

                    //Set OrderId.


                    string currentOrderId = ConnectionClass.GetMaxOrderId();

                    Session["currentOrderId"] = currentOrderId;


                    // Get the Shopping Cart Products
                    DataTable dt = (DataTable)Session["MyCart"];


                    DataTable myOrderDetail = new DataTable();
                    myOrderDetail.Columns.Add("ProductID", typeof(string));
                    myOrderDetail.Columns.Add("ProductName", typeof(string));
                    myOrderDetail.Columns.Add("ProductPrice", typeof(string));
                    myOrderDetail.Columns.Add("ProductQuantity", typeof(string));

                    DataRow dr = myOrderDetail.NewRow();

                    // Display OrderDetail information to the Review page for each product purchased.
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        dr["ProductID"]       = Convert.ToInt32(dt.Rows[i]["ProductID"]);
                        dr["ProductName"]     = dt.Rows[i]["Name"].ToString();
                        dr["ProductPrice"]    = dt.Rows[i]["Price"].ToString();
                        dr["ProductQuantity"] = Convert.ToInt32(dt.Rows[i]["ProductQuantity"]);

                        myOrderDetail.Rows.Add(dr);
                    }


                    // Display OrderDetails.
                    OrderItemList.DataSource = myOrderDetail;
                    OrderItemList.DataBind();

                    // Add OrderDetail information to the DB for each product purchased.
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        // Create a new OrderDetail object.
                        ShoppingCart orderDetail = new ShoppingCart()
                        {
                            ProductID       = Convert.ToInt32(dt.Rows[i]["ProductID"]),
                            ProductName     = dt.Rows[i]["Name"].ToString(),
                            ProductPrice    = dt.Rows[i]["Price"].ToString(),
                            ProductQuantity = Convert.ToInt32(dt.Rows[i]["ProductQuantity"])
                        };

                        orderDetail.AddOrders();
                    }



                    // Display Order information.

                    List <Order1> orderList = new List <Order1>();
                    orderList.Add(myOrder);
                    ShipInfo.DataSource = orderList;
                    ShipInfo.DataBind();
                }
                else
                {
                    Response.Redirect("~/Checkout/CheckoutError.aspx?" + retMsg);
                }
            }
        }
예제 #26
0
    protected void Page_Load(object sender, EventArgs e)
    {
        double subTotal = 0;
        double total    = 0;
        double shipping = 00;

        if (!IsPostBack)
        {
            NVPAPICaller payPalCaller = new NVPAPICaller();

            string retMsg   = "";
            string token    = "";
            string PayerID  = "";
            string foreName = "";
            string surName  = "";
            string email    = "";
            string address  = "";
            string postcode = "";
            string town     = "";

            NVPCodec decoder = new NVPCodec();
            token = Session["token"].ToString();

            bool ret = payPalCaller.GetCheckoutDetails(token, ref PayerID, ref decoder, ref retMsg);
            if (ret)
            {
                //get user information from papal
                Session["payerId"] = PayerID;

                foreName = decoder["FIRSTNAME"].ToString();
                surName  = decoder["LASTNAME"].ToString();
                address  = decoder["SHIPTOSTREET"].ToString();
                town     = decoder["SHIPTOCITY"].ToString();
                postcode = decoder["SHIPTOZIP"].ToString();
                email    = decoder["EMAIL"].ToString();

                //display user information
                lblFore.Text     = foreName;
                lblSur.Text      = surName;
                lblCity.Text     = town;
                lblEmail.Text    = email;
                lblPostCode.Text = postcode;
                lblAddress.Text  = address;


                //set customer object with information from paypal
                Customer aCustomer = (Customer)Session["Customer"];
                aCustomer.CityAddress   = town;
                aCustomer.Email         = email;
                aCustomer.FName         = foreName;
                aCustomer.SName         = surName;
                aCustomer.StreetAddress = address;
                aCustomer.PostCode      = postcode;


                // Verify total payment amount as set on CheckoutStart.aspx.
                try
                {
                    decimal paymentAmountOnCheckout = Convert.ToDecimal(Session["payment_amt"].ToString());
                    decimal paymentAmoutFromPayPal  = Convert.ToDecimal(decoder["AMT"].ToString());
                    shipping = Convert.ToDouble(decoder["SHIPPINGAMT"].ToString());
                    if (paymentAmountOnCheckout != paymentAmoutFromPayPal)
                    {
                        Response.Redirect("CheckoutError.aspx?" + "Desc=Amount%20total%20mismatch.");
                    }
                }
                catch (Exception)
                {
                    Response.Redirect("CheckoutError.aspx?" + "Desc=Amount%20total%20mismatch.");
                }

                // Display Order information.

                var query = from goods in aCustomer.Orders[0].OrderLines
                            select new
                {
                    Name        = goods.Product.ProdName,
                    Description = goods.Product.ProdDescription,
                    Price       = goods.Product.ProdPrice,
                    Qty         = goods.Quantity,
                    Total       = "£" + Convert.ToString(goods.Quantity * goods.Product.ProdPrice),
                    ProdImage   = goods.Product.ProdImage
                };


                GridView1.DataSource = query;
                GridView1.DataBind();

                subTotal = CartFunctions.getSubTotal(aCustomer);

                cellSub.Text      = "£" + Convert.ToString(subTotal);
                total             = subTotal + shipping;
                cellTotal.Text    = "£" + total;
                cellShipping.Text = shipping.ToString();
            }
            else
            {
                Response.Redirect("CheckoutError.aspx?" + retMsg);
            }
        }
    }
예제 #27
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            NVPAPICaller payPalCaller = new NVPAPICaller();

            string   retMsg  = "";
            string   token   = "";
            string   PayerID = "";
            NVPCodec decoder = new NVPCodec();
            payPalCaller.SetCredentials(PrizeConstants.WALLET_USER_NAME,
                                        PrizeConstants.WALLET_PASSWORD,
                                        PrizeConstants.WALLET_SIGNATURE);
            token = Session["token"].ToString();

            bool ret = payPalCaller.GetCheckoutDetails(token, ref PayerID, ref decoder, ref retMsg);
            if (ret)
            {
                Session["payerId"] = PayerID;

                var myOrder = new PrizeOrder();
                myOrder.OrderDate      = Convert.ToDateTime(decoder["TIMESTAMP"].ToString());
                myOrder.Username       = PrizeMemberAuthUtils.GetMemberName();
                myOrder.FirstName      = decoder["FIRSTNAME"].ToString();
                myOrder.LastName       = decoder["LASTNAME"].ToString();
                myOrder.Email          = decoder["EMAIL"].ToString();
                myOrder.Total          = Convert.ToDecimal(decoder["AMT"].ToString());
                myOrder.MemberPlanId   = Int32.Parse(Session["buying_my_plan_id"].ToString());
                myOrder.ExercisePlanId = Int32.Parse(Session["buying_plan_id"].ToString());

                // Verify total payment amount as set on CheckoutStart.aspx.
                try
                {
                    decimal paymentAmountOnCheckout = Convert.ToDecimal(Session["payment_amt"].ToString());
                    decimal paymentAmoutFromPayPal  = Convert.ToDecimal(decoder["AMT"].ToString());
                    if (paymentAmountOnCheckout != paymentAmoutFromPayPal)
                    {
                        Response.Redirect("/Checkout/CheckoutError.aspx?" + "Desc=Amount%20total%20mismatch.");
                    }
                }
                catch (Exception)
                {
                    Response.Redirect("/Checkout/CheckoutError.aspx?" + "Desc=Amount%20total%20mismatch.");
                }

                // Get DB context.
                DIYPTEntities _db = new DIYPTEntities();
                try
                {
                    // Add order to DB.
                    _db.Database.Connection.Open();
                    _db.PrizeOrders.Add(myOrder);
                    _db.SaveChanges();
                    Session["currentOrderId"] = myOrder.OrderId;
                }
                finally
                {
                    _db.Database.Connection.Close();
                }
            }
            Session["userCheckoutCompleted"] = "true";
            Response.Redirect("~/Checkout/CheckoutComplete.aspx");
        }
    }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // Verify user has completed the checkout process.
                if ((string)Session["userCheckoutCompleted"] != "true")
                {
                    Session["userCheckoutCompleted"] = string.Empty;
                    Response.Redirect("CheckoutError.aspx?" + "Desc=Unvalidated%20Checkout.");
                }

                NVPAPICaller payPalCaller = new NVPAPICaller();

                string   retMsg             = "";
                string   token              = "";
                string   finalPaymentAmount = "";
                string   PayerID            = "";
                NVPCodec decoder            = new NVPCodec();

                token              = Session["token"].ToString();
                PayerID            = Session["payerId"].ToString();
                finalPaymentAmount = Session["payment_amt"].ToString();

                bool ret = payPalCaller.DoCheckoutPayment(finalPaymentAmount, token, PayerID, ref decoder, ref retMsg);
                if (ret)
                {
                    // Retrieve PayPal confirmation value.
                    string PaymentConfirmation = decoder["PAYMENTINFO_0_TRANSACTIONID"].ToString();

                    //
                    //TransactionId.Text = PaymentConfirmation;


                    ProductContext _db = new ProductContext();
                    // Get the current order id.
                    int currentOrderId = -1;
                    if (Session["currentOrderId"] != string.Empty)
                    {
                        currentOrderId = Convert.ToInt32(Session["currentOrderID"]);
                    }
                    Order myCurrentOrder;
                    if (currentOrderId >= 0)
                    {
                        // Get the order based on order id.
                        myCurrentOrder = _db.Orders.Single(o => o.OrderId == currentOrderId);
                        // Update the order to reflect payment has been completed.
                        myCurrentOrder.PaymentTransactionId = PaymentConfirmation;
                        // Save to DB.
                        _db.SaveChanges();
                    }

                    // Clear shopping cart.
                    using (ACMEINC.Logic.ShoppingCartActions usersShoppingCart =
                               new ACMEINC.Logic.ShoppingCartActions())
                    {
                        usersShoppingCart.EmptyCart();
                    }

                    // Clear order id.
                    Session["currentOrderId"] = string.Empty;
                }
                else
                {
                    Response.Redirect("CheckoutError.aspx?" + retMsg);
                }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                NVPAPICaller paypalCaller = new NVPAPICaller();

                string   retMsg  = string.Empty;
                string   token   = Session["token"].ToString();
                string   payerId = string.Empty;
                NVPCodec decoder = new NVPCodec();

                bool ret = paypalCaller.GetCheckoutDetails(token, ref payerId, ref decoder, ref retMsg);
                if (ret)
                {
                    Session["payerId"] = payerId;

                    var myOrder = new Order()
                    {
                        OrderDate  = Convert.ToDateTime(decoder["TIMESTAMP"].ToString()),
                        Username   = User.Identity.Name,
                        FirstName  = decoder["FIRSTNAME"].ToString(),
                        LastName   = decoder["LASTNAME"].ToString(),
                        Address    = decoder["SHIPTOSTREET"].ToString(),
                        City       = decoder["SHIPTOCITY"].ToString(),
                        State      = decoder["SHIPTOSTATE"].ToString(),
                        PostalCode = decoder["SHIPTOZIP"].ToString(),
                        Country    = decoder["SHIPTOCOUNTRYCODE"].ToString(),
                        Email      = decoder["EMAIL"].ToString(),
                        Total      = Convert.ToDecimal(decoder["AMT"].ToString(), CultureInfo.InvariantCulture),
                    };

                    // Verify total payment amount as set on CheckoutStart.aspx.
                    try
                    {
                        decimal paymentAmountOnCheckout = Convert.ToDecimal(Session["payment_amt"].ToString(), CultureInfo.InvariantCulture);
                        decimal paymentAmoutFromPayPal  = Convert.ToDecimal(decoder["AMT"].ToString(), CultureInfo.InvariantCulture);
                        if (paymentAmountOnCheckout != paymentAmoutFromPayPal)
                        {
                            Response.Redirect("CheckoutError.aspx?" + "Desc=Amount%20total%20mismatch.");
                        }
                    }
                    catch (Exception)
                    {
                        Response.Redirect("CheckoutError.aspx?" + "Desc=Amount%20total%20mismatch.");
                    }

                    // Get DB context.
                    ProductContext _db = new ProductContext();

                    // Add order to DB.
                    _db.Orders.Add(myOrder);
                    _db.SaveChanges();

                    // Get the shopping cart items and process them.
                    using (ShoppingCartActions usersShoppingCart = new ShoppingCartActions())
                    {
                        List <CartItem> myOrderList = usersShoppingCart.GetCartItems();

                        // Add OrderDetail information to the DB for each product purchased.
                        for (int i = 0; i < myOrderList.Count; i++)
                        {
                            // Create a new OrderDetail object.
                            var myOrderDetail = new OrderDetail
                            {
                                OrderId   = myOrder.OrderId,
                                Username  = User.Identity.Name,
                                ProductId = myOrderList[i].ProductId,
                                Quantity  = myOrderList[i].Quantity,
                                UnitPrice = myOrderList[i].Product.UnitPrice
                            };

                            // Add OrderDetail to DB.
                            _db.OrderDetails.Add(myOrderDetail);
                            _db.SaveChanges();
                        }

                        // Set OrderId.
                        Session["currentOrderId"] = myOrder.OrderId;

                        // Display Order information.
                        List <Order> orderList = new List <Order>
                        {
                            myOrder
                        };
                        ShipInfo.DataSource = orderList;
                        ShipInfo.DataBind();

                        // Display OrderDetails.
                        OrderItemList.DataSource = myOrderList;
                        OrderItemList.DataBind();
                    }
                }
                else
                {
                    Response.Redirect($"CheckoutError.aspx?{retMsg}");
                }
            }
        }
예제 #30
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                NVPAPICaller payPalCaller = new NVPAPICaller();

                string   retMsg  = "";
                string   token   = "";
                string   PayerID = "";
                NVPCodec decoder = new NVPCodec();
                token = Session["token"].ToString();

                bool ret = payPalCaller.GetCheckoutDetails(token, ref PayerID, ref decoder, ref retMsg);
                if (ret)
                {
                    Session["payerId"] = PayerID;

                    var myOrder = new Orders();

                    myOrder.Username = User.Identity.Name;
                    myOrder.Total    = Convert.ToDecimal(decoder["AMT"].ToString());

                    // Verify total payment amount as set on CheckoutStart.aspx.
                    try
                    {
                        decimal paymentAmountOnCheckout = Convert.ToDecimal(Session["payment_amt"].ToString());
                        decimal paymentAmoutFromPayPal  = Convert.ToDecimal(decoder["AMT"].ToString());
                        if (paymentAmountOnCheckout != paymentAmoutFromPayPal)
                        {
                            Response.Redirect("CheckoutError.aspx?" + "Desc=Amount%20total%20mismatch.");
                        }
                    }
                    catch (Exception)
                    {
                        Response.Redirect("CheckoutError.aspx?" + "Desc=Amount%20total%20mismatch.");
                    }

                    // Get DB context.
                    ProductContext _db = new ProductContext();

                    // Add order to DB.
                    _db.Orders.Add(myOrder);
                    _db.SaveChanges();

                    // Get the shopping cart items and process them.
                    using (CampusCourier.Logic.ShoppingCartActions usersShoppingCart = new CampusCourier.Logic.ShoppingCartActions())
                    {
                        List <CartItem> myOrderList = usersShoppingCart.GetCartItems();

                        // Add OrderDetail information to the DB for each product purchased.
                        for (int i = 0; i < myOrderList.Count; i++)
                        {
                            // Create a new OrderDetail object.
                            var myOrderDetail = new OrderDetail();
                            myOrderDetail.OrderId   = myOrder.OrderId;
                            myOrderDetail.CustName  = User.Identity.Name;
                            myOrderDetail.ProductId = myOrderList[i].ProductId;
                            myOrderDetail.Quantity  = myOrderList[i].Quantity;
                            myOrderDetail.UnitPrice = myOrderList[i].Product.UnitPrice;

                            // Add OrderDetail to DB.
                            _db.OrderDetails.Add(myOrderDetail);
                            _db.SaveChanges();
                        }


                        // Set OrderId. Remove this if it wont work
                        Session["currentOrderId"] = myOrder.OrderId;

                        //Adding data to orders

                        List <CartItem> ordersdatalist = usersShoppingCart.GetCartItems();
                        for (int i = 0; i < ordersdatalist.Count; i++)
                        {
                            var ordersdata = new Orders();
                            ordersdata.OrderId  = myOrder.OrderId;
                            ordersdata.Quantity = ordersdatalist[i].Quantity;
                            int productid = ordersdatalist[i].ProductId;
                            ordersdata.RestName = ordersdatalist[i].Product.Restaurant.RestaurantName;

                            int location = Convert.ToInt32(ordersdatalist[i].Product.RestaurantID);

                            string        Query            = "SELECT LocationName from Locations WHERE LocationID ='" + location + "'";
                            string        connectionstring = ConfigurationManager.ConnectionStrings["CampusCourier"].ConnectionString;
                            SqlConnection conn             = new SqlConnection(connectionstring);
                            SqlCommand    comm             = new SqlCommand(Query, conn);
                            conn.Open();
                            SqlDataReader nwReader = comm.ExecuteReader();

                            while (nwReader.Read())
                            {
                                ordersdata.Location = (string)nwReader["LocationName"];
                            }
                            nwReader.Close();
                            conn.Close();

                            ordersdata.Total  = Convert.ToDecimal(ordersdatalist[i].Product.UnitPrice);
                            ordersdata.Status = "Waiting For Delivery";
                            _db.Orders.Add(ordersdata);
                            _db.SaveChanges();
                        }

                        // Display Order information.
                        List <Orders> orderList = new List <Orders>();
                        orderList.Add(myOrder);
                        ShipInfo.DataSource = orderList;
                        ShipInfo.DataBind();

                        // Display OrderDetails.
                        OrderItemList.DataSource = myOrderList;
                        OrderItemList.DataBind();
                        Session["userCheckoutCompleted"] = "true";
                        Response.Redirect("~/Checkout/CheckoutComplete.aspx");
                    }
                }
                else
                {
                    Response.Redirect("CheckoutError.aspx?" + retMsg);
                }
            }
        }
예제 #31
0
        public ActionResult Complete(string token, string PayerID)
        {
            if (string.IsNullOrEmpty(token) && string.IsNullOrEmpty(PayerID))
            {
                //Need to specify error handling
                return(RedirectToAction("ErrorMessage", "Checkout", new { ErrorCode = ErrorCode.PAYPAL_ERROR }));
            }

            var    order   = market.Orders.SingleOrDefault(o => o.PayPalToken == token);
            var    decoder = new NVPCodec();
            string retMsg  = "";

            // This is where we call DoExpressCheckoutPayment
            NVPAPICaller completeCheckout = new NVPAPICaller(token: token, PayerID: PayerID, total: order.Total.ToString());
            bool         ret = completeCheckout.ConfirmPayment(order.Total.ToString(), ref decoder, ref retMsg);

            if (ret)
            {
                var cart = RentalCart.GetCart(this.HttpContext);
                cart.EmptyCart();
                Session["RentalCartItems"] = 0;


                order.Confirmed           = true;
                market.Entry(order).State = System.Data.EntityState.Modified;
                market.SaveChanges();

                var orderDetails = market.OrderDetails.Where(o => o.OrderId == order.OrderId).ToList();

                if (order != null)
                {
                    foreach (OrderDetailModel o in orderDetails)
                    {
                        if (EmailSecurityCode(User.Identity.Name, o.OrderDetailId, false))
                        {
                        }
                        //Need to specify error handling
                        else
                        {
                            return(RedirectToAction("ErrorMessage", "Checkout", new { ErrorCode = ErrorCode.UNKNOWN }));
                        }
                        if (EmailSecurityCode(market.OrderDetails.Find(o.OrderDetailId).Item.Owner.Email, o.OrderDetailId, true))
                        {
                        }
                        //Need to specify error handling
                        else
                        {
                            return(RedirectToAction("ErrorMessage", "Checkout", new { ErrorCode = ErrorCode.UNKNOWN }));
                        }
                        o.Status = (int)OrderStatus.ORDER_TENTATIVE;
                        market.Entry(o).State = System.Data.EntityState.Modified;
                        market.SaveChanges();
                    }
                    return(View(order.OrderDetails));
                }
                return(RedirectToAction("ErrorMessage", "Checkout", new { ErrorCode = ErrorCode.UNKNOWN }));
            }
            else
            {
                //PayPal payment didn't go through
                return(Redirect(Url.Content("~/CheckOut/ErrorMessage") + retMsg));
            }
            //Need to specify error handling
            return(RedirectToAction("ErrorMessage", "Checkout", new { ErrorCode = ErrorCode.UNKNOWN }));
        }
        public ActionResult CheckoutReview()
        {
            int CustomerID = 0;
            string ErrorMessage = "";
            string retMsg = "";
            string token = "";
            string PayerID = "5678912340";
            NVPCodec decoder = new NVPCodec();
            token = Session["token"].ToString();
            OrderViewModel orderViewModel = new OrderViewModel();
            NVPAPICaller payPalCaller = new NVPAPICaller();
            CustomerDataAccessService customerDataAccessService = new CustomerDataAccessService();
            var Cart = ShoppingCartActions.GetCart();

            string CartID = Cart.ShoppingCartId;
            orderViewModel.Order.CartID = CartID;

            bool ret = payPalCaller.GetCheckoutDetails(token, ref PayerID, ref decoder, ref retMsg);
            if (ret)
            {
                Session["payerId"] = PayerID;
                CustomerID = customerDataAccessService.GetCustomerIdNumber(User.Identity.Name);
                orderViewModel.Order.CustomerID = CustomerID;
                orderViewModel.Order.OrderDate = Convert.ToDateTime(decoder["TIMESTAMP"].ToString());
                orderViewModel.Order.UserName = User.Identity.Name;
                orderViewModel.Order.FirstName = decoder["FIRSTNAME"].ToString();
                orderViewModel.Order.LastName = decoder["LASTNAME"].ToString();
                orderViewModel.Order.SheepToStreet = decoder["SHIPTOSTREET"].ToString();
                orderViewModel.Order.ShipCity = decoder["SHIPTOCITY"].ToString();
                orderViewModel.Order.ShipToState = decoder["SHIPTOSTATE"].ToString();
                orderViewModel.Order.ShipPostalCode = decoder["SHIPTOZIP"].ToString();
                orderViewModel.Order.ShipCountry = decoder["SHIPTOCOUNTRYCODE"].ToString();
                orderViewModel.Order.Email = decoder["EMAIL"].ToString();
                orderViewModel.Order.OrderTotal = Convert.ToDouble(decoder["AMT"].ToString());
                orderViewModel.Customer.CustomerID = CustomerID;

                // Verify total payment amount as set on CheckoutStart.aspx.
                try
                {
                    decimal paymentAmountOnCheckout = Convert.ToDecimal(Session["payment_amt"].ToString());
                    decimal paymentAmoutFromPayPal = Convert.ToDecimal(decoder["AMT"].ToString());
                    if (paymentAmountOnCheckout != paymentAmoutFromPayPal)
                    {
                        ErrorMessage = "Amount%20total%20mismatch.";
                        return RedirectToAction("CheckoutError", ErrorMessage);
                    }
                }
                catch (Exception)
                {
                    ErrorMessage = "Amount%20total%20mismatch.";
                    return RedirectToAction("CheckoutError", ErrorMessage);

                }
                //Process the order

                OrderApplicationService orderApplicationService = new OrderApplicationService();
                orderViewModel = orderApplicationService.CreateOrder(orderViewModel);
                orderViewModel = orderApplicationService.BeginOrderEntry(orderViewModel);
                Session["currentOrderId"] = orderViewModel.Order.OrderID;

            }
            else
            {
                RedirectToAction("CheckoutError", retMsg);
            }
            return View("CheckoutReview", orderViewModel);
        }
        public ActionResult Review(CheckoutViewModel data)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    NVPAPICaller gatewayCaller = new NVPAPICaller();

                    string token = "";
                    NVPCodec decoder = new NVPCodec();

                    // Call the gateway payment authorization API:
                    bool ret = gatewayCaller.DoCheckoutAuth(data.Order, ref token, ref decoder);

                    // If authorizaton is successful:
                    if (ret)
                    {
                        // Hydrate a new Order model from our OrderViewModel.
                        var myOrder = Mapper.Map<Data.Models.Order>(data.Order);
                        // Timestamp with a UTC date.
                        myOrder.OrderDate = DateTime.UtcNow;

                        // Get DB context.
                        ProductContext _db = new ProductContext();

                        // Add order to DB.
                        _db.Orders.Add(myOrder);
                        _db.SaveChanges();

                        // Get the shopping cart items and process them.
                        using (ShoppingCartActions usersShoppingCart = new ShoppingCartActions(cartId))
                        {
                            List<CartItem> myOrderList = usersShoppingCart.GetCartItems();

                            // Add OrderDetail information to the DB for each product purchased.
                            for (int i = 0; i < myOrderList.Count; i++)
                            {
                                // Create a new OrderDetail object.
                                var myOrderDetail = new OrderDetail();
                                myOrderDetail.OrderId = myOrder.OrderId;
                                myOrderDetail.ProductId = myOrderList[i].ProductId;
                                myOrderDetail.Quantity = myOrderList[i].Quantity;
                                myOrderDetail.UnitPrice = myOrderList[i].Product.UnitPrice;

                                // Add OrderDetail to DB.
                                _db.OrderDetails.Add(myOrderDetail);
                                _db.SaveChanges();
                            }

                            // Set OrderId.
                            Session["currentOrderId"] = myOrder.OrderId;
                            Session["Token"] = token;

                            // Report successful event to Application Insights.
                            var eventProperties = new Dictionary<string, string>();
                            eventProperties.Add("CustomerEmail", data.Order.Email);
                            eventProperties.Add("NumberOfItems", myOrderList.Count.ToString());
                            eventProperties.Add("OrderTotal", data.Order.Total.ToString("C2"));
                            eventProperties.Add("OrderId", myOrder.OrderId.ToString());
                            TelemetryHelper.TrackEvent("SuccessfulPaymentAuth", eventProperties);

                            data.Order.OrderId = myOrder.OrderId;
                            if (data.Order.CreditCardNumber.Length > 4)
                            {
                                // Only show the last 4 digits of the credit card number:
                                data.Order.CreditCardNumber = "xxxxxxxxxxx" + data.Order.CreditCardNumber.Substring(data.Order.CreditCardNumber.Length - 4);
                            }
                        }
                    }
                    else
                    {
                        var error = gatewayCaller.PopulateGatewayErrorModel(decoder);

                        // Report failed event to Application Insights.
                        Exception ex = new Exception(error.ToString());
                        ex.Source = "Contoso.Apps.SportsLeague.Web.CheckoutController.cs";
                        TelemetryHelper.TrackException(ex);

                        // Redirect to the checkout error view:
                        return RedirectToAction("Error", error);
                    }
                }
                catch (WebException wex)
                {
                    ExceptionUtility.LogException(wex, "CheckoutController.cs Complete Action");

                    var error = new CheckoutErrorViewModel
                    {
                        ErrorCode = wex.Message
                    };

                    if (wex.Response != null && wex.Response.GetType() == typeof(HttpWebResponse))
                    {
                        // Extract the response body from the WebException's HttpWebResponse:
                        error.LongMessage = ((HttpWebResponse)wex.Response).StatusDescription;
                    }

                    // Redirect to the checkout error view:
                    return RedirectToAction("Error", error);
                }
                catch (Exception ex)
                {
                    ExceptionUtility.LogException(ex, "CheckoutController.cs Review Action");

                    var error = new CheckoutErrorViewModel
                    {
                        ErrorCode = ex.Message
                    };

                    // Redirect to the checkout error view:
                    return RedirectToAction("Error", error);
                }
            }

            return View(data);
        }
예제 #34
0
        public async Task <ActionResult> Complete(OrderModel order)
        {
            try
            {
                // TODO: Complete the payment processing via the gateway and update the order...
                NVPAPICaller gatewayCaller = new NVPAPICaller();

                string   token = "";
                string   finalPaymentAmount = "";
                NVPCodec decoder            = new NVPCodec();

                token = Session["token"].ToString();
                //PayerID = Session["payerId"].ToString();
                //finalPaymentAmount = Session["payment_amt"].ToString();
                finalPaymentAmount = order.Total.ToString("C2");

                bool ret = true;// gatewayCaller.DoCheckoutPayment(finalPaymentAmount, token, ref decoder);
                if (ret)
                {
                    //// Retrieve PayPal confirmation value.
                    string PaymentConfirmation = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 10);// decoder[NVPProperties.Properties.TRANSACTIONID].ToString();
                    order.PaymentTransactionId = PaymentConfirmation;

                    // Get the current order id.
                    int currentOrderId = -1;
                    if (Session["currentOrderId"] != null && Session["currentOrderId"].ToString() != string.Empty)
                    {
                        currentOrderId = Convert.ToInt32(Session["currentOrderID"]);
                    }

                    Order myCurrentOrder;

                    if (currentOrderId >= 0)
                    {
                        myCurrentOrder = await SqlDbHelper.GetOrder(currentOrderId);

                        myCurrentOrder.PaymentTransactionId = PaymentConfirmation;

                        await SqlDbHelper.SaveOrder(myCurrentOrder);

                        // Queue up a receipt generation request, asynchronously.
                        await new AzureQueueHelper().QueueReceiptRequest(myCurrentOrder);

                        // Report successful event to Application Insights.
                        var eventProperties = new Dictionary <string, string>();
                        eventProperties.Add("CustomerEmail", order.Email);
                        eventProperties.Add("OrderTotal", finalPaymentAmount);
                        eventProperties.Add("PaymentTransactionId", PaymentConfirmation);
                        TelemetryHelper.TrackEvent("OrderCompleted", eventProperties);
                    }

                    // Clear shopping cart.
                    using (ShoppingCartActions usersShoppingCart =
                               new ShoppingCartActions(cartId, items, categories))
                    {
                        await usersShoppingCart.EmptyCart();
                    }

                    // Clear order id.
                    Session["currentOrderId"] = string.Empty;
                }
                else
                {
                    var error = gatewayCaller.PopulateGatewayErrorModel(decoder);

                    // Report failed event to Application Insights.
                    Exception ex = new Exception(error.ToString());
                    ex.Source = "Contoso.Apps.Movies.Web.CheckoutController.cs";
                    TelemetryHelper.TrackException(ex);

                    // Redirect to the checkout error view:
                    return(RedirectToAction("Error", error));
                }
            }
            catch (WebException wex)
            {
                ExceptionUtility.LogException(wex, "CheckoutController.cs Complete Action");

                var error = new CheckoutErrorModel
                {
                    ErrorCode = wex.Message
                };

                if (wex.Response != null && wex.Response.GetType() == typeof(HttpWebResponse))
                {
                    // Extract the response body from the WebException's HttpWebResponse:
                    error.LongMessage = ((HttpWebResponse)wex.Response).StatusDescription;
                }

                // Redirect to the checkout error view:
                return(RedirectToAction("Error", error));
            }
            catch (Exception ex)
            {
                ExceptionUtility.LogException(ex, "CheckoutController.cs Complete Action");

                var error = new CheckoutErrorModel
                {
                    ErrorCode = ex.Message
                };

                // Redirect to the checkout error view:
                return(RedirectToAction("Error", error));
            }

            return(View(order));
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // Verify user has completed the checkout process.
                if ((string)Session["userCheckoutCompleted"] != "true")
                {
                    Session["userCheckoutCompleted"] = string.Empty;
                    Response.Redirect("CheckoutError.aspx?" + "Desc=Unvalidated%20Checkout.");
                }
                if (Session["payment_method"].ToString() == "PayPal")
                {
                    NVPAPICaller payPalCaller = new NVPAPICaller();

                    string   retMsg             = "";
                    string   token              = "";
                    string   finalPaymentAmount = "";
                    string   PayerID            = "";
                    NVPCodec decoder            = new NVPCodec();

                    token              = Session["token"].ToString();
                    PayerID            = Session["payerId"].ToString();
                    finalPaymentAmount = Session["payment_amt"].ToString();

                    bool ret = payPalCaller.DoCheckoutPayment(finalPaymentAmount, token, PayerID, ref decoder, ref retMsg);
                    if (ret)
                    {
                        // Retrieve PayPal confirmation value.
                        string PaymentConfirmation = decoder["PAYMENTINFO_0_TRANSACTIONID"].ToString();
                        TransactionId.Text = PaymentConfirmation;

                        ProductContext _db = new ProductContext();
                        // Get the current order id.
                        int currentOrderId = -1;
                        if (Session["currentOrderId"].ToString() != string.Empty)
                        {
                            currentOrderId = Convert.ToInt32(Session["currentOrderID"]);
                        }
                        Order myCurrentOrder;
                        if (currentOrderId >= 0)
                        {
                            // Get the order based on order id.
                            myCurrentOrder = _db.Orders.Single(o => o.OrderId == currentOrderId);
                            // Update the order to reflect payment has been completed.
                            myCurrentOrder.PaymentTransactionId = PaymentConfirmation;
                            // Save to DB.
                            _db.SaveChanges();
                        }


                        // Clear order id.
                        Session["currentOrderId"] = string.Empty;
                    }

                    else
                    {
                        Response.Redirect("CheckoutError.aspx?" + retMsg);
                    }
                }
                else if (Session["payment_method"].ToString() == "Braintree")
                {
                    var myOrder   = new Models.Order();
                    var myAddress = new Models.Address();
                    var manager   = HttpContext.Current.GetOwinContext().GetUserManager <ApplicationUserManager>();
                    var user      = manager.FindByName(HttpContext.Current.User.Identity.Name);
                    myOrder.OrderDate            = DateTime.Now;
                    myOrder.Email                = user.Email;
                    myAddress.UserName           = user.Email;
                    myAddress.AddressLine1       = Session["streetNumberValue"].ToString() + " " + Session["routeValue"].ToString();
                    myAddress.City               = Session["cityValue"].ToString();
                    myAddress.State              = Session["stateValue"].ToString();
                    myAddress.PostalCode         = Session["postalCodeValue"].ToString();
                    myAddress.Country            = Session["countryValue"].ToString();
                    myOrder.Email                = user.Email;
                    myOrder.PaymentTransactionId = "Stripe" + Session["token"].ToString();
                    myOrder.Total                = Convert.ToDecimal(HttpContext.Current.Session["payment_amt"].ToString());

                    ProductContext _db = new ProductContext();

                    // Add order to DB.
                    _db.Orders.Add(myOrder);
                    _db.Addresses.Add(myAddress);
                    _db.SaveChanges();

                    using (fashionUtilityApplication.Logic.ShoppingCartActions usersShoppingCart = new fashionUtilityApplication.Logic.ShoppingCartActions())
                    {
                        List <CartItem> myOrderList = usersShoppingCart.GetCartItems();

                        // Add OrderDetail information to the DB for each product purchased.
                        for (int i = 0; i < myOrderList.Count; i++)
                        {
                            // Create a new OrderDetail object.
                            var myOrderDetail = new OrderDetail();
                            myOrderDetail.OrderId   = myOrder.OrderId;
                            myOrderDetail.Username  = HttpContext.Current.User.Identity.Name;
                            myOrderDetail.ProductId = myOrderList[i].ProductId;
                            myOrderDetail.Quantity  = myOrderList[i].Quantity;
                            myOrderDetail.ImagePath = myOrderList[i].ImagePath;
                            myOrderDetail.UnitPrice = myOrderList[i].Product.UnitPrice;

                            // Add OrderDetail to DB.
                            _db.OrderDetails.Add(myOrderDetail);
                            _db.SaveChanges();
                        }

                        // Set OrderId.
                        HttpContext.Current.Session["currentOrderId"] = myOrder.OrderId;

                        // Display Order information.
                        List <fashionUtilityApplication.Models.Order> orderList = new List <fashionUtilityApplication.Models.Order>();
                        orderList.Add(myOrder);
                    }
                }
                else
                {
                    Response.Redirect("CheckoutError.aspx?");
                }
                // Clear shopping cart.
                using (fashionUtilityApplication.Logic.ShoppingCartActions usersShoppingCart =
                           new fashionUtilityApplication.Logic.ShoppingCartActions())
                {
                    usersShoppingCart.EmptyCart();
                }
            }
        }
예제 #36
0
        public async Task <ActionResult> Review(CheckoutModel data)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    NVPAPICaller gatewayCaller = new NVPAPICaller();

                    string   token   = "";
                    NVPCodec decoder = new NVPCodec();

                    // Call the gateway payment authorization API:
                    bool ret = true;// gatewayCaller.DoCheckoutAuth(data.Order, ref token, ref decoder);

                    // If authorizaton is successful:
                    if (ret)
                    {
                        // Hydrate a new Order model from our OrderModel.
                        var myOrder = Mapper.Map <Data.Models.Order>(data.Order);
                        // Timestamp with a UTC date.
                        myOrder.OrderDate = DateTime.UtcNow;

                        // Add order to DB.
                        await SqlDbHelper.SaveOrder(myOrder);

                        // Get the shopping cart items and process them.
                        using (ShoppingCartActions usersShoppingCart = new ShoppingCartActions(cartId, items, categories))
                        {
                            List <CartItem> myOrderList = usersShoppingCart.GetCartItems();

                            // Add OrderDetail information to the DB for each product purchased.
                            for (int i = 0; i < myOrderList.Count; i++)
                            {
                                // Create a new OrderDetail object.
                                var myOrderDetail = new OrderDetail();
                                myOrderDetail.OrderDetailId = i;
                                myOrderDetail.OrderId       = myOrder.OrderId;
                                myOrderDetail.ProductId     = myOrderList[i].ItemId;
                                myOrderDetail.Quantity      = myOrderList[i].Quantity;
                                myOrderDetail.UnitPrice     = myOrderList[i].Product.UnitPrice;
                                myOrderDetail.Email         = myOrder.Email;

                                // Add OrderDetail to DB.
                                await SqlDbHelper.SaveOrderDetails(myOrderDetail);
                            }

                            // Set OrderId.
                            Session["currentOrderId"] = myOrder.OrderId;
                            Session["Token"]          = token;

                            // Report successful event to Application Insights.
                            var eventProperties = new Dictionary <string, string>();
                            eventProperties.Add("CustomerEmail", data.Order.Email);
                            eventProperties.Add("NumberOfItems", myOrderList.Count.ToString());
                            eventProperties.Add("OrderTotal", data.Order.Total.ToString("C2"));
                            eventProperties.Add("OrderId", myOrder.OrderId.ToString());
                            TelemetryHelper.TrackEvent("SuccessfulPaymentAuth", eventProperties);

                            data.Order.OrderId = myOrder.OrderId;

                            if (data.Order.CreditCardNumber.Length > 4)
                            {
                                // Only show the last 4 digits of the credit card number:
                                data.Order.CreditCardNumber = "xxxxxxxxxxx" + data.Order.CreditCardNumber.Substring(data.Order.CreditCardNumber.Length - 4);
                            }
                        }
                    }
                    else
                    {
                        var error = gatewayCaller.PopulateGatewayErrorModel(decoder);

                        // Report failed event to Application Insights.
                        Exception ex = new Exception(error.ToString());
                        ex.Source = "Contoso.Apps.Movies.Web.CheckoutController.cs";
                        TelemetryHelper.TrackException(ex);

                        // Redirect to the checkout error view:
                        return(RedirectToAction("Error", error));
                    }
                }
                catch (WebException wex)
                {
                    ExceptionUtility.LogException(wex, "CheckoutController.cs Complete Action");

                    var error = new CheckoutErrorModel
                    {
                        ErrorCode = wex.Message
                    };

                    if (wex.Response != null && wex.Response.GetType() == typeof(HttpWebResponse))
                    {
                        // Extract the response body from the WebException's HttpWebResponse:
                        error.LongMessage = ((HttpWebResponse)wex.Response).StatusDescription;
                    }

                    // Redirect to the checkout error view:
                    return(RedirectToAction("Error", error));
                }
                catch (Exception ex)
                {
                    ExceptionUtility.LogException(ex, "CheckoutController.cs Review Action");

                    var error = new CheckoutErrorModel
                    {
                        ErrorCode = ex.Message
                    };

                    // Redirect to the checkout error view:
                    return(RedirectToAction("Error", error));
                }
            }

            return(View(data));
        }
예제 #37
0
    protected void Page_Load(object sender, EventArgs e)
    {
        double subTotal = 0;
        double total = 0;
        double shipping = 00;

        if (!IsPostBack)
        {
            NVPAPICaller payPalCaller = new NVPAPICaller();

            string retMsg = "";
            string token = "";
            string PayerID = "";
            string foreName = "";
            string surName = "";
            string email = "";
            string address = "";
            string postcode = "";
            string town = "";

            NVPCodec decoder = new NVPCodec();
            token = Session["token"].ToString();

            bool ret = payPalCaller.GetCheckoutDetails(token, ref PayerID, ref decoder, ref retMsg);
            if (ret)
            {

                //get user information from papal
                Session["payerId"] = PayerID;

                foreName = decoder["FIRSTNAME"].ToString();
                surName = decoder["LASTNAME"].ToString();
                address = decoder["SHIPTOSTREET"].ToString();
                town = decoder["SHIPTOCITY"].ToString();
                postcode = decoder["SHIPTOZIP"].ToString();
                email = decoder["EMAIL"].ToString();

                //display user information
                lblFore.Text = foreName;
                lblSur.Text = surName;
                lblCity.Text = town;
                lblEmail.Text = email;
                lblPostCode.Text = postcode;
                lblAddress.Text = address;

                //set customer object with information from paypal
                Customer aCustomer = (Customer)Session["Customer"];
                aCustomer.CityAddress = town;
                aCustomer.Email = email;
                aCustomer.FName = foreName;
                aCustomer.SName = surName;
                aCustomer.StreetAddress = address;
                aCustomer.PostCode = postcode;

                // Verify total payment amount as set on CheckoutStart.aspx.
                try
                {
                    decimal paymentAmountOnCheckout = Convert.ToDecimal(Session["payment_amt"].ToString());
                    decimal paymentAmoutFromPayPal = Convert.ToDecimal(decoder["AMT"].ToString());
                    shipping = Convert.ToDouble(decoder["SHIPPINGAMT"].ToString());
                    if (paymentAmountOnCheckout != paymentAmoutFromPayPal)
                    {
                        Response.Redirect("CheckoutError.aspx?" + "Desc=Amount%20total%20mismatch.");
                    }
                }
                catch (Exception)
                {
                    Response.Redirect("CheckoutError.aspx?" + "Desc=Amount%20total%20mismatch.");
                }

                // Display Order information.

                var query = from goods in aCustomer.Orders[0].OrderLines
                            select new
                            {
                                Name = goods.Product.ProdName,
                                Description = goods.Product.ProdDescription,
                                Price = goods.Product.ProdPrice,
                                Qty = goods.Quantity,
                                Total = "£" + Convert.ToString(goods.Quantity * goods.Product.ProdPrice),
                                ProdImage = goods.Product.ProdImage
                            };

                GridView1.DataSource = query;
                GridView1.DataBind();

                subTotal = CartFunctions.getSubTotal(aCustomer);

                cellSub.Text = "£" + Convert.ToString(subTotal);
                total = subTotal + shipping;
                cellTotal.Text = "£" + total;
                cellShipping.Text = shipping.ToString();

            }
            else
            {
                Response.Redirect("CheckoutError.aspx?" + retMsg);
            }
        }
    }
        public async Task<ActionResult> Complete(OrderViewModel order)
        {
            try
            {
                // TODO: Complete the payment processing via the gateway and update the order...
                NVPAPICaller gatewayCaller = new NVPAPICaller();

                string token = "";
                string finalPaymentAmount = "";
                NVPCodec decoder = new NVPCodec();

                token = Session["token"].ToString();
                //PayerID = Session["payerId"].ToString();
                //finalPaymentAmount = Session["payment_amt"].ToString();
                finalPaymentAmount = order.Total.ToString("C2");

                bool ret = gatewayCaller.DoCheckoutPayment(finalPaymentAmount, token, ref decoder);
                if (ret)
                {
                    // Retrieve PayPal confirmation value.
                    string PaymentConfirmation = decoder[NVPProperties.Properties.TRANSACTIONID].ToString();
                    order.PaymentTransactionId = PaymentConfirmation;


                    ProductContext _db = new ProductContext();
                    // Get the current order id.
                    int currentOrderId = -1;
                    if (Session["currentOrderId"] != null && Session["currentOrderId"].ToString() != string.Empty)
                    {
                        currentOrderId = Convert.ToInt32(Session["currentOrderID"]);
                    }
                    Order myCurrentOrder;
                    if (currentOrderId >= 0)
                    {
                        // Get the order based on order id.
                        myCurrentOrder = _db.Orders.Single(o => o.OrderId == currentOrderId);
                        // Update the order to reflect payment has been completed.
                        myCurrentOrder.PaymentTransactionId = PaymentConfirmation;
                        // Save to DB.
                        _db.SaveChanges();

                        // Queue up a receipt generation request, asynchronously.
                        await new AzureQueueHelper().QueueReceiptRequest(currentOrderId);

                        // Report successful event to Application Insights.
                        var eventProperties = new Dictionary<string, string>();
                        eventProperties.Add("CustomerEmail", order.Email);
                        eventProperties.Add("OrderTotal", finalPaymentAmount);
                        eventProperties.Add("PaymentTransactionId", PaymentConfirmation);
                        TelemetryHelper.TrackEvent("OrderCompleted", eventProperties);
                    }

                    // Clear shopping cart.
                    using (ShoppingCartActions usersShoppingCart =
                        new ShoppingCartActions(cartId))
                    {
                        usersShoppingCart.EmptyCart();
                    }

                    // Clear order id.
                    Session["currentOrderId"] = string.Empty;
                }
                else
                {
                    var error = gatewayCaller.PopulateGatewayErrorModel(decoder);

                    // Report failed event to Application Insights.
                    Exception ex = new Exception(error.ToString());
                    ex.Source = "Contoso.Apps.SportsLeague.Web.CheckoutController.cs";
                    TelemetryHelper.TrackException(ex);

                    // Redirect to the checkout error view:
                    return RedirectToAction("Error", error);
                }
            }
            catch (WebException wex)
            {
                ExceptionUtility.LogException(wex, "CheckoutController.cs Complete Action");

                var error = new CheckoutErrorViewModel
                {
                    ErrorCode = wex.Message
                };

                if (wex.Response != null && wex.Response.GetType() == typeof(HttpWebResponse))
                {
                    // Extract the response body from the WebException's HttpWebResponse:
                    error.LongMessage = ((HttpWebResponse)wex.Response).StatusDescription;
                }

                // Redirect to the checkout error view:
                return RedirectToAction("Error", error);
            }
            catch (Exception ex)
            {
                ExceptionUtility.LogException(ex, "CheckoutController.cs Complete Action");

                var error = new CheckoutErrorViewModel
                {
                    ErrorCode = ex.Message
                };

                // Redirect to the checkout error view:
                return RedirectToAction("Error", error);
            }

            return View(order);
        }
예제 #39
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                NVPAPICaller payPalCaller = new NVPAPICaller();

                string retMsg = "";
                string token = "";
                string PayerID = "";
                NVPCodec decoder = new NVPCodec();

                bool ret = true;
                if (ret)
                {
                    Session["payerId"] = PayerID;
                    string AMT = Session["payment_amt"].ToString();

                    // Verify total payment amount as set on CheckoutStart.aspx.
                    try
                    {
                        decimal paymentAmountOnCheckout = Convert.ToDecimal(Session["payment_amt"].ToString());
                        decimal paymentAmoutFromPayPal = Convert.ToDecimal(AMT);
                        if (paymentAmountOnCheckout != paymentAmoutFromPayPal)
                        {
                            Response.Redirect("CheckoutError.aspx?" + "Desc=Amount%20total%20mismatch.");
                        }
                    }
                    catch (Exception)
                    {
                        Response.Redirect("CheckoutError.aspx?" + "Desc=Amount%20total%20mismatch.");
                    }

                    // Get the shopping cart items and process them.
                    using (WingtipToys.Logic.ShoppingCartActions usersShoppingCart = new WingtipToys.Logic.ShoppingCartActions())
                    {
                        List<CartItem> myOrderList = usersShoppingCart.GetCartItems();

                        // Display Order information.
                        List<Order> orderList = new List<Order>();
                        using (ProductContext _db = new ProductContext())
                        {
                            int id = Convert.ToInt32(Session["currentOrderId"].ToString());
                            Order myOrder = _db.Orders.Where(order => order.OrderId == id).First();
                            if (myOrder != null)
                            {
                                orderList.Add(myOrder);
                            }
                        }
                        ShipInfo.DataSource = orderList;
                        ShipInfo.DataBind();

                        // Display OrderDetails.
                        OrderItemList.DataSource = myOrderList;
                        OrderItemList.DataBind();
                    }
                }
                else
                {
                    Response.Redirect("CheckoutError.aspx?" + retMsg);
                }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                NVPAPICaller payPalCaller = new NVPAPICaller();

                string   retMsg  = "";
                string   token   = "";
                string   PayerID = "";
                NVPCodec decoder = new NVPCodec();
                token = Session["token"].ToString();

                bool ret = payPalCaller.GetCheckoutDetails(token, ref PayerID, ref decoder, ref retMsg);
                if (ret)
                {
                    Session["payerId"] = PayerID;

                    var myOrder = new Order();
                    myOrder.OrderDate  = Convert.ToDateTime(decoder["TIMESTAMP"].ToString());
                    myOrder.Username   = User.Identity.Name;
                    myOrder.FirstName  = decoder["FIRSTNAME"].ToString();
                    myOrder.LastName   = decoder["LASTNAME"].ToString();
                    myOrder.Address    = decoder["SHIPTOSTREET"].ToString();
                    myOrder.City       = decoder["SHIPTOCITY"].ToString();
                    myOrder.State      = decoder["SHIPTOSTATE"].ToString();
                    myOrder.PostalCode = decoder["SHIPTOZIP"].ToString();
                    myOrder.Country    = decoder["SHIPTOCOUNTRYCODE"].ToString();
                    myOrder.Email      = decoder["EMAIL"].ToString();
                    myOrder.Total      = Convert.ToDecimal(decoder["AMT"].ToString());

                    // Verify total payment amount as set on CheckoutStart.aspx.
                    try
                    {
                        decimal paymentAmountOnCheckout = Convert.ToDecimal(Session["payment_amt"].ToString());
                        decimal paymentAmoutFromPayPal  = Convert.ToDecimal(decoder["AMT"].ToString());
                        if (paymentAmountOnCheckout != paymentAmoutFromPayPal)
                        {
                            Response.Redirect("CheckoutError.aspx?" + "Desc=Amount%20total%20mismatch.");
                        }
                    }
                    catch (Exception)
                    {
                        Response.Redirect("CheckoutError.aspx?" + "Desc=Amount%20total%20mismatch.");
                    }

                    // Get DB context.
                    CatalogObjectContext _db = new CatalogObjectContext();

                    // Add order to DB.
                    _db.Orders.Add(myOrder);
                    try
                    {
                        _db.SaveChanges();
                    }
                    catch (Exception ex)
                    {
                        string s = ex.Message;
                    }

                    // Get the shopping cart items and process them.
                    using (CatalogiaWebForms.Logic.ShoppingCartActions usersShoppingCart = new CatalogiaWebForms.Logic.ShoppingCartActions())
                    {
                        List <CartItem> orders = usersShoppingCart.GetCartItems();

                        // Add OrderDetail information to the DB for each catalog item ordered.
                        for (int i = 0; i < orders.Count; i++)
                        {
                            // Create a new OrderDetail object.
                            var currentDetail = new OrderDetail();
                            currentDetail.OrderId   = myOrder.OrderId;
                            currentDetail.Username  = User.Identity.Name;
                            currentDetail.ObjectId  = orders[i].CatalogObject.ObjectId;
                            currentDetail.Quantity  = orders[i].Quantity;
                            currentDetail.UnitPrice = orders[i].CatalogObject.Price;

                            // Add OrderDetail to DB.
                            _db.OrderDetails.Add(currentDetail);
                            _db.SaveChanges();
                        }

                        // Set OrderId.
                        Session["currentOrderId"] = myOrder.OrderId;

                        // Display Order information.
                        List <Order> orderList = new List <Order>();
                        orderList.Add(myOrder);
                        ShipInfo.DataSource = orderList;
                        ShipInfo.DataBind();

                        // Display OrderDetails.
                        OrderItemList.DataSource = orders;
                        OrderItemList.DataBind();
                    }
                }
                else
                {
                    Response.Redirect("CheckoutError.aspx?" + retMsg);
                }
            }
        }
예제 #41
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                var payPalCaller = new NVPAPICaller();

                var retMsg  = "";
                var token   = Session["token"].ToString();
                var payerId = "";
                var decoder = new NVPCodec();

                var ret = payPalCaller.GetCheckoutDetails(token, ref payerId, ref decoder, ref retMsg);
                if (ret)
                {
                    Session["PayerId"] = payerId;

                    var myOrder = new Order();
                    myOrder.OrderDate  = Convert.ToDateTime(decoder["TIMESTAMP"]);
                    myOrder.Username   = User.Identity.Name;
                    myOrder.FirstName  = decoder["FIRSTNAME"];
                    myOrder.LastName   = decoder["LASTNAME"];
                    myOrder.Address    = decoder["SHIPTOSTREET"];
                    myOrder.City       = decoder["SHIPTOCITY"];
                    myOrder.State      = decoder["SHIPTOSTATE"];
                    myOrder.PostalCode = decoder["SHIPTOZIP"];
                    myOrder.Country    = decoder["SHIPTOCOUNTRYCODE"];
                    myOrder.Email      = decoder["EMAIL"];
                    myOrder.Total      = Convert.ToDecimal(decoder["AMT"]);

                    // Verify total payment amount as set on CheckoutStart.aspx
                    try {
                        var paymentAmountOnCheckout = Convert.ToDecimal(Session["payment_amt"].ToString());
                        var paymentAmountFromPayPal = Convert.ToDecimal(decoder["AMT"]);
                        if (paymentAmountOnCheckout != paymentAmountFromPayPal)
                        {
                            Response.Redirect("/Checkout/CheckoutError.aspx?Desc=Amount%20total%20mismatch.");
                        }
                    } catch (Exception) {
                        Response.Redirect("/Checkout/CheckoutError.aspx?Desc=Amount%20total%20mismatch.");
                    }

                    // Get DB context
                    var _db = new ProductContext();

                    // Add order to db
                    _db.Orders.Add(myOrder);
                    _db.SaveChanges();

                    // Get the shopping cart items and process them.
                    using (var usersShoppingCart = new ShoppingCartActions()) {
                        var myOrderList = usersShoppingCart.GetCartItems();

                        // Add OrderDetail information to the db for each product purchased
                        foreach (var item in myOrderList)
                        {
                            // Create a new OrderDetail object
                            var myOrderDetail = new OrderDetail {
                                OrderId   = myOrder.OrderId,
                                Username  = User.Identity.Name,
                                ProductId = item.ProductId,
                                Quantity  = item.Quantity,
                                UnitPrice = item.Product.UnitPrice
                            };
                            // Add OrderDetail to db
                            _db.OrderDetails.Add(myOrderDetail);
                            _db.SaveChanges();
                        }
                        // Set OrderId
                        Session["CurrentOrderId"] = myOrder.OrderId;

                        // Display Order information
                        var orderList = new List <Order>();
                        orderList.Add(myOrder);
                        ShipInfo.DataSource = orderList;
                        ShipInfo.DataBind();

                        // Display OrderDetails
                        OrderItemList.DataSource = myOrderList;
                        OrderItemList.DataBind();
                    }
                }
                else
                {
                    Response.Redirect($"/Checkout/CheckoutError.aspx?{retMsg}");
                }
            }
        }
예제 #42
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                NVPAPICaller payPalCaller = new NVPAPICaller();

                string retMsg = "";
                string token = "";
                string PayerID = "";
                NVPCodec decoder = new NVPCodec();
                token = Session["token"].ToString();

                bool ret = payPalCaller.GetCheckoutDetails(token, ref PayerID, ref decoder, ref retMsg);
                if (ret)
                {
                    Session["payerId"] = PayerID;

                    var myOrder = new Order();
                    myOrder.OrderDate = Convert.ToDateTime(decoder["TIMESTAMP"].ToString());
                    myOrder.Username = User.Identity.Name;
                    myOrder.FirstName = decoder["FIRSTNAME"].ToString();
                    myOrder.LastName = decoder["LASTNAME"].ToString();
                    myOrder.Address = decoder["SHIPTOSTREET"].ToString();
                    myOrder.City = decoder["SHIPTOCITY"].ToString();
                    myOrder.State = decoder["SHIPTOSTATE"].ToString();
                    myOrder.PostalCode = decoder["SHIPTOZIP"].ToString();
                    myOrder.Country = decoder["SHIPTOCOUNTRYCODE"].ToString();
                    myOrder.Email = decoder["EMAIL"].ToString();
                    myOrder.Total = Convert.ToDecimal(decoder["AMT"].ToString());

                    // Verify total payment amount as set on CheckoutStart.aspx.
                    try
                    {
                        decimal paymentAmountOnCheckout = Convert.ToDecimal(Session["payment_amt"].ToString());
                        decimal paymentAmoutFromPayPal = Convert.ToDecimal(decoder["AMT"].ToString());
                        if (paymentAmountOnCheckout != paymentAmoutFromPayPal)
                        {
                            Response.Redirect("CheckoutError.aspx?" + "Desc=Amount%20total%20mismatch.");
                        }
                    }
                    catch (Exception)
                    {
                        Response.Redirect("CheckoutError.aspx?" + "Desc=Amount%20total%20mismatch.");
                    }

                    // Get DB context.
                    DataContext _db = new DataContext();

                    // Add order to DB.
                    _db.Orders.Add(myOrder);
                    _db.SaveChanges();

                    // Get the shopping cart items and process them.
                    using (talker.logic.ShoppingCartActions usersShoppingCart = new talker.logic.ShoppingCartActions())
                    {
                        List<CartItem> myOrderList = usersShoppingCart.GetCartItems();

                        // Add OrderDetail information to the DB for each product purchased.
                        for (int i = 0; i < myOrderList.Count; i++)
                        {
                            // Create a new OrderDetail object.
                            var myOrderDetail = new OrderDetail();
                            myOrderDetail.OrderId = myOrder.OrderId;
                            myOrderDetail.Username = User.Identity.Name;
                            myOrderDetail.ProductId = myOrderList[i].DiscussionId;
                            myOrderDetail.Quantity = 1;
                            myOrderDetail.UnitPrice = myOrderList[i].Discussion.TransactionAmount;

                            // Add OrderDetail to DB.
                            _db.OrderDetails.Add(myOrderDetail);
                            _db.SaveChanges();
                        }

                        // Set OrderId.
                        Session["currentOrderId"] = myOrder.OrderId;

                        // Display Order information.
                        List<Order> orderList = new List<Order>();
                        orderList.Add(myOrder);
                        ShipInfo.DataSource = orderList;
                        ShipInfo.DataBind();

                        // Display OrderDetails.
                        OrderItemList.DataSource = myOrderList;
                        OrderItemList.DataBind();
                    }
                }
                else
                {
                    Response.Redirect("CheckoutError.aspx?" + retMsg);
                }
            }
        }
        //private ApplicationDbContext db = new ApplicationDbContext();
        //
        // GET: /Checkout/
        public ActionResult CheckoutStart()
        {
            NVPAPICaller payPalCaller = new NVPAPICaller();
            string ErrorMessage = "Unkown";
            string retMsg = "Messgae from PayPal";
            string token = "";

            if (Session["payment_amt"] != null)
            {
                string amt = Session["payment_amt"].ToString();

              bool ret = payPalCaller.ShortcutExpressCheckout(amt, ref token, ref retMsg);
             // bool ret = true;
                if (ret)
                {
                    Session["token"] = token;
                    return Redirect(retMsg);
                  // return RedirectToAction("CheckoutReview");
                    //return RedirectToAction(retMsg);
                }
                else
                {
                    //Response.Redirect("CheckoutError.aspx?" + retMsg);
                    return RedirectToAction("CheckoutError", retMsg);
                }
            }
            else
            {
               // Response.Redirect("CheckoutError.aspx?ErrorCode=AmtMissing");
                ErrorMessage = "AmtMissing";
                RedirectToAction("CheckoutError", ErrorMessage);
            }
            return RedirectToAction("CheckoutError", ErrorMessage);
        }
예제 #44
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                NVPAPICaller payPalCaller = new NVPAPICaller();

                string   retMsg  = "";
                string   token   = "";
                string   PayerID = "";
                NVPCodec decoder = new NVPCodec();
                token = Session["token"].ToString();

                bool ret = payPalCaller.GetCheckoutDetails(token, ref PayerID, ref decoder, ref retMsg);
                if (ret)
                {
                    Session["payerId"] = PayerID;

                    var myOrder   = new Order();
                    var myAddress = new Address();
                    myOrder.OrderDate  = Convert.ToDateTime(decoder["TIMESTAMP"].ToString());
                    myOrder.Username   = User.Identity.Name;
                    myAddress.UserName = decoder["EMAIL"].ToString();
                    // myAddress = "";
                    myAddress.AddressLine1 = decoder["SHIPTOSTREET"].ToString();
                    myAddress.City         = decoder["SHIPTOCITY"].ToString();
                    myAddress.State        = decoder["SHIPTOSTATE"].ToString();
                    myAddress.PostalCode   = decoder["SHIPTOZIP"].ToString();
                    myAddress.Country      = decoder["SHIPTOCOUNTRYCODE"].ToString();
                    myOrder.Email          = decoder["EMAIL"].ToString();
                    myOrder.Total          = Convert.ToDecimal(decoder["AMT"].ToString());

                    // Verify total payment amount as set on CheckoutStart.aspx.
                    try
                    {
                        decimal paymentAmountOnCheckout = Convert.ToDecimal(Session["payment_amt"].ToString());
                        decimal paymentAmoutFromPayPal  = Convert.ToDecimal(decoder["AMT"].ToString());
                        if (paymentAmountOnCheckout != paymentAmoutFromPayPal)
                        {
                            Response.Redirect("CheckoutError.aspx?" + "Desc=Amount%20total%20mismatch.");
                        }
                    }
                    catch (Exception)
                    {
                        Response.Redirect("CheckoutError.aspx?" + "Desc=Amount%20total%20mismatch.");
                    }

                    // Get DB context.
                    ProductContext _db = new ProductContext();

                    // Add order to DB.
                    _db.Orders.Add(myOrder);
                    _db.Addresses.Add(myAddress);
                    _db.SaveChanges();

                    // Get the shopping cart items and process them.
                    using (fashionUtilityApplication.Logic.ShoppingCartActions usersShoppingCart = new fashionUtilityApplication.Logic.ShoppingCartActions())
                    {
                        List <CartItem> myOrderList = usersShoppingCart.GetCartItems();

                        // Add OrderDetail information to the DB for each product purchased.
                        for (int i = 0; i < myOrderList.Count; i++)
                        {
                            // Create a new OrderDetail object.
                            var myOrderDetail = new OrderDetail();
                            myOrderDetail.OrderId   = myOrder.OrderId;
                            myOrderDetail.Username  = User.Identity.Name;
                            myOrderDetail.ProductId = myOrderList[i].ProductId;
                            myOrderDetail.Quantity  = myOrderList[i].Quantity;
                            myOrderDetail.ImagePath = myOrderList[i].ImagePath;
                            myOrderDetail.UnitPrice = myOrderList[i].Product.UnitPrice;

                            // Add OrderDetail to DB.
                            _db.OrderDetails.Add(myOrderDetail);
                            _db.SaveChanges();
                        }

                        // Set OrderId.
                        Session["currentOrderId"] = myOrder.OrderId;

                        // Display Order information.
                        List <Order> orderList = new List <Order>();
                        orderList.Add(myOrder);
                        orderInfo.DataSource = orderList;
                        orderInfo.DataBind();

                        List <Address> addressList = new List <Address>();
                        addressList.Add(myAddress);
                        ShipInfo.DataSource = addressList;
                        ShipInfo.DataBind();


                        // Display OrderDetails.
                        OrderItemList.DataSource = myOrderList;
                        OrderItemList.DataBind();
                    }
                }
                else
                {
                    Response.Redirect("CheckoutError.aspx?" + retMsg);
                }
            }
        }
        public ActionResult CheckoutComplete()
        {
            CheckoutViewModel checkoutViewModel = new CheckoutViewModel();
               string ErrorMessage = "";
            Session["userCheckoutCompleted"]="true";
               if ((string)Session["userCheckoutCompleted"] != "true")
               {
               Session["userCheckoutCompleted"] = string.Empty;
               ErrorMessage = "Unvalidated%20Checkout";
               RedirectToAction("CheckoutError", ErrorMessage);
               }

            NVPAPICaller payPalCaller = new NVPAPICaller();

               string retMsg = "";
               string token = "";
               string finalPaymentAmount = "";
               string PayerID = "";
               NVPCodec decoder = new NVPCodec();
               string PaymentConfirmation = "";

               token = Session["token"].ToString();
               PayerID = Session["payerId"].ToString();
               finalPaymentAmount = Session["payment_amt"].ToString();

              bool ret = payPalCaller.DoCheckoutPayment(finalPaymentAmount, token, PayerID, ref decoder, ref retMsg);
              // bool ret = true;
            if (ret)
               {
             // Retrieve PayPal confirmation value.
              PaymentConfirmation = decoder["PAYMENTINFO_0_TRANSACTIONID"].ToString();

            // PaymentConfirmation ="34rt56789";
            checkoutViewModel.PayementConfirmationNo = PaymentConfirmation;

             // Get the current order id.
             int currentOrderId = -1;
             if (Session["currentOrderId"].ToString() !=string.Empty)
             {
               currentOrderId = Convert.ToInt32(Session["currentOrderID"]);
             }
            string CartID="";
             if (currentOrderId >= 0)
             {
             OrderApplicationService orderApplicationService = new OrderApplicationService();
             var Cart = ShoppingCartActions.GetCart();
             CartID = Cart.ShoppingCartId;
               // Get the order based on order id.
               // Update the order to reflect payment has been completed.Clear shopping cart.
               orderApplicationService.UpdateOrderEmptyCart(currentOrderId, PaymentConfirmation, CartID);

             }

             // Clear order id.
             Session["currentOrderId"] = string.Empty;
               }
               else
               {
               RedirectToAction("CheckoutError", retMsg);
               }
            return View("CheckoutComplete", checkoutViewModel);
        }