상속: SearchRequest
예제 #1
0
        public async Task <ActionResult> Index()
        {
            CheckoutModel model = new CheckoutModel();

            model.SavedCards     = new CreditCard[0];
            model.SavedAddresses = new Braintree.Address[0];

            if (User.Identity.IsAuthenticated)
            {
                Braintree.CustomerSearchRequest search = new Braintree.CustomerSearchRequest();
                string email = db.AspNetUsers.Single(x => x.UserName == User.Identity.Name).Email;
                search.Email.Is(email);
                var searchResult = await _braintreeGateway.Customer.SearchAsync(search);

                Braintree.Customer customer = searchResult.FirstItem;
                model.SavedCards     = customer.CreditCards;
                model.SavedAddresses = customer.Addresses;
                model.CustomerId     = customer.Id;
                model.FirstName      = customer.FirstName;
                model.LastName       = customer.LastName;
                model.Email          = customer.Email;
                model.Phone          = customer.Phone;
            }


            model.Basket = this.GetBasket(db);
            return(View(model));
        }
        public async Task <IActionResult> Index()
        {
            CheckOutViewModel model = new CheckOutViewModel();

            await GetCurrentCart(model);

            if (User.Identity.IsAuthenticated)
            {
                TCPUser currentUser = await _signInManager.UserManager.GetUserAsync(User);

                Braintree.CustomerSearchRequest search = new Braintree.CustomerSearchRequest();
                search.Email.Is(currentUser.Email);
                var searchResult = await _brainTreeGateway.Customer.SearchAsync(search);

                if (searchResult.Ids.Count > 0)
                {
                    Braintree.Customer customer = searchResult.FirstItem;
                    model.CreditCards = customer.CreditCards;
                    model.Addresses   = customer.Addresses;
                }
            }
            if (model.Cart == null)
            {
                return(RedirectToAction("Index", "Home"));
            }

            return(View(model));
        }
        public ActionResult Index()
        {
            var customerRequest = new CustomerSearchRequest().
                Id.Is(Request.QueryString["id"]);
            ResourceCollection<Customer> customers = Constants.Gateway.Customer.Search(customerRequest);
            // There should only ever be one customer with the given ID
            Customer customer = customers.FirstItem;
            string PaymentMethodToken = customer.CreditCards[0].Token;
            var SubscriptionRequest = new SubscriptionRequest
            {
                PaymentMethodToken = PaymentMethodToken,
                PlanId = "test_plan_1"
            };
            Result<Subscription> result = Constants.Gateway.Subscription.Create(SubscriptionRequest);

            if (result.IsSuccess())
            {
                ViewData["Message"] = result.Target.Status;
            }
            else
            {
                ViewData["Message"] = string.Join(", ", result.Errors.DeepAll());
            }

            return View();
        }
예제 #4
0
        public virtual ResourceCollection <Customer> Search(CustomerSearchRequest query)
        {
            NodeWrapper response = new NodeWrapper(Service.Post("/customers/advanced_search_ids", query));

            return(new ResourceCollection <Customer>(response, delegate(String[] ids) {
                return FetchCustomers(query, ids);
            }));
        }
예제 #5
0
        public virtual async Task <ResourceCollection <Customer> > SearchAsync(CustomerSearchRequest query)
        {
            var response = new NodeWrapper(await service.PostAsync(service.MerchantPath() + "/customers/advanced_search_ids", query));

            return(new ResourceCollection <Customer>(response, delegate(string[] ids) {
                return FetchCustomers(query, ids);
            }));
        }
예제 #6
0
        public virtual ResourceCollection<Customer> Search(CustomerSearchRequest query)
        {
            NodeWrapper response = new NodeWrapper(Service.Post("/customers/advanced_search_ids", query));

            return new ResourceCollection<Customer>(response, delegate(String[] ids) {
                return FetchCustomers(query, ids);
            });
        }
예제 #7
0
        public virtual async Task <ResourceCollection <Customer> > AllAsync()
        {
            var response = new NodeWrapper(await service.PostAsync(service.MerchantPath() + "/customers/advanced_search_ids").ConfigureAwait(false));
            var query    = new CustomerSearchRequest();

            return(new ResourceCollection <Customer>(response, delegate(string[] ids) {
                return FetchCustomers(query, ids);
            }));
        }
예제 #8
0
        public virtual ResourceCollection <Customer> All()
        {
            var response = new NodeWrapper(service.Post(service.MerchantPath() + "/customers/advanced_search_ids"));
            var query    = new CustomerSearchRequest();

            return(new ResourceCollection <Customer>(response, delegate(string[] ids) {
                return FetchCustomers(query, ids);
            }));
        }
        public virtual ResourceCollection<Customer> All()
        {
            var response = new NodeWrapper(service.Post(service.MerchantPath() + "/customers/advanced_search_ids"));
            var query = new CustomerSearchRequest();

            return new ResourceCollection<Customer>(response, delegate(string[] ids) {
                return FetchCustomers(query, ids);
            });
        }
예제 #10
0
        private List <Customer> FetchCustomers(CustomerSearchRequest query, String[] ids)
        {
            query.Ids.IncludedIn(ids);

            NodeWrapper response = new NodeWrapper(Service.Post("/customers/advanced_search", query));

            List <Customer> customers = new List <Customer>();

            foreach (NodeWrapper node in response.GetList("customer"))
            {
                customers.Add(new Customer(node, Service));
            }
            return(customers);
        }
예제 #11
0
        private List <Customer> FetchCustomers(CustomerSearchRequest query, string[] ids)
        {
            query.Ids.IncludedIn(ids);

            var response = new NodeWrapper(service.Post(service.MerchantPath() + "/customers/advanced_search", query));

            var customers = new List <Customer>();

            foreach (var node in response.GetList("customer"))
            {
                customers.Add(new Customer(node, gateway));
            }
            return(customers);
        }
