Esempio n. 1
0
        public IActionResult ExtendSubscriptionPaypal([FromBody] PaypalPaymentRequest paymentRequest)
        {
            Console.WriteLine(paymentRequest.paymentNonce);
            Braintree.TransactionRequest request = new Braintree.TransactionRequest()
            {
                PaymentMethodNonce = paymentRequest.paymentNonce,
                Amount             = (decimal)(paymentRequest.amount)
            };

            Braintree.Result <Braintree.Transaction> result = gateway.Transaction.Sale(request);
            if (result.IsSuccess())
            {
                TransactionDto transaction = new TransactionDto();
                transaction.Amount           = (decimal)(paymentRequest.amount);
                transaction.Status           = "succeeded";
                transaction.CustomerId       = 1;
                transaction.PaymentGatewayId = 2;
                transaction.PricingPackageId = paymentRequest.packageId;
                transaction.DateCreated      = DateTime.Now;
                _transactionManipulation.SaveTransaction(transaction);


                SubscriptionDto subscription = _subscriptionManipulation.GetCustomerSubscription(1);
                subscription.SubscriptionExpirationDate = subscription.SubscriptionExpirationDate.AddMonths(1);
                _subscriptionManipulation.UpdateSubscription(subscription);

                return(Ok("Uspjesan placanje"));
            }
            else
            {
                return(BadRequest("Neuspjesna transakcija!"));
            }
        }
Esempio n. 2
0
        public ActionResult Index(CheckoutModel model)
        {
            string publicKey   = ConfigurationManager.AppSettings["Braintree.PublicKey"];
            string privateKey  = ConfigurationManager.AppSettings["Braintree.PrivateKey"];
            string environment = ConfigurationManager.AppSettings["Braintree.Environment"];
            string merchantId  = ConfigurationManager.AppSettings["Braintree.MerchantId"];


            Braintree.BraintreeGateway braintree = new Braintree.BraintreeGateway(environment, merchantId, publicKey, privateKey);
            //int userId = -1;
            if (ModelState.IsValid)
            {
                using (CustomersEntities entities = new CustomersEntities())
                {
                    var currentCustomer = entities.Customers.Single(x => x.EmailAddress == User.Identity.Name);
                    var currentPackage  = currentCustomer.CustomerPackages.First(x => x.PurchaseDate == null);


                    //TODO: Validate the credit card - if it errors out, add a model error and display it to the user
                    //TODO: Persist this information to the database

                    //var currentPackage = entities.Customers.Single(x => x.EmailAddress == User.Identity.Name).CustomerPackages.First(x => x.PurchaseDate == null);
                    //model.Package = new PackageModel();
                    //string publicKey = ConfigurationManager.AppSettings["Braintree.PublicKey"];
                    //string privateKey = ConfigurationManager.AppSettings["Braintree.PrivateKey"];
                    //string environment = ConfigurationManager.AppSettings["Braintree.Environment"];
                    //string merchantId = ConfigurationManager.AppSettings["Braintree.MerchantId"];


                    Braintree.CustomerRequest request = new Braintree.CustomerRequest();
                    request.Email      = model.EmailAddress;
                    request.FirstName  = model.FirstName;
                    request.LastName   = model.LastName;
                    request.Phone      = model.PhoneNumber;
                    request.CreditCard = new Braintree.CreditCardRequest();

                    request.CreditCard.Number          = model.CreditCardNumber;
                    request.CreditCard.CardholderName  = model.CreditCardName;
                    request.CreditCard.ExpirationMonth = (model.CreditCardExpirationMonth).ToString().PadLeft(2, '0');
                    request.CreditCard.ExpirationYear  = model.CreditCardExpirationYear.ToString();


                    var customerResult = braintree.Customer.Create(request);
                    Braintree.TransactionRequest sale = new Braintree.TransactionRequest();
                    sale.Amount = currentPackage.Package.Price;


                    sale.CustomerId         = customerResult.Target.Id;
                    sale.PaymentMethodToken = customerResult.Target.DefaultPaymentMethod.Token;
                    braintree.Transaction.Sale(sale);

                    currentPackage.PurchaseDate = DateTime.UtcNow;
                    entities.SaveChanges();

                    return(RedirectToAction("Receipt", "Membership", null));
                }
            }
            return(View(model));
        }
Esempio n. 3
0
        public async Task <IActionResult> Index(
            string fname,
            string lname,
            string address,
            string state,
            string city,
            int zip,
            string creditcardnumber,
            string creditcardname,
            string creditcardverificationvalue,
            string expirationmonth,
            string expirationyear,
            ShippingModel model)
        {
            ViewData["States"] = new string[] { "Alabama", "Alaska",
                                                "Arkansas", "Illinois" };

            if (ModelState.IsValid)
            {
                string cartId;
                Guid   cartCode;
                if (Request.Cookies.TryGetValue("cartId", out cartId) && Guid.TryParse(cartId, out cartCode) && _context.Carts.Any(x => x.CartCode == cartCode))
                {
                    var cart = _context.Carts.Include(x => x.CartsProducts).ThenInclude(y => y.Product).Single(x => x.CartCode == cartCode);
                    //return View(cart);


                    //var cart = _context.Carts.Include(x => x.CartsProducts).ThenInclude(y => y.Product).Single(x => x.CartCode == cartCode);
                    Braintree.TransactionRequest saleRequest = new Braintree.TransactionRequest();
                    saleRequest.Amount     = cart.CartsProducts.Sum(x => x.Quantity * (x.Product.Price ?? 0));
                    saleRequest.CreditCard = new Braintree.TransactionCreditCardRequest
                    {
                        CardholderName  = creditcardname,
                        CVV             = creditcardverificationvalue,
                        ExpirationMonth = expirationmonth,
                        ExpirationYear  = expirationyear,
                        Number          = creditcardnumber
                    };
                    var result = await _braintreeGateway.Transaction.SaleAsync(saleRequest);

                    if (result.IsSuccess())
                    {
                        //If model state is valid, proceed to the next step.
                        return(RedirectToAction("Index", "Home"));
                    }
                    foreach (var error in result.Errors.All())
                    {
                        ModelState.AddModelError(error.Code.ToString(), error.Message);
                    }
                }
            }
            return(View());
        }
        public async Task <IActionResult> Index(DeliveryViewModel models)
        {
            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"^\d{5}(?:[-\s]\d{4})?$");
            if (string.IsNullOrEmpty(models.ShippingZip) || !regex.IsMatch(models.ShippingZip))
            {
                ModelState.AddModelError("Zip", "The zip code is invalid!");
            }

            if (ModelState.IsValid)
            {
                string cartId;
                Guid   trackingNumber;
                if (Request.Cookies.TryGetValue("cartId", out cartId) && Guid.TryParse(cartId, out trackingNumber) && _context.Cart.Any(x => x.TrackingNumber == trackingNumber))
                {
                    var cart = _context.Cart.Include(x => x.CartProducts).ThenInclude(y => y.Products).Single(x => x.TrackingNumber == trackingNumber);

                    Braintree.TransactionRequest saleRequest = new Braintree.TransactionRequest();
                    saleRequest.Amount     = cart.CartProducts.Sum(x => x.Products.Price * x.Quantity) ?? .01m; //Hard-coded for now
                    saleRequest.CreditCard = new Braintree.TransactionCreditCardRequest
                    {
                        CardholderName  = models.creditcardname,
                        CVV             = models.creditcardverificationvalue,
                        ExpirationMonth = models.expirationmonth,
                        ExpirationYear  = models.expirationyear,
                        Number          = models.creditcardnumber
                    };
                    saleRequest.BillingAddress = new Braintree.AddressRequest
                    {
                        StreetAddress      = models.BillingAddress,
                        PostalCode         = models.BillingZip,
                        Region             = models.BillingState,
                        Locality           = models.BillingCity,
                        CountryName        = "United States of America",
                        CountryCodeAlpha2  = "US",
                        CountryCodeAlpha3  = "USA",
                        CountryCodeNumeric = "840"
                    };
                    var result = await _braintreeGateway.Transaction.SaleAsync(saleRequest);

                    if (result.IsSuccess())
                    {
                        return(this.RedirectToAction("Receipt", "Delivery"));
                    }
                    foreach (var error in result.Errors.All())
                    {
                        ModelState.AddModelError(error.Code.ToString(), error.Message);
                    }
                }
            }
            return(View());
        }
