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

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


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

                return(Ok("Uspjesan placanje"));
            }
            else
            {
                return(BadRequest("Neuspjesna transakcija!"));
            }
        }
Ejemplo n.º 2
0
        public string Pay(string json)
        {
            int?id = Token.Verify(ListenerRequest.Headers.Get("Authorization"));

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

                Braintree.Result <Braintree.Transaction> result = BraintreeClient.gateway.Transaction.Sale(request);
                if (result.IsSuccess())
                {
                    StatusCode = 200;
                    return("Successfully paid.");
                }
                else
                {
                    StatusCode = 400;
                    return("Error while paying");
                }
            }
            else
            {
                StatusCode = 403;
                return("Invalid token/user ID");
            }
        }
Ejemplo n.º 3
0
        public async Task <ActionResult> Index(CheckoutModel model)
        {
            if (ModelState.IsValid)
            {
                using (AppStoreEntities entities = new AppStoreEntities())
                {
                    Order o = null;
                    if (User.Identity.IsAuthenticated)
                    {
                        AspNetUser currentUser = entities.AspNetUsers.Single(x => x.UserName == User.Identity.Name);
                        o = currentUser.Orders.FirstOrDefault(x => x.TimeCompleted == null);
                        if (o == null)
                        {
                            o             = new Order();
                            o.OrderNumber = Guid.NewGuid();
                            currentUser.Orders.Add(o);
                            entities.SaveChanges();
                        }
                    }
                    else
                    {
                        if (Request.Cookies.AllKeys.Contains("orderNumber"))
                        {
                            Guid orderNumber = Guid.Parse(Request.Cookies["orderNumber"].Value);
                            o = entities.Orders.FirstOrDefault(x => x.TimeCompleted == null && x.OrderNumber == orderNumber);
                        }
                        if (o == null)
                        {
                            o             = new Order();
                            o.OrderNumber = Guid.NewGuid();
                            entities.Orders.Add(o);
                            Response.Cookies.Add(new HttpCookie("orderNumber", o.OrderNumber.ToString()));
                            entities.SaveChanges();
                        }
                    }
                    if (o.OrdersProducts.Sum(x => x.Quantity) == 0)
                    {
                        return(RedirectToAction("Index", "Cart"));
                    }

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

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

                    entities.sp_CompleteOrder(o.ID);

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

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

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

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

                    newTransaction.CreditCard = creditCard;

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

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

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

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

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

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

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


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

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

                    o.TimeCompleted = DateTime.UtcNow;

                    entities.SaveChanges();
                }
                return(RedirectToAction("profile", "Home"));
            }
            return(View(model));
        }
Ejemplo n.º 4
0
        public ActionResult Payment(CheckOut model, int?id)
        {
            Basket b = new Basket();

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

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

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

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

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

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

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

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



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

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

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

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

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

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



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

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

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

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


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

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

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

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

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


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

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

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

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

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


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


                        await mail.SendAsync(new Microsoft.AspNet.Identity.IdentityMessage
                        {
                            Destination = model.CurrentBasket.Customer.AspNetUser.Email,
                            Subject     = "Order " + model.CurrentBasket.OId + " Completed",
                            Body        = "Order Body Here"
                        });
                    }
                    return(RedirectToAction("Index", "Receipt", new { id = model.CurrentBasket.OId }));
                }
                else
                {
                    ModelState.AddModelError("CreditCardNumber", "Unable to authorize this card number");
                }
            }
            return(View(model));
        }
Ejemplo n.º 7
0
        public async Task <IActionResult> Index(CheckoutViewModel model, string braintreeNonce)
        {
            ViewData["clientToken"] = await _braintreeGateway.ClientToken.GenerateAsync();

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

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

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

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


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

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

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

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