예제 #12
0
        // GET: Checkout
        public ActionResult Index()
        {
            CheckoutDetails details = new CheckoutDetails();
            Guid            cartId  = Guid.Parse(Request.Cookies["cartId"].Value);

            details.CurrentCart = db.Carts.Find(cartId);

            details.Addresses = new Braintree.Address[0];

            if (User.Identity.IsAuthenticated)
            {
                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);

                var customerGateway = gateway.Customer;

                Braintree.CustomerSearchRequest query = new Braintree.CustomerSearchRequest();
                query.Email.Is(User.Identity.Name);
                var matchedCustomers        = customerGateway.Search(query);
                Braintree.Customer customer = null;
                if (matchedCustomers.Ids.Count == 0)
                {
                    Braintree.CustomerRequest newCustomer = new Braintree.CustomerRequest();
                    newCustomer.Email = User.Identity.Name;

                    var result = customerGateway.Create(newCustomer);
                    customer = result.Target;
                }
                else
                {
                    customer = matchedCustomers.FirstItem;
                }

                details.Addresses = customer.Addresses;
            }

            return(View(details));
        }
예제 #13
0
        public Braintree.Customer GetCustomer(string email)
        {
            var customerGateway = gateway.Customer;

            Braintree.CustomerSearchRequest query = new Braintree.CustomerSearchRequest();
            query.Email.Is(email);
            var matchedCustomers = customerGateway.Search(query);

            Braintree.Customer customer = null;
            if (matchedCustomers.Ids.Count == 0)
            {
                Braintree.CustomerRequest newCustomer = new Braintree.CustomerRequest();
                newCustomer.Email = email;

                var result = customerGateway.Create(newCustomer);
                customer = result.Target;
            }
            else
            {
                customer = matchedCustomers.FirstItem;
            }
            return(customer);
        }
예제 #14
0
        public async Task <string> GetCustomerId(string email, string phone, string firstName, string lastName)
        {
            Braintree.CustomerSearchRequest search = new Braintree.CustomerSearchRequest();
            search.Email.Is(email);
            var searchResult = await _braintreeGateway.Customer.SearchAsync(search);

            if (searchResult.Ids.Any())
            {
                return(searchResult.FirstItem.Id);
            }
            else
            {
                Braintree.CustomerRequest customer = new Braintree.CustomerRequest();
                customer.Email     = email;
                customer.Phone     = phone;
                customer.FirstName = firstName;
                customer.LastName  = lastName;

                var customerResult = await _braintreeGateway.Customer.CreateAsync(customer);

                return(customerResult.Target.Id);
            }
        }
예제 #15
0
        public async Task <Braintree.Customer> GetCustomerAsync(string email)
        {
            var customerGateway         = gateway.Customer;
            CustomerSearchRequest query = new Braintree.CustomerSearchRequest();

            query.Email.Is(email);
            var matchedCustomers = await customerGateway.SearchAsync(query);

            if (matchedCustomers.Ids.Count == 0)
            {
                CustomerRequest newCustomer = new CustomerRequest()
                {
                    Email = email
                };

                var result = await customerGateway.CreateAsync(newCustomer);

                return(result.Target);
            }
            else
            {
                return(matchedCustomers.FirstItem);
            }
        }