Esempio n. 5
0
        public async Task <IActionResult> Index(CheckoutViewModel model)
        {
            if (ModelState.IsValid)
            {
                Braintree.CustomerRequest customerRequest = new Braintree.CustomerRequest
                {
                };

                Braintree.AddressRequest addressRequest = new Braintree.AddressRequest
                {
                    StreetAddress = model.Billingaddress,
                    PostalCode    = model.BillingZip,
                    Region        = model.BillingState,
                    Locality      = model.BillingCity,
                    CountryName   = "USA"
                };

                Braintree.TransactionRequest saleRequest = new Braintree.TransactionRequest();
                saleRequest.Amount     = 10; //Hard-coded forever because Braintree ain't gonna take $2 million+
                saleRequest.CreditCard = new Braintree.TransactionCreditCardRequest
                {
                    CardholderName  = model.creditcardname,
                    CVV             = model.creditcardverificationvalue,
                    ExpirationMonth = model.expirationmonth,
                    ExpirationYear  = model.expirationyear,
                    Number          = model.creditcardnumber
                };
                saleRequest.BillingAddress = new Braintree.AddressRequest
                {
                    StreetAddress = model.Billingaddress,
                    PostalCode    = model.BillingZip,
                    Region        = model.BillingState,
                    Locality      = model.BillingCity,
                    CountryName   = "USA"
                };
                var result = await _braintreeGateway.Transaction.SaleAsync(saleRequest);

                if (result.IsSuccess())
                {
                    //If model state is valid, proceed to the next step.
                    return(this.RedirectToAction("Index", "Home"));
                }
                foreach (var error in result.Errors.All())
                {
                    ModelState.AddModelError(error.Code.ToString(), error.Message);
                }
            }

            return(View());
        }
Esempio n. 6
0
        public async Task <IActionResult> Index(ShippingViewModel model)
        {
            //System.Text.RegularExpressions.Regex = new System.Text.RegularExpressions.Regex();


            if (ModelState.IsValid)
            {
                Braintree.TransactionRequest saleRequest = new Braintree.TransactionRequest();
                saleRequest.Amount     = 10; //Hard-coded for now
                saleRequest.CreditCard = new Braintree.TransactionCreditCardRequest
                {
                    CardholderName  = model.CreditCardName,
                    CVV             = model.CVV,
                    ExpirationMonth = model.ExpMonth,
                    ExpirationYear  = model.ExpYear,
                    Number          = model.CreditCardNumber
                };
                saleRequest.BillingAddress = new Braintree.AddressRequest
                {
                    StreetAddress      = model.BillingStreet,
                    PostalCode         = model.BillingZipCode,
                    Region             = model.BillingState,
                    Locality           = model.BillingCity,
                    CountryName        = "United States of America",
                    CountryCodeAlpha2  = "US",
                    CountryCodeAlpha3  = "USA",
                    CountryCodeNumeric = "840"
                };
                var result = await _braintreeGateway.Transaction.SaleAsync(saleRequest);

                if (result.IsSuccess())
                {
                    return(this.RedirectToAction("Index", "Home"));
                }
                foreach (var error in result.Errors.All())
                {
                    ModelState.AddModelError(error.Code.ToString(), error.Message);
                }
            }
            return(View(model));
        }
Esempio n. 7
0
        public string Pay(string json)
        {
            int?id = Token.Verify(ListenerRequest.Headers.Get("Authorization"));

            if (id.HasValue)
            {
                var payment = JsonConvert.DeserializeObject <BraintreeClient.PaymentRequest>(json);
                var request = new Braintree.TransactionRequest
                {
                    Amount             = payment.Amount,
                    MerchantAccountId  = "Sandbox_Project",
                    PaymentMethodNonce = payment.Nonce,
                    CustomerId         = id.Value.ToString(),
                    Options            = new Braintree.TransactionOptionsRequest
                    {
                        SubmitForSettlement = true
                    }
                };

                Braintree.Result <Braintree.Transaction> result = BraintreeClient.gateway.Transaction.Sale(request);
                if (result.IsSuccess())
                {
                    StatusCode = 200;
                    return("Successfully paid.");
                }
                else
                {
                    StatusCode = 400;
                    return("Error while paying");
                }
            }
            else
            {
                StatusCode = 403;
                return("Invalid token/user ID");
            }
        }
        public async Task <IActionResult> Index(ShippingViewModel model)
        {
            await SetupViewAsync(model);

            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"^\d{5}(?:[-\s]\d{4})?$");
            if (string.IsNullOrEmpty(model.ShippingZipCode) || !regex.IsMatch(model.ShippingZipCode))
            {
                ModelState.AddModelError("ZipCode", "Invalid ZipCode");
            }

            if (ModelState.IsValid)
            {
                Braintree.CustomerSearchRequest customerSearch = new Braintree.CustomerSearchRequest();
                customerSearch.Email.Is(model.Email);
                Braintree.Customer customer = null;
                var customers = await _braintreeGateway.Customer.SearchAsync(customerSearch);

                if (customers.Ids.Any())
                {
                    customer = customers.FirstItem;
                }
                else
                {
                    Braintree.CustomerRequest newCustomer = new Braintree.CustomerRequest
                    {
                        Email = model.Email
                    };
                    var creationResult = await _braintreeGateway.Customer.CreateAsync(newCustomer);

                    customer = creationResult.Target;
                }
                if (string.IsNullOrEmpty(model.CardToken))
                {
                    Braintree.CreditCard card = null;
                    if (customer.CreditCards.Any())
                    {
                        string lastFour = new string(model.CreditCardNumber.Skip(model.CreditCardNumber.Length - 4).ToArray());

                        card = customer.CreditCards.FirstOrDefault(
                            x => x.ExpirationMonth == model.ExpirationMonth &&
                            x.ExpirationYear == model.ExpirationYear &&
                            x.LastFour == lastFour);
                    }
                    if (card == null)
                    {
                        Braintree.CreditCardRequest newCard = new Braintree.CreditCardRequest
                        {
                            CustomerId      = customer.Id,
                            CardholderName  = model.CreditCardName,
                            CVV             = model.CreditCardVerificationValue,
                            ExpirationMonth = model.ExpirationMonth,
                            ExpirationYear  = model.ExpirationYear,
                            Number          = model.CreditCardNumber
                        };
                        var creationResult = await _braintreeGateway.CreditCard.CreateAsync(newCard);

                        card            = creationResult.Target;
                        model.CardToken = card.Token;
                    }
                }

                Braintree.TransactionRequest saleRequest = new Braintree.TransactionRequest();
                saleRequest.Amount = model.CartLineItem.Sum(x => (x.ProductConfiguration.Product.UnitPrice * x.Quantity ?? .99m));

                saleRequest.CustomerId         = customer.Id;
                saleRequest.PaymentMethodToken = model.CardToken;
                saleRequest.BillingAddress     = new Braintree.AddressRequest
                {
                    StreetAddress      = model.BillingAddress,
                    PostalCode         = model.BillingZipCode,
                    Region             = model.BillingState,
                    Locality           = model.BillingCity,
                    CountryName        = "United States of America",
                    CountryCodeAlpha2  = "US",
                    CountryCodeAlpha3  = "USA",
                    CountryCodeNumeric = "840"
                };

                var result = await _braintreeGateway.Transaction.SaleAsync(saleRequest);

                if (result.IsSuccess())
                {
                    //If model state is valid convert to order and show reciept
                    return(this.RedirectToAction("Index", "Receipt"));
                }

                foreach (var error in result.Errors.All())
                {
                    ModelState.AddModelError(error.Code.ToString(), error.Message);
                }
            }
            return(View(model));
        }
