public ActionResult Index() { 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.CustomerSearchRequest search = new Braintree.CustomerSearchRequest(); search.Email.Equals(User.Identity.Name); var customers = braintreeGateway.Customer.Search(search); if (customers.Ids != null && customers.Ids.Count() > 0) { var customer = customers.FirstItem; ViewBag.Addresses = customer.Addresses; ViewBag.CreditCards = customer.CreditCards; Customer c = db.Customers.FirstOrDefault(x => x.EmailAddress == customer.Email); if (c != null) { return(View(c)); } } return(View(db.Customers.FirstOrDefault(x => x.AspNetUser.UserName == User.Identity.Name))); }
public async Task <ActionResult> CreateAddress(string fname, string lname, string region, string locality, string postalCode, string street1, string street2) { if (ModelState.IsValid) { 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.CustomerSearchRequest search = new Braintree.CustomerSearchRequest(); search.Email.Equals(User.Identity.Name); var customers = await braintreeGateway.Customer.SearchAsync(search); if (customers != null) { var customer = customers.FirstItem; await braintreeGateway.Address.CreateAsync(customer.Id, new Braintree.AddressRequest { FirstName = fname, LastName = lname, StreetAddress = street1 + " " + street2, Locality = locality, Region = region, }); } TempData["Message"] = "Address created"; return(RedirectToAction("Index")); } return(View()); }
public ActionResult Index() { 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.PriavteKey"]; 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; } return(View(customer)); }
private async Task SetupViewAsync(ShippingViewModel model) { if (User.Identity.IsAuthenticated) { Braintree.CustomerSearchRequest customerSearch = new Braintree.CustomerSearchRequest(); var user = await _signInManager.UserManager.FindByIdAsync(User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier).Value); customerSearch.Email.Is(user.Email); //this is the problem line returns null var customers = await _braintreeGateway.Customer.SearchAsync(customerSearch); if (customers.Ids.Any()) { var customer = customers.FirstItem; model.SavedCreditCards = customer.CreditCards.Select(x => new SavedCreditCard { Token = x.Token, LastFour = x.LastFour }).ToArray(); } else { model.SavedCreditCards = new SavedCreditCard[0]; } model.Email = user.Email; } 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.CartLineItems) .ThenInclude(y => y.ProductConfiguration) .ThenInclude(y => y.Product) .Include(x => x.CartLineItems) .ThenInclude(y => y.ProductConfiguration) .ThenInclude(y => y.Size) .Include(x => x.CartLineItems) .ThenInclude(y => y.ProductConfiguration) .ThenInclude(y => y.Color) .Single(x => x.TrackingNumber == trackingNumber); model.CartLineItem = cart.CartLineItems.ToArray(); } }
public ActionResult DeleteAddress(string id) { 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.CustomerSearchRequest search = new Braintree.CustomerSearchRequest(); search.Email.Equals(User.Identity.Name); var customers = braintreeGateway.Customer.Search(search); if (customers.Ids != null) { var customer = customers.FirstItem; braintreeGateway.Address.Delete(customer.Id, id); TempData["Message"] = "Address Deleted"; } return(RedirectToAction("Index")); }
// GET: Checkout public ActionResult Index() { Models.CheckoutDetails details = new Models.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)); }
public async Task <IActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { BoatChartesUser newUser = new BoatChartesUser { UserName = model.UserName, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName, PhoneNumber = model.PhoneNumber }; IdentityResult creationResult = await this._signInManager.UserManager.CreateAsync(newUser); if (creationResult.Succeeded) { 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); 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 My Boat!", "<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 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 <ActionResult> Register(string username, string fname, string lname, DateTime?dateOfBirth, string phone, string password) { IdentityUser newUser = new IdentityUser(username) { // set the Email to be the username Email = username, PhoneNumber = phone }; IdentityResult result = await UserManager.CreateAsync(newUser, password); if (!result.Succeeded) { ViewBag.Errors = result.Errors; return(View()); } // Check if new registrant has ordered before. If so, they should already have a Customer record // We don't want to create a new one - just modify their record to add the AspNetUserID string custID = ""; Customer existingCustomer = db.Customers.FirstOrDefault(x => x.EmailAddress == username); if (existingCustomer == null) { var newCustomer = new Customer { AspNetUserID = newUser.Id, FirstName = fname, LastName = lname, DateOfBirth = dateOfBirth, PhoneNumber = phone, EmailAddress = username, DateCreated = DateTime.UtcNow, DateLastModified = DateTime.UtcNow }; custID = newCustomer.Id.ToString(); db.Customers.Add(newCustomer); await db.SaveChangesAsync(); } else { existingCustomer.PhoneNumber = phone; existingCustomer.DateOfBirth = dateOfBirth ?? null; existingCustomer.AspNetUserID = newUser.Id; custID = existingCustomer.Id.ToString(); } 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.CustomerSearchRequest search = new Braintree.CustomerSearchRequest(); search.Email.Equals(username); var existingCustomers = await braintreeGateway.Customer.SearchAsync(search); if (existingCustomers != null || !existingCustomers.Ids.Any()) { Braintree.CustomerRequest c = new Braintree.CustomerRequest { FirstName = fname, LastName = lname, CustomerId = custID, Email = username, Phone = phone }; var creationResult = await braintreeGateway.Customer.CreateAsync(c); } string token = await UserManager.GenerateEmailConfirmationTokenAsync(newUser.Id); string body = string.Format( "<a href=\"{0}/account/confirmaccount?email={1}&token={2}\">Confirm Your Account</a>", Request.Url.GetLeftPart(UriPartial.Authority), username, token); await UserManager.SendEmailAsync(newUser.Id, "Confirm Your WeirdEnsemble Account", body); TempData["ConfirmEmail"] = "Account created. Please check your email inbox to confirm your account!"; return(RedirectToAction("SignIn")); }
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)); }
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)); }