예제 #16
0
        [ValidateAntiForgeryToken] //this prevents automated scripts from trying to register
        public async Task <IActionResult> Register(RegisterViewModel model)
        {
            //Check to confirm that my register model is filled out correctly
            if (ModelState.IsValid)
            {
                //this is creating my new user.  I simply used email only rather than username
                BurgerStoreUser newEmail = new BurgerStoreUser
                {
                    UserName    = model.Email,
                    Email       = model.Email,
                    FirstName   = model.FirstName,
                    LastName    = model.LastName,
                    PhoneNumber = model.PhoneNumber
                };

                IdentityResult creationResult = await this._signInManager.UserManager.CreateAsync(newEmail);

                if (creationResult.Succeeded)
                {
                    IdentityResult passwordResult = await this._signInManager.UserManager.AddPasswordAsync(newEmail, model.Password);

                    if (passwordResult.Succeeded)
                    {
                        Braintree.CustomerSearchRequest search = new Braintree.CustomerSearchRequest();
                        search.Email.Is(model.Email);
                        var searchResult = await _braintreeGateway.Customer.SearchAsync(search);

                        if (searchResult.Ids.Count == 0)
                        {
                            //creating a new braintree customer here
                            await _braintreeGateway.Customer.CreateAsync(new Braintree.CustomerRequest
                            {
                                Email     = model.Email,
                                FirstName = model.FirstName,
                                LastName  = model.LastName,
                                Phone     = model.PhoneNumber
                            });
                        }
                        else
                        {
                            //update the existing braintree customer

                            Braintree.Customer existingCustomer = searchResult.FirstItem;
                            await _braintreeGateway.Customer.UpdateAsync(existingCustomer.Id, new Braintree.CustomerRequest
                            {
                                FirstName = model.FirstName,
                                LastName  = model.LastName,
                                Phone     = model.PhoneNumber
                            });
                        }



                        var confirmationToken = await _signInManager.UserManager.GenerateEmailConfirmationTokenAsync(newEmail);

                        confirmationToken = System.Net.WebUtility.UrlEncode(confirmationToken);

                        string     currentUrl      = Request.GetDisplayUrl();
                        System.Uri uri             = new System.Uri(currentUrl);
                        string     confirmationUrl = uri.GetLeftPart(System.UriPartial.Authority);
                        confirmationUrl += "/account/confirm?id=" + confirmationToken + "&userId=" + System.Net.WebUtility.UrlEncode(newEmail.Id);
                        await this._signInManager.SignInAsync(newEmail, false);

                        var emailResult = await this._emailService.SendEmailAsync(model.Email, "Welcome to Flavor Town Burgers", "<p> Thanks for signing up, " + model.Email + "!</p><p>< a href =\"" + confirmationUrl + "\">Confirm your account<a></p>", "Thanks for signing up, " + model.Email);

                        if (emailResult.Success)
                        {
                            return(RedirectToAction("Index", "Home"));
                        }
                        else
                        {
                            return(BadRequest(emailResult.Message));
                        }
                    }
                    else
                    {
                        this._signInManager.UserManager.DeleteAsync(newEmail).Wait();
                        foreach (var error in passwordResult.Errors)
                        {
                            ModelState.AddModelError(error.Code, error.Description);
                        }
                    }
                }
                else
                {
                    foreach (var error in creationResult.Errors)
                    {
                        ModelState.AddModelError(error.Code, error.Description);
                    }
                }
            }

            return(View());
        }
        public async Task <IActionResult> Register(Models.RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                TCPUser newUser = new TCPUser {
                    Email       = model.email,
                    UserName    = model.userName,
                    FirstName   = model.firstName,
                    LastName    = model.lastName,
                    PhoneNumber = model.phoneNumber
                };

                IdentityResult creationResult = this._signInManager.UserManager.CreateAsync(newUser).Result;
                if (creationResult.Succeeded)
                {
                    IdentityResult passwordResult = this._signInManager.UserManager.AddPasswordAsync(newUser, model.password).Result;
                    if (passwordResult.Succeeded)
                    {
                        Braintree.CustomerSearchRequest search = new Braintree.CustomerSearchRequest();
                        search.Email.Is(model.email);
                        var searchResult = await _braintreeGateway.Customer.SearchAsync(search);

                        if (searchResult.Ids.Count == 0)
                        {
                            //Create  a new Braintree Customer
                            await _braintreeGateway.Customer.CreateAsync(new Braintree.CustomerRequest
                            {
                                Email     = model.email,
                                FirstName = model.firstName,
                                LastName  = model.lastName,
                                Phone     = model.phoneNumber
                            });
                        }
                        else
                        {
                            //Update the existing Braintree customer
                            Braintree.Customer existingCustomer = searchResult.FirstItem;
                            await _braintreeGateway.Customer.UpdateAsync(existingCustomer.Id, new Braintree.CustomerRequest
                            {
                                FirstName = model.firstName,
                                LastName  = model.lastName,
                                Phone     = model.phoneNumber
                            });
                        }

                        var confirmationToken = await _signInManager.UserManager.GenerateEmailConfirmationTokenAsync(newUser);

                        confirmationToken = System.Net.WebUtility.UrlEncode(confirmationToken);

                        string     currentUrl      = Request.GetDisplayUrl();               //This will get me the URL for the current request
                        System.Uri uri             = new Uri(currentUrl);                   //This will wrap it in a "URI" object so I can split it into parts
                        string     confirmationUrl = uri.GetLeftPart(UriPartial.Authority); //This gives me just the scheme + authority of the URI
                        confirmationUrl += "/account/confirm?id=" + confirmationToken + "&userId=" + System.Net.WebUtility.UrlEncode(newUser.Id);
                        await this._signInManager.SignInAsync(newUser, false);

                        var emailResult = await this._emailService.SendEmailAsync(
                            model.email,
                            "Welcome to The Chesed Project!",
                            "<p>Thanks for signing up, " + model.userName + "!</p><p><a href=\"" + confirmationUrl + "\">Confirm your account<a></p>",
                            "Thanks for signing up, " + model.userName + "!"
                            );

                        if (!emailResult.Success)
                        {
                            throw new Exception(string.Join(',', emailResult.Errors.Select(x => x.Message)));
                        }
                        return(RedirectToAction("Index", "Home"));
                    }

                    else
                    {
                        foreach (var error in creationResult.Errors)
                        {
                            ModelState.AddModelError(error.Code, error.Description);
                        }
                    }
                }
                else
                {
                    foreach (var error in creationResult.Errors)
                    {
                        ModelState.AddModelError(error.Code, error.Description);
                    }
                }
            }
            return(View());
        }