Esempio n. 9
0
        public async Task <ActionResult> Index(CheckoutModel model)
        {
            if (ModelState.IsValid)
            {
                using (AppStoreEntities entities = new AppStoreEntities())
                {
                    Order o = null;
                    if (User.Identity.IsAuthenticated)
                    {
                        AspNetUser currentUser = entities.AspNetUsers.Single(x => x.UserName == User.Identity.Name);
                        o = currentUser.Orders.FirstOrDefault(x => x.TimeCompleted == null);
                        if (o == null)
                        {
                            o             = new Order();
                            o.OrderNumber = Guid.NewGuid();
                            currentUser.Orders.Add(o);
                            entities.SaveChanges();
                        }
                    }
                    else
                    {
                        if (Request.Cookies.AllKeys.Contains("orderNumber"))
                        {
                            Guid orderNumber = Guid.Parse(Request.Cookies["orderNumber"].Value);
                            o = entities.Orders.FirstOrDefault(x => x.TimeCompleted == null && x.OrderNumber == orderNumber);
                        }
                        if (o == null)
                        {
                            o             = new Order();
                            o.OrderNumber = Guid.NewGuid();
                            entities.Orders.Add(o);
                            Response.Cookies.Add(new HttpCookie("orderNumber", o.OrderNumber.ToString()));
                            entities.SaveChanges();
                        }
                    }
                    if (o.OrdersProducts.Sum(x => x.Quantity) == 0)
                    {
                        return(RedirectToAction("Index", "Cart"));
                    }

                    o.BuyerEmail = User.Identity.Name;
                    Address newShippingAddress = new Address();
                    newShippingAddress.Address1 = model.ShippingAddress1;
                    newShippingAddress.Address2 = model.ShippingAddress2;
                    newShippingAddress.City     = model.ShippingCity;
                    newShippingAddress.State    = model.ShippingState;
                    newShippingAddress.Zip      = model.ZipCode;
                    newShippingAddress.Country  = model.ShippingCountry;
                    o.Address1 = newShippingAddress;

                    WhereTo = ("\n Your Order will be shipped to the following address: \n" + model.ShippingAddress1 + "\n " + model.ShippingAddress2 + "\n " + model.ShippingCity + "\n " + model.ShippingState + "\n " + model.ZipCode);

                    entities.sp_CompleteOrder(o.ID);

                    string merchantId  = ConfigurationManager.AppSettings["Braintree.MerchantID"];
                    string publicKey   = ConfigurationManager.AppSettings["Braintree.PublicKey"];
                    string privateKey  = ConfigurationManager.AppSettings["Braintree.PrivateKey"];
                    string environment = ConfigurationManager.AppSettings["Braintree.Environment"];

                    Braintree.BraintreeGateway braintree = new Braintree.BraintreeGateway(environment, merchantId, publicKey, privateKey);

                    Braintree.TransactionRequest newTransaction = new Braintree.TransactionRequest();
                    newTransaction.Amount = o.OrdersProducts.Sum(x => x.Quantity * x.Product.Price) ?? 0.01m;

                    Braintree.TransactionCreditCardRequest creditCard = new Braintree.TransactionCreditCardRequest();
                    creditCard.CardholderName  = model.CreditCardName;
                    creditCard.CVV             = model.CreditCardVerificationValue;
                    creditCard.ExpirationMonth = model.CreditCardExpiration.Value.Month.ToString().PadLeft(2, '0');
                    creditCard.ExpirationYear  = model.CreditCardExpiration.Value.Year.ToString();
                    creditCard.Number          = model.CreditCardNumber;

                    newTransaction.CreditCard = creditCard;

                    // If the user is logged in, associate this transaction with their account
                    if (User.Identity.IsAuthenticated)
                    {
                        Braintree.CustomerSearchRequest search = new Braintree.CustomerSearchRequest();
                        search.Email.Is(User.Identity.Name);
                        var customers = braintree.Customer.Search(search);
                        newTransaction.CustomerId = customers.FirstItem.Id;
                    }

                    Braintree.Result <Braintree.Transaction> result = await braintree.Transaction.SaleAsync(newTransaction);

                    if (!result.IsSuccess())
                    {
                        ModelState.AddModelError("CreditCard", "Could not authorize payment");
                        return(View(model));
                    }

                    string sendGridApiKey = ConfigurationManager.AppSettings["SendGrid.ApiKey"];

                    SendGrid.SendGridClient client = new SendGrid.SendGridClient(sendGridApiKey);
                    SendGrid.Helpers.Mail.SendGridMessage message = new SendGrid.Helpers.Mail.SendGridMessage();
                    //TODO: Go into SendGrid and set up a template and insert the if below
                    //message.SetTemplateId("524c7845-3ed9-4d53-81c8-b467443f8c5c");
                    message.Subject = string.Format("Receipt for order {0}", o.ID);
                    message.From    = new SendGrid.Helpers.Mail.EmailAddress("*****@*****.**", "Will Mabrey");
                    message.AddTo(new SendGrid.Helpers.Mail.EmailAddress(o.BuyerEmail));

                    string prodcuctsReceipt = "You've Ordered: ";
                    WhatWasOrdered = prodcuctsReceipt;

                    foreach (var item in o.OrdersProducts)
                    {
                        string addition = string.Format("\n " + "{0} copies of {1}", item.Quantity, item.Product.Name);
                        prodcuctsReceipt += addition;
                    }


                    SendGrid.Helpers.Mail.Content contents = new SendGrid.Helpers.Mail.Content("text/plain", string.Format("Thank you for ordering through Ye Olde App Store \n {0} {1}", prodcuctsReceipt, WhereTo));
                    message.AddSubstitution("%ordernum%", o.ID.ToString());
                    message.AddContent(contents.Type, contents.Value);

                    SendGrid.Response response = await client.SendEmailAsync(message);

                    o.TimeCompleted = DateTime.UtcNow;

                    entities.SaveChanges();
                }
                return(RedirectToAction("profile", "Home"));
            }
            return(View(model));
        }
