public IActionResult ExtendSubscriptionPaypal([FromBody] PaypalPaymentRequest paymentRequest) { Console.WriteLine(paymentRequest.paymentNonce); Braintree.TransactionRequest request = new Braintree.TransactionRequest() { PaymentMethodNonce = paymentRequest.paymentNonce, Amount = (decimal)(paymentRequest.amount) }; Braintree.Result <Braintree.Transaction> result = gateway.Transaction.Sale(request); if (result.IsSuccess()) { TransactionDto transaction = new TransactionDto(); transaction.Amount = (decimal)(paymentRequest.amount); transaction.Status = "succeeded"; transaction.CustomerId = 1; transaction.PaymentGatewayId = 2; transaction.PricingPackageId = paymentRequest.packageId; transaction.DateCreated = DateTime.Now; _transactionManipulation.SaveTransaction(transaction); SubscriptionDto subscription = _subscriptionManipulation.GetCustomerSubscription(1); subscription.SubscriptionExpirationDate = subscription.SubscriptionExpirationDate.AddMonths(1); _subscriptionManipulation.UpdateSubscription(subscription); return(Ok("Uspjesan placanje")); } else { return(BadRequest("Neuspjesna transakcija!")); } }
public string Pay(string json) { int?id = Token.Verify(ListenerRequest.Headers.Get("Authorization")); if (id.HasValue) { var payment = JsonConvert.DeserializeObject <BraintreeClient.PaymentRequest>(json); var request = new Braintree.TransactionRequest { Amount = payment.Amount, MerchantAccountId = "Sandbox_Project", PaymentMethodNonce = payment.Nonce, CustomerId = id.Value.ToString(), Options = new Braintree.TransactionOptionsRequest { SubmitForSettlement = true } }; Braintree.Result <Braintree.Transaction> result = BraintreeClient.gateway.Transaction.Sale(request); if (result.IsSuccess()) { StatusCode = 200; return("Successfully paid."); } else { StatusCode = 400; return("Error while paying"); } } else { StatusCode = 403; return("Invalid token/user ID"); } }
public async Task <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)); }
public ActionResult Payment(CheckOut model, int?id) { Basket b = new Basket(); using (EscapeRoomDBEntities entities = new EscapeRoomDBEntities()) { //create basket b = entities.Baskets.Single(x => x.ID == id); //if logged in, update record and add basket if (User.Identity.IsAuthenticated) { User user = entities.Users.Single(X => X.Email == User.Identity.Name); user.FirstName = model.FirstName; user.LastName = model.LastName; user.Email = model.Email; user.Phone = model.Phone; user.DateCreated = DateTime.UtcNow; b.User = user; entities.SaveChanges(); } //if no login, create user and add basket else { User user = new Models.User(); user.FirstName = model.FirstName; user.LastName = model.LastName; user.Email = model.Email; user.Phone = model.Phone; user.DateCreated = DateTime.UtcNow; b.User = user; entities.SaveChanges(); } } using (EscapeRoomDBEntities entities = new EscapeRoomDBEntities()) { b = entities.Baskets.Single(x => x.ID == id); model.numPlayers = b.Players.Count; model.session = new Models.Session { Id = b.Session.Id, Price = b.Session.Price, Title = b.Session.Title, Start = b.Session.Start }; model.Players = b.Players.ToArray(); } //configure braintree connection and take payment string clientID = ConfigurationManager.AppSettings["Braintree.ClientID"]; string privateKey = ConfigurationManager.AppSettings["Braintree.PrivateKey"]; string publicKey = ConfigurationManager.AppSettings["Braintree.PublicKey"]; Braintree.IBraintreeGateway gateway = new Braintree.BraintreeGateway(Braintree.Environment.SANDBOX, clientID, publicKey, privateKey); Braintree.TransactionRequest request = new Braintree.TransactionRequest { Amount = model.session.Price * model.numPlayers, PaymentMethodNonce = "fake-valid-nonce", Customer = new Braintree.CustomerRequest { FirstName = model.FirstName, LastName = model.LastName, Email = model.Email }, BillingAddress = new Braintree.AddressRequest { FirstName = model.FirstName, LastName = model.LastName, StreetAddress = model.Address, ExtendedAddress = model.Unit, Locality = model.City, Region = model.State, PostalCode = model.Zip.ToString(), CountryCodeAlpha2 = "US" }, Options = new Braintree.TransactionOptionsRequest { SubmitForSettlement = true, StoreInVault = true }, }; Braintree.Result <Braintree.Transaction> result = gateway.Transaction.Sale(request); if (result.IsSuccess()) { using (EscapeRoomDBEntities entities = new EscapeRoomDBEntities()) { Basket completedBasket = entities.Baskets.Single(x => x.ID == id); completedBasket.PurchaseDate = DateTime.UtcNow; entities.SaveChanges(); } return(RedirectToAction("Success", "Checkout", new { id = b.ID })); } else { string errorMessages = ""; foreach (Braintree.ValidationError error in result.Errors.DeepAll()) { errorMessages += "Error: " + (int)error.Code + " - " + error.Message + "\n"; } TempData["Flash"] = errorMessages; return(RedirectToAction("Payment", "Checkout", new { id = b.ID })); } }
public async Task <IActionResult> Index(CheckoutViewModel model, string braintreeNonce) { ViewData["clientToken"] = await _braintreeGateway.ClientToken.GenerateAsync(); if (string.IsNullOrEmpty(braintreeNonce)) { this.ModelState.AddModelError("nonce", "We're unable to validate this credit card"); } if (this.ModelState.IsValid) { HatUser hatUser = null; if (User.Identity.IsAuthenticated) { hatUser = _userManager.FindByNameAsync(User.Identity.Name).Result; } Cart cart = CartService.GetCart(_context, Request, Response, hatUser); if (cart.CartItems.Count > 0) { var orderId = Guid.NewGuid().ToString().Substring(0, 8); Braintree.TransactionRequest transactionRequest = new Braintree.TransactionRequest(); transactionRequest.PaymentMethodNonce = braintreeNonce; transactionRequest.PurchaseOrderNumber = orderId; transactionRequest.Amount = cart.CartItems.Sum(x => x.Quantity * x.Product.Price); transactionRequest.ShippingAddress = new Braintree.AddressRequest { StreetAddress = model.ShippingStreet1, ExtendedAddress = model.ShippingStreet2, PostalCode = model.ShippingPostalCode, //CountryName = model.ShippingCountry, //This thing is picky about casing FirstName = model.ContactName.Split(' ').First(), LastName = model.ContactName.Contains(' ') ? string.Join(' ', model.ContactName.Split(' ').Skip(1)) : "", Locality = model.ShippingCity, Region = model.ShippingRegion }; transactionRequest.Customer = new Braintree.CustomerRequest { Email = hatUser != null ? hatUser.Email : model.ContactEmail, }; transactionRequest.LineItems = cart.CartItems.Select(x => new Braintree.TransactionLineItemRequest { Name = x.Product.Name, Description = x.Product.Description, ProductCode = x.ProductID.ToString(), Quantity = x.Quantity, UnitAmount = x.Product.Price, TotalAmount = x.Product.Price * x.Quantity, LineItemKind = Braintree.TransactionLineItemKind.DEBIT }).ToArray(); Braintree.Result <Braintree.Transaction> transactionResult = _braintreeGateway.Transaction.Sale(transactionRequest); if (transactionResult.IsSuccess()) { //TODO: Get a lot more info here, validate credit card + address, save it to a database Order order = new Order(); order.ID = orderId; order.OrderDate = DateTime.Now.ToString(); order.ContactEmail = model.ContactEmail; order.ContactName = model.ContactName; order.ContactPhoneNumber = model.ContactPhoneNumber; order.ShippingCity = model.ShippingCity; order.ShippingCountry = model.ShippingCountry; order.ShippingPostalCode = model.ShippingPostalCode; order.ShippingRegion = model.ShippingRegion; order.ShippingStreet1 = model.ShippingStreet1; order.ShippingStreet2 = model.ShippingStreet2; order.OrderItems = cart.CartItems.Select(ci => new OrderItem { ProductID = ci.ProductID, Color = ci.ProductColor != null ? ci.ProductColor.Color : null, Description = ci.Product.Description, Name = ci.Product.Name, Price = ci.Product.Price, Quantity = ci.Quantity, Size = ci.ProductSize != null ? ci.ProductSize.Size : null }).ToArray(); _context.CartItems.RemoveRange(cart.CartItems); _context.Carts.Remove(cart); Response.Cookies.Delete("HatShopCartInfo"); _context.Orders.Add(order); if (hatUser != null) { order.HatUser = hatUser; } _context.SaveChanges(); await _emailSender.SendEmailAsync(model.ContactEmail, "Receipt for order #" + order.ID, "Thanks for your order!"); return(RedirectToAction("index", "receipt", new { id = order.ID })); } } ModelState.AddModelError("cart", "There was a problem processing your cart"); } return(View(model)); }