예제 #18
0
        public async Task <IActionResult> Index(CheckoutViewModel model)
        {
            if (ModelState.IsValid)
            {
                // load cart
                if (Request.Cookies.ContainsKey("cartId"))
                {
                    if (Guid.TryParse(Request.Cookies["cartId"], out var cartId))
                    {
                        model.Cart = await _oContext.Carts
                                     .Include(carts => carts.CartItems)
                                     .ThenInclude(cartitems => cartitems.Yacht)
                                     .FirstOrDefaultAsync(x => x.CookieIdentifier == cartId);
                    }
                }

                Order order = new Order
                {
                    TrackingNumber = Guid.NewGuid().ToString(),
                    OrderDate      = DateTime.Now,
                    OrderItems     = model.Cart.CartItems.Select(x => new OrderItem
                    {
                        Yacht = x.Yacht,

                        DatesFrom = x.DatesFrom,
                        DatesTo   = x.DatesTo
                    }).ToArray(),
                    FirstName   = model.FirstName,
                    LastName    = model.LastName,
                    Email       = model.Email,
                    Address     = model.Address,
                    Country     = model.Country,
                    Zip         = model.Zip,
                    PhoneNumber = model.PhoneNumber
                };


                Braintree.Customer customer            = null;
                Braintree.CustomerSearchRequest search = new Braintree.CustomerSearchRequest();
                search.Email.Is(model.Email);
                var searchResult = await _braintreeGateway.Customer.SearchAsync(search);

                if (searchResult.Ids.Count == 0)
                {
                    //Create  a new Braintree Customer
                    Braintree.Result <Customer> creationResult =
                        await _braintreeGateway.Customer.CreateAsync(new Braintree.CustomerRequest
                    {
                        Email = model.Email,
                        Phone = model.PhoneNumber
                    });

                    customer = creationResult.Target;
                }
                else
                {
                    customer = searchResult.FirstItem;
                }


                //More on card testing: https://developers.braintreepayments.com/reference/general/testing/dotnet
                var transaction = new TransactionRequest
                {
                    Amount = model.Cart.CartItems.Sum(x => (x.Yacht.PriceHighSeason ?? 0)),

                    CreditCard = new TransactionCreditCardRequest
                    {
                        Number          = model.CCnumber,
                        CardholderName  = model.NameOnCard,
                        CVV             = model.CVV,
                        ExpirationMonth = model.ExpirationMonth?.PadLeft(2, '0'),
                        ExpirationYear  = model.ExpirationYear
                    },
                    CustomerId = customer.Id,
                    LineItems  = model.Cart.CartItems.Select(x => new TransactionLineItemRequest
                    {
                        Name = x.Yacht.Name,
                        // Description = x.Yacht.Description,
                        ProductCode  = x.Yacht.ID.ToString(),
                        Quantity     = '1',
                        LineItemKind = TransactionLineItemKind.DEBIT,
                        UnitAmount   = x.Yacht.PriceHighSeason, //* x.Quantity,
                        TotalAmount  = x.Yacht.PriceHighSeason  // * x.Quantity
                    }).ToArray()
                };
                var transactionResult = await _braintreeGateway.Transaction.SaleAsync(transaction);

                if (transactionResult.IsSuccess())
                {
                    _oContext.Orders.Add(order);
                    _oContext.CartItems.RemoveRange(model.Cart.CartItems);
                    _oContext.Carts.Remove(model.Cart);
                    await _oContext.SaveChangesAsync();

                    Response.Cookies.Delete("cartId");
                    return(RedirectToAction("Receipt", new { id = order.ID }));
                }
            }

            return(View(model));
        }
예제 #19
0
        private List<Customer> FetchCustomers(CustomerSearchRequest query, String[] ids)
        {
            query.Ids.IncludedIn(ids);

            NodeWrapper response = new NodeWrapper(Service.Post("/customers/advanced_search", query));

            List<Customer> customers = new List<Customer>();
            foreach (NodeWrapper node in response.GetList("customer"))
            {
                customers.Add(new Customer(node, Service));
            }
            return customers;
        }