Esempio n. 10
0
        public async Task <ActionResult> Index(CheckoutModel model2)
        {
            using (MemberEntities1 entities = new MemberEntities1())
            {
                //int orderId = int.Parse(Request.Cookies["OrderID"].Value);
                var   cart = entities.Carts.Single(x => x.Id == model2.id);
                Order o    = new Order();
                cart.Orders.Add(o);

                if (ModelState.IsValid)
                {
                    bool addressValidationSuccessful = true;
                    bool validateAddress             = false;

                    string smartyStreetsAuthId    = ConfigurationManager.AppSettings["SmartyStreets.AuthId"];
                    string smartyStreetsAuthToken = ConfigurationManager.AppSettings["SmartyStreets.AuthToken"];

                    Rentler.SmartyStreets.SmartyStreetsClient client = new Rentler.SmartyStreets.SmartyStreetsClient(smartyStreetsAuthId, smartyStreetsAuthToken);
                    var addresses = await client.GetStreetAddressAsync(model2.BillingStreet1, null, model2.BillingStreet2, model2.BillingCity, model2.BillingState, model2.BillingPostalCode);

                    if (addresses.Count() == 0)
                    {
                        ModelState.AddModelError("BillingStreet1", "Could not find exact or similiar address");
                        addressValidationSuccessful = false;
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(model2.BillingStreet1) && addresses.First().delivery_line_1 != model2.BillingStreet1)
                        {
                            ModelState.AddModelError("BillingStreet1", string.Format("Suggested Address: {0}", addresses.First().delivery_line_1));
                            addressValidationSuccessful = false;
                        }
                        if (!string.IsNullOrEmpty(model2.BillingStreet2) && addresses.First().delivery_line_2 != model2.BillingStreet2)
                        {
                            ModelState.AddModelError("BillingStreet2", string.Format("Suggested Address: {0}", addresses.First().delivery_line_2));
                            addressValidationSuccessful = false;
                        }
                        if (!string.IsNullOrEmpty(model2.BillingCity) && addresses.First().components.city_name != model2.BillingCity)
                        {
                            ModelState.AddModelError("BillingCity", string.Format("Suggested Address: {0}", addresses.First().components.city_name));
                            addressValidationSuccessful = false;
                        }
                        if (!string.IsNullOrEmpty(model2.BillingPostalCode) && addresses.First().components.zipcode != model2.BillingPostalCode)
                        {
                            ModelState.AddModelError("BillingPostalCode", string.Format("Suggested Address: {0}", addresses.First().components.zipcode));
                            addressValidationSuccessful = false;
                        }
                        if (!string.IsNullOrEmpty(model2.BillingState) && addresses.First().components.state_abbreviation != model2.BillingState)
                        {
                            ModelState.AddModelError("BillingState", string.Format("Suggested Address: {0}", addresses.First().components.state_abbreviation));
                            addressValidationSuccessful = false;
                        }
                    }
                    if (addressValidationSuccessful || !validateAddress)
                    {
                        //TODO: Validate the credit card - if it errors out, add a model error and display it to the user
                        string publicKey   = ConfigurationManager.AppSettings["Braintree.PublicKey"];
                        string privateKey  = ConfigurationManager.AppSettings["Braintree.PrivateKey"];
                        string environment = ConfigurationManager.AppSettings["Braintree.Environment"];
                        string merchantId  = ConfigurationManager.AppSettings["Braintree.MerchantId"];

                        Braintree.BraintreeGateway braintree = new Braintree.BraintreeGateway(environment, merchantId, publicKey, privateKey);

                        int userId = -1;
                        if (string.IsNullOrEmpty(User.Identity.Name))
                        {
                            userId = 34;

                            var customer = braintree.Customer.Find(userId.ToString());

                            Braintree.CustomerRequest request = new Braintree.CustomerRequest();

                            request.CreditCard = new Braintree.CreditCardRequest();

                            request.CreditCard.Number          = model2.CreditCardNumber;
                            request.CreditCard.CardholderName  = model2.CreditCardName;
                            request.CreditCard.ExpirationMonth = (model2.CreditCardExpirationMonth).ToString().PadLeft(2, '0');
                            request.CreditCard.ExpirationYear  = model2.CreditCardExpirationYear.ToString();


                            var customerResult = braintree.Customer.Update(userId.ToString(), request);

                            Braintree.TransactionRequest sale = new Braintree.TransactionRequest();
                            sale.Amount             = decimal.Parse(cart.saleTotal.Replace("USD", string.Empty));
                            sale.CustomerId         = customerResult.Target.Id;
                            sale.PaymentMethodToken = customerResult.Target.DefaultPaymentMethod.Token;
                            braintree.Transaction.Sale(sale);


                            o.FirstName    = model2.FirstName;
                            o.LastName     = model2.LastName;
                            o.EmailAddress = model2.EmailAddress;
                            o.PhoneNumber  = model2.PhoneNumber;

                            o.BillingCity       = model2.BillingCity;
                            o.BillingPostalCode = model2.BillingPostalCode;
                            o.BillingReceipient = model2.BillingReceipient;
                            o.BillingStreet1    = model2.BillingStreet1;
                            o.BillingStreet2    = model2.BillingStreet2;
                            o.BillingState      = model2.BillingState;
                            o.DateCreated       = DateTime.UtcNow;
                            o.DateLastModified  = DateTime.UtcNow;
                            entities.SaveChanges();

                            return(RedirectToAction("Index", "Receipt", new { id = o.OrderId }));
                        }
                        else
                        {
                            using (MemberEntities1 e = new MemberEntities1())
                            {
                                userId = e.CustomerLists.Single(x => x.EmailAddress == User.Identity.Name).ID;
                            }
                            var customer = braintree.Customer.Find(userId.ToString());

                            Braintree.CustomerRequest request = new Braintree.CustomerRequest();

                            request.CreditCard = new Braintree.CreditCardRequest();

                            request.CreditCard.Number          = model2.CreditCardNumber;
                            request.CreditCard.CardholderName  = model2.CreditCardName;
                            request.CreditCard.ExpirationMonth = (model2.CreditCardExpirationMonth).ToString().PadLeft(2, '0');
                            request.CreditCard.ExpirationYear  = model2.CreditCardExpirationYear.ToString();


                            var customerResult = braintree.Customer.Update(userId.ToString(), request);

                            Braintree.TransactionRequest sale = new Braintree.TransactionRequest();
                            sale.Amount             = decimal.Parse(cart.saleTotal.Replace("USD", string.Empty));
                            sale.CustomerId         = customerResult.Target.Id;
                            sale.PaymentMethodToken = customerResult.Target.DefaultPaymentMethod.Token;
                            braintree.Transaction.Sale(sale);


                            o.FirstName    = model2.FirstName;
                            o.LastName     = model2.LastName;
                            o.EmailAddress = model2.EmailAddress;
                            o.PhoneNumber  = model2.PhoneNumber;

                            o.BillingCity       = model2.BillingCity;
                            o.BillingPostalCode = model2.BillingPostalCode;
                            o.BillingReceipient = model2.BillingReceipient;
                            o.BillingStreet1    = model2.BillingStreet1;
                            o.BillingStreet2    = model2.BillingStreet2;
                            o.BillingState      = model2.BillingState;
                            o.DateCreated       = DateTime.UtcNow;
                            o.DateLastModified  = DateTime.UtcNow;
                            entities.SaveChanges();

                            return(RedirectToAction("Index", "Receipt", new { id = o.OrderId }));
                        }
                    }
                }
            }
            return(View(model2));
        }
