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(string firstName, string lastName, string id) { Braintree.Customer customer = paymentServices.UpdateCustomer(firstName, lastName, id); ViewBag.Message = "Updated Successfully"; return(View(customer)); }
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)); }
// 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)); }
public void Setup() { gateway = new BraintreeGateway { Environment = Environment.DEVELOPMENT, MerchantId = "integration_merchant_id", PublicKey = "integration_public_key", PrivateKey = "integration_private_key" }; CustomerRequest request = new CustomerRequest { CreditCard = new CreditCardRequest { CardholderName = "Fred Jones", Number = "5105105105105100", ExpirationDate = "05/12" } }; customer = gateway.Customer.Create(request).Target; creditCard = customer.CreditCards[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); }
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)); }
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()); }
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)); }
internal Transaction(NodeWrapper node, BraintreeService service) { Service = service; if (node == null) return; Id = node.GetString("id"); Amount = node.GetDecimal("amount"); AvsErrorResponseCode = node.GetString("avs-error-response-code"); AvsPostalCodeResponseCode = node.GetString("avs-postal-code-response-code"); AvsStreetAddressResponseCode = node.GetString("avs-street-address-response-code"); GatewayRejectionReason = (TransactionGatewayRejectionReason)CollectionUtil.Find( TransactionGatewayRejectionReason.ALL, node.GetString("gateway-rejection-reason"), null ); OrderId = node.GetString("order-id"); Status = (TransactionStatus)CollectionUtil.Find(TransactionStatus.ALL, node.GetString("status"), TransactionStatus.UNRECOGNIZED); List<NodeWrapper> statusNodes = node.GetList("status-history/status-event"); StatusHistory = new StatusEvent[statusNodes.Count]; for (int i = 0; i < statusNodes.Count; i++) { StatusHistory[i] = new StatusEvent(statusNodes[i]); } Type = (TransactionType)CollectionUtil.Find(TransactionType.ALL, node.GetString("type"), TransactionType.UNRECOGNIZED); MerchantAccountId = node.GetString("merchant-account-id"); ProcessorAuthorizationCode = node.GetString("processor-authorization-code"); ProcessorResponseCode = node.GetString("processor-response-code"); ProcessorResponseText = node.GetString("processor-response-text"); PurchaseOrderNumber = node.GetString("purchase-order-number"); RefundedTransactionId = node.GetString("refunded-transaction-id"); #pragma warning disable 0618 RefundId = node.GetString("refund-id"); #pragma warning restore 0618 RefundIds = node.GetStrings("refund-ids/*"); SettlementBatchId = node.GetString("settlement-batch-id"); SubscriptionId = node.GetString("subscription-id"); TaxAmount = node.GetDecimal("tax-amount"); TaxExempt = node.GetBoolean("tax-exempt"); CustomFields = node.GetDictionary("custom-fields"); CreditCard = new CreditCard(node.GetNode("credit-card"), service); Subscription = new Subscription(node.GetNode("subscription"), service); Customer = new Customer(node.GetNode("customer"), service); CurrencyIsoCode = node.GetString("currency-iso-code"); CvvResponseCode = node.GetString("cvv-response-code"); Descriptor = new Descriptor(node.GetNode("descriptor")); BillingAddress = new Address(node.GetNode("billing")); ShippingAddress = new Address(node.GetNode("shipping")); CreatedAt = node.GetDateTime("created-at"); UpdatedAt = node.GetDateTime("updated-at"); AddOns = new List<AddOn>(); foreach (NodeWrapper addOnResponse in node.GetList("add-ons/add-on")) { AddOns.Add(new AddOn(addOnResponse)); } Discounts = new List<Discount>(); foreach (NodeWrapper discountResponse in node.GetList("discounts/discount")) { Discounts.Add(new Discount(discountResponse)); } }
protected internal Transaction(NodeWrapper node, BraintreeGateway gateway) { Gateway = gateway; if (node == null) return; Id = node.GetString("id"); Amount = node.GetDecimal("amount"); AvsErrorResponseCode = node.GetString("avs-error-response-code"); AvsPostalCodeResponseCode = node.GetString("avs-postal-code-response-code"); AvsStreetAddressResponseCode = node.GetString("avs-street-address-response-code"); GatewayRejectionReason = (TransactionGatewayRejectionReason)CollectionUtil.Find( TransactionGatewayRejectionReason.ALL, node.GetString("gateway-rejection-reason"), TransactionGatewayRejectionReason.UNRECOGNIZED ); PaymentInstrumentType = (PaymentInstrumentType)CollectionUtil.Find( PaymentInstrumentType.ALL, node.GetString("payment-instrument-type"), PaymentInstrumentType.UNKNOWN ); Channel = node.GetString("channel"); OrderId = node.GetString("order-id"); Status = (TransactionStatus)CollectionUtil.Find(TransactionStatus.ALL, node.GetString("status"), TransactionStatus.UNRECOGNIZED); EscrowStatus = (TransactionEscrowStatus)CollectionUtil.Find( TransactionEscrowStatus.ALL, node.GetString("escrow-status"), TransactionEscrowStatus.UNRECOGNIZED ); List<NodeWrapper> statusNodes = node.GetList("status-history/status-event"); StatusHistory = new StatusEvent[statusNodes.Count]; for (int i = 0; i < statusNodes.Count; i++) { StatusHistory[i] = new StatusEvent(statusNodes[i]); } Type = (TransactionType)CollectionUtil.Find(TransactionType.ALL, node.GetString("type"), TransactionType.UNRECOGNIZED); MerchantAccountId = node.GetString("merchant-account-id"); ProcessorAuthorizationCode = node.GetString("processor-authorization-code"); ProcessorResponseCode = node.GetString("processor-response-code"); ProcessorResponseText = node.GetString("processor-response-text"); ProcessorSettlementResponseCode = node.GetString("processor-settlement-response-code"); ProcessorSettlementResponseText = node.GetString("processor-settlement-response-text"); AdditionalProcessorResponse = node.GetString("additional-processor-response"); VoiceReferralNumber = node.GetString("voice-referral-number"); PurchaseOrderNumber = node.GetString("purchase-order-number"); Recurring = node.GetBoolean("recurring"); RefundedTransactionId = node.GetString("refunded-transaction-id"); #pragma warning disable 0618 RefundId = node.GetString("refund-id"); #pragma warning restore 0618 RefundIds = node.GetStrings("refund-ids/*"); PartialSettlementTransactionIds = node.GetStrings("partial-settlement-transaction-ids/*"); AuthorizedTransactionId = node.GetString("authorized-transaction-id"); SettlementBatchId = node.GetString("settlement-batch-id"); PlanId = node.GetString("plan-id"); SubscriptionId = node.GetString("subscription-id"); TaxAmount = node.GetDecimal("tax-amount"); TaxExempt = node.GetBoolean("tax-exempt"); CustomFields = node.GetDictionary("custom-fields"); CreditCard = new CreditCard(node.GetNode("credit-card"), gateway); Subscription = new Subscription(node.GetNode("subscription"), gateway); Customer = new Customer(node.GetNode("customer"), gateway); CurrencyIsoCode = node.GetString("currency-iso-code"); CvvResponseCode = node.GetString("cvv-response-code"); Descriptor = new Descriptor(node.GetNode("descriptor")); ServiceFeeAmount = node.GetDecimal("service-fee-amount"); DisbursementDetails = new DisbursementDetails(node.GetNode("disbursement-details")); var paypalNode = node.GetNode("paypal"); if (paypalNode != null) { PayPalDetails = new PayPalDetails(paypalNode); } var coinbaseNode = node.GetNode("coinbase-account"); if (coinbaseNode != null) { CoinbaseDetails = new CoinbaseDetails(coinbaseNode); } var applePayNode = node.GetNode("apple-pay"); if (applePayNode != null) { ApplePayDetails = new ApplePayDetails(applePayNode); } var androidPayNode = node.GetNode("android-pay-card"); if (androidPayNode != null) { AndroidPayDetails = new AndroidPayDetails(androidPayNode); } BillingAddress = new Address(node.GetNode("billing")); ShippingAddress = new Address(node.GetNode("shipping")); CreatedAt = node.GetDateTime("created-at"); UpdatedAt = node.GetDateTime("updated-at"); AddOns = new List<AddOn>(); foreach (var addOnResponse in node.GetList("add-ons/add-on")) { AddOns.Add(new AddOn(addOnResponse)); } Discounts = new List<Discount>(); foreach (var discountResponse in node.GetList("discounts/discount")) { Discounts.Add(new Discount(discountResponse)); } Disputes = new List<Dispute>(); foreach (var dispute in node.GetList("disputes/dispute")) { Disputes.Add(new Dispute(dispute)); } var riskDataNode = node.GetNode("risk-data"); if (riskDataNode != null){ RiskData = new RiskData(riskDataNode); } var threeDSecureInfoNode = node.GetNode("three-d-secure-info"); if (threeDSecureInfoNode != null && !threeDSecureInfoNode.IsEmpty()){ ThreeDSecureInfo = new ThreeDSecureInfo(threeDSecureInfoNode); } }
[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()); }
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.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)); }
[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()); }