예제 #20
0
        public async Task <IActionResult> Index(CheckoutViewModel model)
        {
            await GetCurrentCart(model);

            if (ModelState.IsValid)
            {
                if (!string.IsNullOrEmpty(model.SavedAddressId) ||
                    (!string.IsNullOrEmpty(model.ShippingAddressLine1) && !string.IsNullOrEmpty(model.ShippingLocale) &&
                     !string.IsNullOrEmpty(model.ShippingRegion) && !string.IsNullOrEmpty(model.ShippingPostalCode) && !string.IsNullOrEmpty(model.ShippingCountry)))
                {
                    Order newOrder = new Order
                    {
                        TrackingNumber = Guid.NewGuid().ToString(),
                        OrderDate      = DateTime.Now,
                        OrderItems     = model.Cart.CartItems.Select(x => new OrderItem
                        {
                            ProductID    = x.Product.ID,
                            ProductName  = x.Product.Name,
                            ProductPrice = (x.Product.Price ?? 0),
                            Quantity     = x.Quantity
                        }).ToArray(),
                        AddressLine1 = model.ShippingAddressLine1,
                        AddressLine2 = model.ShippingAddressLine2,
                        Country      = model.ShippingCountry,
                        Email        = model.ContactEmail,
                        PhoneNumber  = model.ContactPhoneNumber,
                        Locale       = model.ShippingLocale,
                        PostalCode   = model.ShippingPostalCode,
                        Region       = model.ShippingRegion
                    };

                    Braintree.Customer customer            = null;
                    Braintree.CustomerSearchRequest search = new Braintree.CustomerSearchRequest();
                    search.Email.Is(model.ContactEmail);

                    var searchResult = await _brainTreeGateway.Customer.SearchAsync(search);

                    if (searchResult.Ids.Count == 0)
                    {
                        //Create  a new Braintree Customer
                        Braintree.Result <Customer> creationResult = await _brainTreeGateway.Customer.CreateAsync(new Braintree.CustomerRequest
                        {
                            Email = model.ContactEmail,
                            Phone = model.ContactPhoneNumber
                        });

                        customer = creationResult.Target;
                    }
                    else
                    {
                        customer = searchResult.FirstItem;
                    }

                    CreditCard creditCard = null;
                    if (model.SaveBillingCard)
                    {
                        var newCardRequest = new CreditCardRequest
                        {
                            CardholderName  = model.BillingNameOnCard,
                            CustomerId      = customer.Id,
                            ExpirationMonth = model.BillingCardExpirationMonth.ToString().PadLeft(2, '0'),
                            ExpirationYear  = model.BillingCardExpirationYear.ToString(),
                            Number          = model.BillingCardNumber,
                            CVV             = model.BillingCardVerificationValue
                        };

                        var newCardResult = await _brainTreeGateway.CreditCard.CreateAsync(newCardRequest);

                        if (newCardResult.IsSuccess())
                        {
                            creditCard = newCardResult.Target;
                        }
                    }

                    Address savedAddress = null;
                    if (model.SaveShippingAddress)
                    {
                        var newAddressRequest = new AddressRequest
                        {
                            StreetAddress   = model.ShippingAddressLine1,
                            ExtendedAddress = model.ShippingAddressLine2,
                            CountryName     = model.ShippingCountry,
                            PostalCode      = model.ShippingPostalCode,
                            Locality        = model.ShippingLocale,
                            Region          = model.ShippingRegion
                        };
                        var newAddressResult = await _brainTreeGateway.Address.CreateAsync(customer.Id, newAddressRequest);

                        if (newAddressResult.IsSuccess())
                        {
                            savedAddress = newAddressResult.Target;
                        }
                    }
                    else
                    {
                    }

                    TransactionRequest transaction = new TransactionRequest
                    {
                        Amount = model.Cart.CartItems.Sum(x => x.Quantity * (x.Product.Price ?? 0)),

                        CustomerId = customer.Id,
                        LineItems  = model.Cart.CartItems.Select(x => new TransactionLineItemRequest
                        {
                            Name         = x.Product.Name,
                            Description  = x.Product.Description,
                            ProductCode  = x.Product.ID.ToString(),
                            Quantity     = x.Quantity,
                            LineItemKind = TransactionLineItemKind.DEBIT,
                            UnitAmount   = x.Product.Price * x.Quantity,
                            TotalAmount  = x.Product.Price * x.Quantity
                        }).ToArray()
                    };


                    if (creditCard == null)
                    {
                        transaction.CreditCard = new TransactionCreditCardRequest
                        {
                            Number          = model.BillingCardNumber,
                            CardholderName  = model.BillingNameOnCard,
                            CVV             = model.BillingCardVerificationValue,
                            ExpirationMonth = model.BillingCardExpirationMonth.ToString().PadLeft(2, '0'),
                            ExpirationYear  = model.BillingCardExpirationYear.ToString()
                        };
                    }
                    else
                    {
                        transaction.PaymentMethodToken = creditCard.Token;
                    }

                    if (savedAddress != null)
                    {
                        transaction.ShippingAddressId = savedAddress.Id;
                    }


                    var transactionResult = await _brainTreeGateway.Transaction.SaleAsync(transaction);

                    if (transactionResult.IsSuccess())
                    {
                        _thisSiteDbContext.Orders.Add(newOrder);
                        _thisSiteDbContext.CartItems.RemoveRange(model.Cart.CartItems);
                        _thisSiteDbContext.Carts.Remove(model.Cart);
                        await _thisSiteDbContext.SaveChangesAsync();

                        //Try to checkout
                        //Confirmation Email
                        //TODO: var serOrder serializes user order.  I want to parse this JSON and send to SendGrid template for custom receipt

                        /*var serOrder = JsonConvert.SerializeObject(newOrder, Formatting.Indented,
                         *  new JsonSerializerSettings
                         *  {
                         *      ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                         *  });
                         */


                        var user = model.ContactEmail;
                        var orderCompleteSubject = "Order #" + newOrder.TrackingNumber + " Completed";
                        var htmlContent          = "Thanks for placing your order with us! Please reference your order number above.";
                        var plainTextContent     = "Thanks for placing your order with us! Please reference your order number above.";

                        var emailResult = await _emailService.SendEmailAsync(user, orderCompleteSubject, htmlContent, plainTextContent);

                        //await _emailService.SendEmailAsync(user, orderCompleteSubject, htmlContent, plainTextContent);
                        if (!emailResult.Success)
                        {
                            throw new Exception(string.Join(',', emailResult.Errors.Select(x => x.Message)));
                        }
                        Response.Cookies.Delete("cartId");
                        return(RedirectToAction("Index", "Receipt", new { id = newOrder.TrackingNumber }));
                    }

                    for (int i = 0; i < transactionResult.Errors.Count; i++)
                    {
                        ModelState.AddModelError("BillingCardNumber" + i, transactionResult.Errors.All()[i].Message);
                    }
                }
            }
            return(View(model));
        }