Esempio n. 11
0
        public async Task <ActionResult> Index(CheckoutViewModel model)
        {
            // if there are errors on the form, refresh the page with the previous model
            // along with errors
            if (ModelState.IsValid)
            {
                // Try to find an existing customer
                Customer currentCustomer = db.Customers.FirstOrDefault(x => x.AspNetUser.UserName == User.Identity.Name);

                // if this is an anonymous customer, create a new Customer record for them
                if (currentCustomer == null)
                {
                    currentCustomer = new Customer
                    {
                        FirstName        = model.FirstName,
                        LastName         = model.LastName,
                        EmailAddress     = model.EmailAddress,
                        PhoneNumber      = model.PhoneNumber,
                        DateCreated      = DateTime.UtcNow,
                        DateLastModified = DateTime.UtcNow
                    };
                    db.Customers.Add(currentCustomer);
                    await db.SaveChangesAsync();

                    if (Request.Cookies.AllKeys.Contains("CartName"))
                    {
                        string cartName = Request.Cookies["CartName"].Value;
                        model.CurrentCart = db.Carts.Single(x => x.Name == cartName);
                    }
                }
                else
                {
                    model.CurrentCart = currentCustomer.Carts.First();
                }



                string merchantId  = ConfigurationManager.AppSettings["Braintree.MerchantID"];
                string publicKey   = ConfigurationManager.AppSettings["Braintree.PublicKey"];
                string privateKey  = ConfigurationManager.AppSettings["Braintree.PrivateKey"];
                string environment = ConfigurationManager.AppSettings["Braintree.Environment"];

                Braintree.BraintreeGateway braintreeGateway = new Braintree.BraintreeGateway
                                                                  (environment, merchantId, publicKey, privateKey);

                Braintree.TransactionRequest request = new Braintree.TransactionRequest();
                request.Amount     = model.CurrentCart.CartItems.Sum(x => x.Product.ListPrice * x.Quantity) ?? .01m;
                request.CreditCard = new Braintree.TransactionCreditCardRequest
                {
                    CardholderName  = model.CreditCardHolder,
                    CVV             = model.CreditCardVerificationValue,
                    Number          = model.CreditCardNumber,
                    ExpirationMonth = model.CreditCardExpirationMonth.ToString().PadLeft(2, '0'),
                    ExpirationYear  = model.CreditCardExpirationYear.ToString()
                };

                Braintree.Result <Braintree.Transaction> result = await braintreeGateway.Transaction.SaleAsync(request);


                if ((result.Errors == null || result.Errors.Count == 0))
                {
                    string transactionId = result.Target.Id;
                    var    order         = new Order
                    {
                        DatePlaced       = DateTime.UtcNow,
                        DateLastModified = DateTime.UtcNow,
                        CustomerID       = currentCustomer.Id,
                        OrderItems       = model.CurrentCart.CartItems.Select(x => new OrderItem
                        {
                            DateLastModified = DateTime.UtcNow,
                            Quantity         = x.Quantity,
                            ProductId        = x.ProductId,
                            PurchasePrice    = x.Product.ListPrice ?? 0
                        }).ToArray(),
                        ShippingAddressLine1 = model.ShippingAddressLine1,
                        TransactionID        = transactionId
                    };

                    // Remove the cart form the database and convert it to an order
                    db.CartItems.RemoveRange(model.CurrentCart.CartItems);
                    db.Carts.Remove(model.CurrentCart);
                    db.Orders.Add(order);
                    await db.SaveChangesAsync();

                    //Remove the basket cookie!
                    Response.SetCookie(new HttpCookie("CartName")
                    {
                        Expires = DateTime.UtcNow
                    });

                    // Send the user an e-mail with their order receipt
                    string body = "<h2>Receipt For WeirdEnsemble.com Order #" + order.TransactionID + "</h2><br/><br/>";
                    body += "<table><thead><tr><th>Item</th><th>List Price</th><th>Quantity</th><th>Total</th></tr></thead>";
                    body += "<tbody>";
                    foreach (var item in order.OrderItems)
                    {
                        body += "<tr>";
                        body += "<td>" + item.Product.Name + "</td>";
                        body += "<td>" + (item.Product.ListPrice ?? 0).ToString("C") + "</td>";
                        body += "<td>" + item.Quantity + "</td>";
                        body += "<td>" + (item.Quantity * (item.Product.ListPrice ?? 0)).ToString("C") + "</td>";
                        body += "</tr>";
                    }
                    body += "</tbody><tfoot><tr><td colspan=\"2\">";
                    body += "<td><strong>Total:</strong></td>";
                    body += "<td><strong>" + (order.OrderItems.Sum(x => x.Quantity * x.Product.ListPrice) ?? 0).ToString("C") + "</strong></td>";
                    body += "</tr></tfoot></table>";

                    SendGridEmailService mail = new SendGridEmailService();
                    await mail.SendAsync(new Microsoft.AspNet.Identity.IdentityMessage
                    {
                        Destination = order.Customer.EmailAddress,
                        Subject     = "Your WeirdEnsemble Order #" + order.TransactionID + " Receipt",
                        Body        = body
                    });


                    return(RedirectToAction("Index", "Receipt", new { id = order.TransactionID }));
                }
                else
                {
                    if (result.Target == null)
                    {
                        ModelState.AddModelError("ResultMessage", result.Message);
                    }
                    else
                    {
                        ModelState.AddModelError("CreditCardNumber", "Unable to authorize this card number");
                    }
                }
            }
            if (Request.Cookies.AllKeys.Contains("CartName"))
            {
                string cartName = Request.Cookies["CartName"].Value;
                model.CurrentCart = db.Carts.Single(x => x.Name == cartName);
            }

            return(View(model));
        }
        public async System.Threading.Tasks.Task <Microsoft.AspNetCore.Mvc.IActionResult> Checkout(Models.Order order, string braintreeNonce)
        {
            if (ModelState.IsValid)
            {
                Braintree.CustomerRequest customer = new Braintree.CustomerRequest();
                // if (User.Identity.IsAuthenticated)
                // {
                //     var user = _context.Users.Single(x => x.UserName == User.Identity.Name);
                //     customer.FirstName = user.FirstName;
                //     customer.LastName = user.LastName;
                // }
                customer.Email = order.Email;
                customer.Phone = order.Phone;
                Braintree.TransactionRequest transactionRequest = new Braintree.TransactionRequest
                {
                    Amount             = cart.Lines.Sum(cartItem => cartItem.Quantity * cartItem.Product.Price),
                    PaymentMethodNonce = order.BraintreeNonce,
                    Customer           = customer,
                    LineItems          = cart.Lines.Select(cartItem => new Braintree.TransactionLineItemRequest
                    {
                        UnitAmount   = cartItem.Product.Price,
                        Name         = cartItem.Product.Name,
                        Description  = cartItem.Product.Description,
                        Quantity     = cartItem.Quantity,
                        TotalAmount  = cartItem.Quantity * cartItem.Product.Price,
                        ProductCode  = cartItem.ProductID.ToString(),
                        LineItemKind = Braintree.TransactionLineItemKind.DEBIT
                    }).ToArray()
                };
                var transactionResult = await _braintreeGateway.Transaction.SaleAsync(transactionRequest);

                //should check for result of transactionResult here, but skipping for sake of demo'ng rest of code
                order.PlacementDate  = System.DateTime.Now;
                order.TrackingNumber = System.Guid.NewGuid().ToString().Substring(0, 8);
                order.SubTotal       = cart.Lines.Sum(x => x.Quantity * x.Product.Price);
                order.Total          = cart.Lines.Sum(x => x.Quantity * x.Product.Price);
                order.Lines          = cart.Lines.ToArray();
                repository.SaveOrder(order);
                if (debug != true)
                {
                    string HtmlLines = "";
                    foreach (Models.CartLine item in order.Lines)
                    {
                        HtmlLines = HtmlLines + "<li>" + item.ProductName + " (quantity: " + item.Quantity + ")</li>";
                    }
                    var message = new SendGrid.Helpers.Mail.SendGridMessage
                    {
                        From        = new SendGrid.Helpers.Mail.EmailAddress("*****@*****.**", "Chalky's Billiard Store Administration"),
                        Subject     = "Receipt for order #" + order.TrackingNumber,
                        HtmlContent = "<h2>Thanks!</h2><p>Thanks for placing your order.</p><p>We'll ship your goods as soon as possible.</p><br/><h2>Order details for Order #" + order.TrackingNumber +
                                      "</h2>Order Date: " + order.PlacementDate + " CT <ul>" + HtmlLines + "</ul>"
                    };
                    message.AddTo(order.Email);
                    var result = await _sendGridClient.SendEmailAsync(message);

                    //This can be helpful debug code, but we wont display it out to the user:
                    var responseBody = await result.DeserializeResponseBodyAsync(result.Body);

                    if (responseBody != null)
                    {
                        foreach (var body in responseBody)
                        {
                            System.Console.WriteLine(body.Key + ":" + body.Value);
                        }
                    }
                }
                return(RedirectToAction(nameof(Completed), new { id = order.OrderID }));
            }
            else
            {
                ViewBag.BraintreeClientToken = await _braintreeGateway.ClientToken.GenerateAsync();

                return(View(order));
            }
        }
        public async Task <ActionResult> Index(CheckoutViewModel model)
        {
            Models.Customer currentUser =
                db.Customers.FirstOrDefault
                    (x => x.AspNetUser.UserName == User.Identity.Name);

            if (Request.Cookies.AllKeys.Contains("CartName"))
            {
                var basketName = Guid.Parse(Request.Cookies["CartName"].Value);
                model.CurrentBasket = db.Orders.Single(x => x.Name == basketName);
            }
            if (ModelState.IsValid)
            {
                string merchantId  = System.Configuration.ConfigurationManager.AppSettings["Braintree.MerchantID"];
                string environment = ConfigurationManager.AppSettings["Braintree.Environment"];
                string publicKey   = ConfigurationManager.AppSettings["Braintree.PublicKey"];
                string privateKey  = ConfigurationManager.AppSettings["Braintree.PrivateKey"];
                Braintree.BraintreeGateway braintreeGateway = new Braintree.BraintreeGateway(environment, merchantId, publicKey, privateKey);

                Braintree.TransactionRequest request = new Braintree.TransactionRequest();
                request.Amount     = model.CurrentBasket.ProdOrders.Sum(x => x.ProdVariant.Product.Price * x.Quantity);
                request.CreditCard = new Braintree.TransactionCreditCardRequest
                {
                    CardholderName  = model.CreditCardHolderName,
                    CVV             = model.CreditCardVerificationValue,
                    Number          = model.CreditCardNumber,
                    ExpirationMonth = model.CreditCardExpirationMonth.ToString().PadLeft(2, '0'),    //This used to be a thing in braintree -- not sure if it still is!
                    ExpirationYear  = model.CreditCardExpirationYear.ToString()
                };
                Braintree.Result <Braintree.Transaction> result = braintreeGateway.Transaction.Sale(request);

                if (result.Errors == null || result.Errors.DeepCount == 0)
                {
                    string transactionId = result.Target.Id;
                    //Remove the basket from the database and convert it to an order
                    model.CurrentBasket.Completed = true;
                    db.SaveChanges();


                    //Remove the basket cookie!
                    Response.SetCookie(new HttpCookie("CartName")
                    {
                        Expires = DateTime.UtcNow
                    });
                    if (User.Identity.IsAuthenticated)
                    {
                        SendGridEmailService mail = new SendGridEmailService();


                        await mail.SendAsync(new Microsoft.AspNet.Identity.IdentityMessage
                        {
                            Destination = model.CurrentBasket.Customer.AspNetUser.Email,
                            Subject     = "Order " + model.CurrentBasket.OId + " Completed",
                            Body        = "Order Body Here"
                        });
                    }
                    return(RedirectToAction("Index", "Receipt", new { id = model.CurrentBasket.OId }));
                }
                else
                {
                    ModelState.AddModelError("CreditCardNumber", "Unable to authorize this card number");
                }
            }
            return(View(model));
        }
Esempio n. 14
0
        public ActionResult Index(Models.CheckoutDetails model)
        {
            Guid cartID = Guid.Parse(Request.Cookies["cartID"].Value);

            model.CurrentCart = db.Carts.Find(cartID);
            if (ModelState.IsValid)
            {
                string  trackingNumber = Guid.NewGuid().ToString().Substring(0, 8);
                decimal Tax            = (model.CurrentCart.Lawyer.Price + model.CurrentCart.HelpType.StandardPrice ?? 0) * .1025m;
                decimal ServiceCharge  = (model.CurrentCart.Lawyer.Price + model.CurrentCart.HelpType.StandardPrice ?? 0) * .10m;
                decimal Total          = (model.CurrentCart.Lawyer.Price + model.CurrentCart.HelpType.StandardPrice ?? 0) * 1.2025m;


                #region pay for order
                string merchantId  = System.Configuration.ConfigurationManager.AppSettings["Braintree.MerchantId"];
                string environment = System.Configuration.ConfigurationManager.AppSettings["Braintree.Environment"];
                string publicKey   = System.Configuration.ConfigurationManager.AppSettings["Braintree.PublicKey"];
                string privateKey  = System.Configuration.ConfigurationManager.AppSettings["Braintree.PrivateKey"];
                Braintree.BraintreeGateway gateway = new Braintree.BraintreeGateway(environment, merchantId, publicKey, privateKey);

                Braintree.TransactionRequest transaction = new Braintree.TransactionRequest();
                // transaction.Amount = 1m;
                transaction.Amount    = Total;
                transaction.TaxAmount = Tax;
                transaction.OrderId   = trackingNumber;

                //https://developers.braintreepayments.com/reference/general/testing/ruby
                transaction.CreditCard = new Braintree.TransactionCreditCardRequest
                {
                    CardholderName  = "Test User",
                    CVV             = "123",
                    Number          = "4111111111111111",
                    ExpirationYear  = DateTime.Now.AddMonths(1).Year.ToString(),
                    ExpirationMonth = DateTime.Now.AddMonths(1).ToString("MM")
                };

                var result = gateway.Transaction.Sale(transaction);
                #endregion

                #region save order
                Order o = new Order
                {
                    DateCreated      = DateTime.UtcNow,
                    DateLastModified = DateTime.UtcNow,
                    TrackingNumber   = trackingNumber,
                    Tax                = Tax,
                    ServiceCharge      = ServiceCharge,
                    Total              = Total,
                    Email              = model.ContactEmail,
                    CustomerName       = model.ContactName,
                    ShippingAddress1   = model.ShippingAddress,
                    ShippingCity       = model.ShippingCity,
                    ShippingPostalCode = model.ShippingPostalCode,
                    ShippingState      = model.ShippingState,
                    Day                = model.CurrentCart.Day,
                    HelpTypeID         = model.CurrentCart.HelpTypeID,
                    LawyerID           = model.CurrentCart.LawyerID
                };
                db.Orders.Add(o);
                db.SaveChanges();
                #endregion

                #region send email
                LawDoggsEmailService emailService = new LawDoggsEmailService();
                emailService.SendAsync(new Microsoft.AspNet.Identity.IdentityMessage
                {
                    Subject     = "Your Order Information",
                    Destination = model.ContactEmail,
                    Body        = "Thank you for your support, here is your order number " + "  " + trackingNumber,
                });
                #endregion

                return(RedirectToAction("Index", "Orders", new { id = trackingNumber }));
            }
            return(View(model));
        }