예제 #21
0
        public async Task <IActionResult> Index(Checkout model)
        {
            await GetCurrentCart(model);

            model.Addresses = new Address[0];

            if (ModelState.IsValid)
            {
                if (!string.IsNullOrEmpty(model.SavedAddressId) ||
                    (!string.IsNullOrEmpty(model.ShippingAddressLine1) && !string.IsNullOrEmpty(model.ShippingLocale) &&
                     !string.IsNullOrEmpty(model.ShippingRegion) && !string.IsNullOrEmpty(model.ShippingPostalCode) && !string.IsNullOrEmpty(model.ShippingCountry)))
                {
                    Order neworder = new Order
                    {
                        TrackingNumber = Guid.NewGuid().ToString(),
                        OrderDate      = DateTime.Now,
                        OrderItems     = model.Cart.CartItems.Select(x => new OrderItem
                        {
                            ProductID    = x.Product.ID,
                            ProductName  = x.Product.Name,
                            ProductPrice = (x.Product.Price ?? 0),
                            Quantity     = x.Quantity
                        }).ToArray(),
                        AddressLine1 = model.ShippingAddressLine1,
                        AddressLine2 = model.ShippingAddressLine2,
                        Country      = model.ShippingCountry,
                        Email        = model.ContactEmail,
                        PhoneNumber  = model.ContactPhoneNumber,
                        Locale       = model.ShippingLocale,
                        PostalCode   = model.ShippingPostalCode,
                        Region       = model.ShippingRegion
                    };

                    Braintree.Customer customer            = null;
                    Braintree.CustomerSearchRequest search = new Braintree.CustomerSearchRequest();
                    search.Email.Is(model.ContactEmail);
                    var searchResult = await _brainTreeGateway.Customer.SearchAsync(search);

                    if (searchResult.Ids.Count == 0)
                    {
                        //Create  a new Braintree Customer
                        Braintree.Result <Customer> creationResult = await _brainTreeGateway.Customer.CreateAsync(new Braintree.CustomerRequest
                        {
                            Email = model.ContactEmail,
                            Phone = model.ContactPhoneNumber
                        });

                        customer = creationResult.Target;
                    }
                    else
                    {
                        customer = searchResult.FirstItem;
                    }

                    CreditCard creditCard = null;
                    if (model.SaveBillingCard)
                    {
                        var newCardRequest = new CreditCardRequest
                        {
                            CardholderName  = model.BillingNameOnCard,
                            CustomerId      = customer.Id,
                            ExpirationMonth = model.BillingCardExpirationMonth.ToString().PadLeft(2, '0'),
                            ExpirationYear  = model.BillingCardExpirationYear.ToString(),
                            Number          = model.BillingCardNumber,
                            CVV             = model.BillingCardVerificationValue
                        };
                        var newCardResult = await _brainTreeGateway.CreditCard.CreateAsync(newCardRequest);

                        if (newCardResult.IsSuccess())
                        {
                            creditCard = newCardResult.Target;
                        }
                    }

                    Address savedAddress = null;
                    if (model.SaveShippingAddress)
                    {
                        var newAddressRequest = new AddressRequest
                        {
                            StreetAddress   = model.ShippingAddressLine1,
                            ExtendedAddress = model.ShippingAddressLine2,
                            CountryName     = model.ShippingCountry,
                            PostalCode      = model.ShippingPostalCode,
                            Locality        = model.ShippingLocale,
                            Region          = model.ShippingRegion
                        };
                        var newAddressResult = await _brainTreeGateway.Address.CreateAsync(customer.Id, newAddressRequest);

                        if (newAddressResult.IsSuccess())
                        {
                            savedAddress = newAddressResult.Target;
                        }
                    }

                    TransactionRequest transaction = new TransactionRequest
                    {
                        Amount = model.Cart.CartItems.Sum(x => x.Quantity * (x.Product.Price ?? 0)),


                        CustomerId = customer.Id,
                        LineItems  = model.Cart.CartItems.Select(x => new TransactionLineItemRequest
                        {
                            Name         = x.Product.Name,
                            Description  = x.Product.Description,
                            ProductCode  = x.Product.ID.ToString(),
                            Quantity     = x.Quantity,
                            LineItemKind = TransactionLineItemKind.DEBIT,
                            UnitAmount   = x.Product.Price * x.Quantity,
                            TotalAmount  = x.Product.Price * x.Quantity
                        }).ToArray()
                    };

                    if (creditCard == null)
                    {
                        transaction.CreditCard = new TransactionCreditCardRequest
                        {
                            Number          = model.BillingCardNumber,
                            CardholderName  = model.BillingNameOnCard,
                            CVV             = model.BillingCardVerificationValue,
                            ExpirationMonth = model.BillingCardExpirationMonth.ToString().PadLeft(2, '0'),
                            ExpirationYear  = model.BillingCardExpirationYear.ToString()
                        };
                    }
                    else
                    {
                        transaction.PaymentMethodToken = creditCard.Token;
                    }
                    if (savedAddress != null)
                    {
                        transaction.ShippingAddressId = savedAddress.Id;
                    }


                    var transactionResult = await _brainTreeGateway.Transaction.SaleAsync(transaction);

                    if (transactionResult.IsSuccess())
                    {
                        _context.Orders.Add(neworder);

                        _context.CartItems.RemoveRange(model.Cart.CartItems);
                        _context.Carts.Remove(model.Cart);


                        await _context.SaveChangesAsync();

                        Response.Cookies.Delete("cartId");

                        RegisterViewModel regModel = new RegisterViewModel();
                        var plainText = "Thanks for signing up, " + regModel.FirstName + "!";
                        var htmlText  = "<p> Thanks for Shopping with us, " + regModel.FirstName + "!</p>";

                        await _emailService.SendEmailAsync(model.ContactEmail, "Your Receipt", htmlText, plainText);



                        return(RedirectToAction("Confirmation", "Checkout", new { id = neworder.TrackingNumber }));
                    }
                    for (int i = 0; i < transactionResult.Errors.Count; i++)
                    {
                        ModelState.AddModelError("BillingCardNumber" + i, transactionResult.Errors.All()[i].Message);
                    }
                }

                //#region use the SendGrid client to send a welcome email
                //var client = new SendGrid.SendGridClient(_sendGridKey);
                //var senderAddress = new SendGrid.Helpers.Mail.EmailAddress("*****@*****.**", "Organic-Farm Store");
                //var subject = "Your Receipt";
                //var to = new SendGrid.Helpers.Mail.EmailAddress(emailReceipt.Email, emailReceipt.Email);
                //var plainText = "Thanks for signing up, " + emailReceipt.FirstName + "!";
                //var htmlText = "<p> Thanks for Shopping with us, " + emailReceipt.FirstName + "!</p>";
                //var message = SendGrid.Helpers.Mail.MailHelper.CreateSingleEmail(senderAddress, to, subject, plainText, htmlText);
                //var mailResult = await client.SendEmailAsync(message);

                //if ((mailResult.StatusCode == System.Net.HttpStatusCode.OK) || (mailResult.StatusCode == System.Net.HttpStatusCode.Accepted))
                //{
                //    return RedirectToAction("Confirmation");
                //}

                //else
                //{
                //    return BadRequest(await mailResult.Body.ReadAsStringAsync());
                //}


                //#endregion
            }
            return(View(model));
        }
        public async Task <IActionResult> Index(CheckOutViewModel model)
        {
            await GetCurrentCart(model);

            if (ModelState.IsValid)
            {
                if (!string.IsNullOrEmpty(model.SavedAddressId) ||
                    (!string.IsNullOrEmpty(model.ShippingAddressLine1) && !string.IsNullOrEmpty(model.ShippingCity) &&
                     !string.IsNullOrEmpty(model.ShippingState) && !string.IsNullOrEmpty(model.ShippingZipcode) && !string.IsNullOrEmpty(model.ShippingCountry)))
                {
                    Order newOrder = new Order
                    {
                        TrackingNumber = Guid.NewGuid().ToString(),
                        OrderDate      = DateTime.Now,
                        OrderItems     = model.Cart.CartItems.Select(x => new OrderItem
                        {
                            ProductID    = x.Product.ID,
                            ProductName  = x.Product.Name,
                            ProductPrice = (x.Product.Price ?? 0),
                            Quantity     = x.Quantity
                        }).ToArray(),

                        AddressLine1 = model.ShippingAddressLine1,
                        AddressLine2 = model.ShippingAddressLine2,
                        State        = model.ShippingState,
                        Country      = model.ShippingCountry,
                        Email        = model.email,
                        phoneNumber  = model.phoneNumber,
                        Locale       = model.ShippingCity,
                        PostalCode   = model.ShippingZipcode,
                    };

                    Braintree.Customer customer            = null;
                    Braintree.CustomerSearchRequest search = new Braintree.CustomerSearchRequest();
                    search.Email.Is(model.email);
                    var searchResult = await _brainTreeGateway.Customer.SearchAsync(search);

                    if (searchResult.Ids.Count == 0)
                    {
                        //Create  a new Braintree Customer
                        Braintree.Result <Customer> creationResult = await _brainTreeGateway.Customer.CreateAsync(new Braintree.CustomerRequest
                        {
                            Email = model.email,
                            Phone = model.phoneNumber
                        });

                        customer = creationResult.Target;
                    }
                    else
                    {
                        customer = searchResult.FirstItem;
                    }
                    CreditCard creditCard = null;
                    if (model.SaveBillingCard)
                    {
                        var newCardRequest = new CreditCardRequest
                        {
                            CardholderName  = model.NameOnCard,
                            CustomerId      = customer.Id,
                            ExpirationMonth = model.BillingCardExpirationMonth.ToString().PadLeft(2, '0'),
                            ExpirationYear  = model.BillingCardExpirationYear.ToString(),
                            Number          = model.CardNumber,
                            CVV             = model.CVV
                        };
                        var newCardResult = await _brainTreeGateway.CreditCard.CreateAsync(newCardRequest);

                        if (newCardResult.IsSuccess())
                        {
                            creditCard = newCardResult.Target;
                        }
                    }

                    Address savedAddress = null;
                    if (model.SaveShippingAddress)
                    {
                        var newAddressRequest = new AddressRequest
                        {
                            StreetAddress   = model.ShippingAddressLine1,
                            ExtendedAddress = model.ShippingAddressLine2,
                            CountryName     = model.ShippingCountry,
                            PostalCode      = model.ShippingZipcode,
                            Locality        = model.ShippingCity,
                            Region          = model.ShippingState
                        };
                        var newAddressResult = await _brainTreeGateway.Address.CreateAsync(customer.Id, newAddressRequest);

                        if (newAddressResult.IsSuccess())
                        {
                            savedAddress = newAddressResult.Target;
                        }
                    }



                    TransactionRequest transaction = new TransactionRequest
                    {
                        //Amount = 1,
                        Amount     = model.Cart.CartItems.Sum(x => x.Quantity * (x.Product.Price ?? 0)),
                        CustomerId = customer.Id,
                        LineItems  = model.Cart.CartItems.Select(x => new TransactionLineItemRequest
                        {
                            Name         = x.Product.Name,
                            Description  = x.Product.Description,
                            ProductCode  = x.Product.ID.ToString(),
                            Quantity     = x.Quantity,
                            LineItemKind = TransactionLineItemKind.DEBIT,
                            UnitAmount   = x.Product.Price * x.Quantity,
                            TotalAmount  = x.Product.Price * x.Quantity
                        }).ToArray()
                    };

                    if (creditCard == null)
                    {
                        transaction.CreditCard = new TransactionCreditCardRequest
                        {
                            Number          = model.CardNumber,
                            CardholderName  = model.NameOnCard,
                            CVV             = model.CVV,
                            ExpirationMonth = model.BillingCardExpirationMonth.ToString().PadLeft(2, '0'),
                            ExpirationYear  = model.BillingCardExpirationYear.ToString()
                        };
                    }
                    else
                    {
                        transaction.PaymentMethodToken = creditCard.Token;
                    }
                    if (savedAddress != null)
                    {
                        transaction.ShippingAddressId = savedAddress.Id;
                    }


                    var transactionResult = await _brainTreeGateway.Transaction.SaleAsync(transaction);

                    if (transactionResult.IsSuccess())
                    {
                        _context.Orders.Add(newOrder);
                        _context.CartItems.RemoveRange(model.Cart.CartItems);
                        _context.Carts.Remove(model.Cart);
                        await _context.SaveChangesAsync();

                        //Try to checkout
                        Response.Cookies.Delete("cartId");
                        return(RedirectToAction("Index", "Receipt", new { id = newOrder.TrackingNumber }));
                    }
                    for (int i = 0; i < transactionResult.Errors.Count; i++)
                    {
                        ModelState.AddModelError("BillingCardNumber" + i, transactionResult.Errors.All()[i].Message);
                    }



                    //Try to checkout
                    Response.Cookies.Delete("cartId");
                    return(RedirectToAction("Index", "Receipt", new { id = newOrder.TrackingNumber }));
                }
            }

            return(View(model));
        }
        [ValidateAntiForgeryToken]                                          //Demands the right token from the submitted page by making sure original user heuristics are the same
        public async Task <IActionResult> Register(RegisterViewModel model) //We're binding the RegisterViewModel model class to access it's properties
        {
            if (ModelState.IsValid)
            {
                //TODO: Create an account and log him in
                //  OrganicStoreUser newUser = new OrganicStoreUser(model.UserName);
                OrganicStoreUser newUser = new OrganicStoreUser
                {
                    UserName    = model.UserName,
                    Email       = model.Email,
                    PhoneNumber = model.PhoneNumber,
                    FirstName   = model.FirstName,
                    LastName    = model.LastName
                };
                IdentityResult creationResult = await _signInManager.UserManager.CreateAsync(newUser);

                if (creationResult.Succeeded)
                {
                    //TODO: Create an account and log this user in
                    IdentityResult passwordResult = await this._signInManager.UserManager.AddPasswordAsync(newUser, model.Password);

                    if (passwordResult.Succeeded)
                    {
                        Braintree.CustomerSearchRequest search = new Braintree.CustomerSearchRequest();
                        search.Email.Is(model.Email);
                        var searchResult = await _braintreeGateway.Customer.SearchAsync(search);

                        if (searchResult.Ids.Count == 0)
                        {
                            //Create  a new Braintree Customer
                            await _braintreeGateway.Customer.CreateAsync(new Braintree.CustomerRequest
                            {
                                Email     = model.Email,
                                FirstName = model.FirstName,
                                LastName  = model.LastName,
                                Phone     = model.PhoneNumber
                            });
                        }
                        else
                        {
                            //Update the existing Braintree customer
                            Braintree.Customer existingCustomer = searchResult.FirstItem;
                            await _braintreeGateway.Customer.UpdateAsync(existingCustomer.Id, new Braintree.CustomerRequest
                            {
                                FirstName = model.FirstName,
                                LastName  = model.LastName,
                                Phone     = model.PhoneNumber
                            });
                        }


                        var confirmationToken = await _signInManager.UserManager.GenerateEmailConfirmationTokenAsync(newUser);

                        confirmationToken = System.Net.WebUtility.UrlEncode(confirmationToken); // This will format our token which might have the plus signs, dashes, etc

                        string     currentUrl      = Request.GetDisplayUrl();                   //This will get me the URL for the current request
                        System.Uri uri             = new Uri(currentUrl);                       //This will wrap it in a "URI" object so I can split it into parts
                        string     confirmationUrl = uri.GetLeftPart(UriPartial.Authority);     //This gives me just the scheme + authority of the URI
                        confirmationUrl += "/account/confirm?id=" + confirmationToken + "&userId=" + System.Net.WebUtility.UrlEncode(newUser.Id);

                        #region use the SendGrid client to send a welcome email
                        var mailResult = await _emailService.SendEmailAsync(
                            model.Email,
                            "Welcome to Organic-Farm Store!",
                            "<p>Thanks for signing up, " + model.UserName + "!</p><p><a href=\"" + confirmationUrl + "\">Confirm your account<a></p>",
                            "Thanks for signing up, " + model.UserName + "!"
                            //"Thanks for signing up, " + model.UserName + "!",
                            //"<p>Thanks for signing up, " + model.UserName + "!</p>"
                            );

                        if (mailResult.Success)
                        {
                            return(RedirectToAction("RegisterConfirmation"));
                        }
                        else
                        {
                            return(BadRequest(mailResult.Message));
                        }
                        #endregion

                        //#region use the SendGrid client to send a welcome email
                        //var client = new SendGrid.SendGridClient(_sendGridKey);
                        //var senderAddress = new SendGrid.Helpers.Mail.EmailAddress("*****@*****.**", "CT O-Store");
                        //var subject = "Welcome to OrganicStore";
                        //var to = new SendGrid.Helpers.Mail.EmailAddress(model.Email, model.Email);
                        //var plainText = "Thanks for signing up, " + model.FirstName + "!";
                        //var htmlText = "<p> Thanks for signing up with us, " + model.FirstName + "!</p>";
                        //var message = SendGrid.Helpers.Mail.MailHelper.CreateSingleEmail(senderAddress, to, subject, plainText, htmlText);
                        //var mailResult = await client.SendEmailAsync(message);

                        //if ((mailResult.StatusCode == System.Net.HttpStatusCode.OK) || (mailResult.StatusCode == System.Net.HttpStatusCode.Accepted))
                        //    return RedirectToAction("RegisterConfirmation");
                        //else
                        //    return BadRequest(await mailResult.Body.ReadAsStringAsync());

                        //#endregion

                        //this._signInManager.SignInAsync(newUser, false);
                        // return RedirectToAction("SignIn", "Account");
                    }
                    else
                    {
                        foreach (var error in passwordResult.Errors)
                        {
                            ModelState.AddModelError(error.Code, error.Description);
                        }
                    }
                }
                else
                {
                    foreach (var error in creationResult.Errors)
                    {
                        ModelState.AddModelError(error.Code, error.Description);
                    }
                }

                // return RedirectToAction("Index", "Home");
            }
            return(View());
        }
 private string GetCustomerId(string email)
 {
     var query = new CustomerSearchRequest();
     query.Email.Is(email);
     return this.gateway.Value.Customer.Search(query).OfType<Customer>().FirstOrDefault()?.Id;
 }
        private List<Customer> FetchCustomers(CustomerSearchRequest query, string[] ids)
        {
            query.Ids.IncludedIn(ids);

            var response = new NodeWrapper(service.Post(service.MerchantPath() + "/customers/advanced_search", query));

            var customers = new List<Customer>();
            foreach (var node in response.GetList("customer"))
            {
                customers.Add(new Customer(node, gateway));
            }
            return customers;
        }