Esempio n. 15
0
        public ActionResult Payment(CheckOut model, int?id)
        {
            Basket b = new Basket();

            using (EscapeRoomDBEntities entities = new EscapeRoomDBEntities())
            {
                //create basket
                b = entities.Baskets.Single(x => x.ID == id);

                //if logged in, update record and add basket
                if (User.Identity.IsAuthenticated)
                {
                    User user = entities.Users.Single(X => X.Email == User.Identity.Name);
                    user.FirstName   = model.FirstName;
                    user.LastName    = model.LastName;
                    user.Email       = model.Email;
                    user.Phone       = model.Phone;
                    user.DateCreated = DateTime.UtcNow;
                    b.User           = user;
                    entities.SaveChanges();
                }

                //if no login, create user and add basket
                else
                {
                    User user = new Models.User();
                    user.FirstName   = model.FirstName;
                    user.LastName    = model.LastName;
                    user.Email       = model.Email;
                    user.Phone       = model.Phone;
                    user.DateCreated = DateTime.UtcNow;
                    b.User           = user;
                    entities.SaveChanges();
                }
            }

            using (EscapeRoomDBEntities entities = new EscapeRoomDBEntities())
            {
                b = entities.Baskets.Single(x => x.ID == id);
                model.numPlayers = b.Players.Count;
                model.session    = new Models.Session
                {
                    Id    = b.Session.Id,
                    Price = b.Session.Price,
                    Title = b.Session.Title,
                    Start = b.Session.Start
                };
                model.Players = b.Players.ToArray();
            }

            //configure braintree connection and take payment
            string clientID   = ConfigurationManager.AppSettings["Braintree.ClientID"];
            string privateKey = ConfigurationManager.AppSettings["Braintree.PrivateKey"];
            string publicKey  = ConfigurationManager.AppSettings["Braintree.PublicKey"];

            Braintree.IBraintreeGateway gateway = new Braintree.BraintreeGateway(Braintree.Environment.SANDBOX, clientID, publicKey, privateKey);

            Braintree.TransactionRequest request = new Braintree.TransactionRequest
            {
                Amount             = model.session.Price * model.numPlayers,
                PaymentMethodNonce = "fake-valid-nonce",
                Customer           = new Braintree.CustomerRequest
                {
                    FirstName = model.FirstName,
                    LastName  = model.LastName,
                    Email     = model.Email
                },
                BillingAddress = new Braintree.AddressRequest
                {
                    FirstName         = model.FirstName,
                    LastName          = model.LastName,
                    StreetAddress     = model.Address,
                    ExtendedAddress   = model.Unit,
                    Locality          = model.City,
                    Region            = model.State,
                    PostalCode        = model.Zip.ToString(),
                    CountryCodeAlpha2 = "US"
                },

                Options = new Braintree.TransactionOptionsRequest
                {
                    SubmitForSettlement = true,
                    StoreInVault        = true
                },
            };



            Braintree.Result <Braintree.Transaction> result = gateway.Transaction.Sale(request);

            if (result.IsSuccess())
            {
                using (EscapeRoomDBEntities entities = new EscapeRoomDBEntities())
                {
                    Basket completedBasket = entities.Baskets.Single(x => x.ID == id);
                    completedBasket.PurchaseDate = DateTime.UtcNow;
                    entities.SaveChanges();
                }

                return(RedirectToAction("Success", "Checkout", new { id = b.ID }));
            }
            else
            {
                string errorMessages = "";
                foreach (Braintree.ValidationError error in result.Errors.DeepAll())
                {
                    errorMessages += "Error: " + (int)error.Code + " - " + error.Message + "\n";
                }
                TempData["Flash"] = errorMessages;

                return(RedirectToAction("Payment", "Checkout", new { id = b.ID }));
            }
        }
Esempio n. 16
0
        public async Task <IActionResult> Index(ShippingsViewModel model) // this Model info needs to go to braintree.
        {
            if (Request.Cookies.Keys.Contains("cartId") && Guid.TryParse(Request.Cookies["cartId"], out Guid cartId))
            {
                model.Cart = await _context.Cart.Include(c => c.Product).Include(c => c.User).SingleAsync(x => x.CartId == cartId);
            }
            if (ModelState.IsValid)
            {
                Orders newOrder = new Orders();
                newOrder.User    = model.Cart.User;
                newOrder.Product = model.Cart.Product;
                newOrder.LineItems.Add(new LineItem
                {
                    Product  = model.Cart.Product,
                    Quantity = 1
                });
                newOrder.Shipping.Add(new Shipping
                {
                    Address = new Address
                    {
                        Street = model.address.Street,
                        City   = model.address.City,
                        State  = model.address.State,
                        Zip    = model.address.Zip
                    }
                });
                if (ModelState.IsValid)
                {
                    // this is to interact with Braintree. Getting all the user card information and sending it to BrainTree.
                    Braintree.TransactionRequest saleRequest = new Braintree.TransactionRequest();
                    saleRequest.Amount     = model.Cart.Product.Price.Value;
                    saleRequest.CreditCard = new Braintree.TransactionCreditCardRequest
                    {
                        CardholderName  = model.CreditCartName,
                        CVV             = model.CreditCardVerificationValue,
                        ExpirationMonth = model.ExpirationMonth,
                        ExpirationYear  = model.ExpirationYear,
                        Number          = model.CreditCardNumber
                    };

                    // awaiting the result of card validation
                    var result = await _braintreeGateway.Transaction.SaleAsync(saleRequest);

                    if (result.IsSuccess())
                    {
                        _context.Orders.Add(newOrder);     // => this adds the newly created order.
                        _context.Cart.Remove(model.Cart);  // => once it's added, Remove() will clear out the cart.
                        Response.Cookies.Delete("cartId"); // => Delete() will delete the cookie with the cart info.
                        await _context.SaveChangesAsync();

                        return(RedirectToAction("Index", "OrderComplete", new { ID = newOrder.Id }));
                    }
                    foreach (var error in result.Errors.All())
                    {
                        ModelState.AddModelError(error.Code.ToString(), error.Message);
                    }
                }


                //return RedirectToAction("Index", "OrderComplete");
            }
            await _context.SaveChangesAsync();

            return(View(model));
        }
Esempio n. 17
0
        public async Task <IActionResult> Index(CheckoutViewModel model, string braintreeNonce)
        {
            ViewData["clientToken"] = await _braintreeGateway.ClientToken.GenerateAsync();

            if (string.IsNullOrEmpty(braintreeNonce))
            {
                this.ModelState.AddModelError("nonce", "We're unable to validate this credit card");
            }

            if (this.ModelState.IsValid)
            {
                HatUser hatUser = null;
                if (User.Identity.IsAuthenticated)
                {
                    hatUser = _userManager.FindByNameAsync(User.Identity.Name).Result;
                }
                Cart cart = CartService.GetCart(_context, Request, Response, hatUser);

                if (cart.CartItems.Count > 0)
                {
                    var orderId = Guid.NewGuid().ToString().Substring(0, 8);
                    Braintree.TransactionRequest transactionRequest = new Braintree.TransactionRequest();
                    transactionRequest.PaymentMethodNonce  = braintreeNonce;
                    transactionRequest.PurchaseOrderNumber = orderId;
                    transactionRequest.Amount          = cart.CartItems.Sum(x => x.Quantity * x.Product.Price);
                    transactionRequest.ShippingAddress = new Braintree.AddressRequest
                    {
                        StreetAddress   = model.ShippingStreet1,
                        ExtendedAddress = model.ShippingStreet2,
                        PostalCode      = model.ShippingPostalCode,
                        //CountryName = model.ShippingCountry,  //This thing is picky about casing
                        FirstName = model.ContactName.Split(' ').First(),
                        LastName  = model.ContactName.Contains(' ') ? string.Join(' ', model.ContactName.Split(' ').Skip(1)) : "",
                        Locality  = model.ShippingCity,
                        Region    = model.ShippingRegion
                    };
                    transactionRequest.Customer = new Braintree.CustomerRequest
                    {
                        Email = hatUser != null ? hatUser.Email : model.ContactEmail,
                    };
                    transactionRequest.LineItems = cart.CartItems.Select(x => new Braintree.TransactionLineItemRequest
                    {
                        Name         = x.Product.Name,
                        Description  = x.Product.Description,
                        ProductCode  = x.ProductID.ToString(),
                        Quantity     = x.Quantity,
                        UnitAmount   = x.Product.Price,
                        TotalAmount  = x.Product.Price * x.Quantity,
                        LineItemKind = Braintree.TransactionLineItemKind.DEBIT
                    }).ToArray();

                    Braintree.Result <Braintree.Transaction> transactionResult = _braintreeGateway.Transaction.Sale(transactionRequest);
                    if (transactionResult.IsSuccess())
                    {
                        //TODO: Get a lot more info here, validate credit card + address, save it to a database
                        Order order = new Order();
                        order.ID                 = orderId;
                        order.OrderDate          = DateTime.Now.ToString();
                        order.ContactEmail       = model.ContactEmail;
                        order.ContactName        = model.ContactName;
                        order.ContactPhoneNumber = model.ContactPhoneNumber;
                        order.ShippingCity       = model.ShippingCity;
                        order.ShippingCountry    = model.ShippingCountry;
                        order.ShippingPostalCode = model.ShippingPostalCode;
                        order.ShippingRegion     = model.ShippingRegion;
                        order.ShippingStreet1    = model.ShippingStreet1;
                        order.ShippingStreet2    = model.ShippingStreet2;


                        order.OrderItems = cart.CartItems.Select(ci => new OrderItem
                        {
                            ProductID   = ci.ProductID,
                            Color       = ci.ProductColor != null ? ci.ProductColor.Color : null,
                            Description = ci.Product.Description,
                            Name        = ci.Product.Name,
                            Price       = ci.Product.Price,
                            Quantity    = ci.Quantity,
                            Size        = ci.ProductSize != null ? ci.ProductSize.Size : null
                        }).ToArray();

                        _context.CartItems.RemoveRange(cart.CartItems);
                        _context.Carts.Remove(cart);
                        Response.Cookies.Delete("HatShopCartInfo");
                        _context.Orders.Add(order);
                        if (hatUser != null)
                        {
                            order.HatUser = hatUser;
                        }

                        _context.SaveChanges();
                        await _emailSender.SendEmailAsync(model.ContactEmail, "Receipt for order #" + order.ID, "Thanks for your order!");

                        return(RedirectToAction("index", "receipt", new { id = order.ID }));
                    }
                }
                ModelState.AddModelError("cart", "There was a problem processing your cart");
            }
            return(View(model));
        }