Exemplo n.º 1
0
        public ActionResult Charge(string stripeEmail, string stripeToken)
        {
            //string secretKey = ConfigurationManager.AppSettings["Stripe:secretKey"];
            string secretKey = "sk_test_e3ssfSIQhhvg7DtlMpHLxMKm";

            StripeConfiguration.SetApiKey(secretKey);

            Stripe.CustomerCreateOptions myCustomer = new Stripe.CustomerCreateOptions();
            myCustomer.Email  = stripeEmail;
            myCustomer.Source = stripeToken;
            var customerService = new Stripe.CustomerService();

            Stripe.Customer stripeCustomer = customerService.Create(myCustomer);

            var options = new Stripe.ChargeCreateOptions
            {
                Amount       = 1000,
                Currency     = "USD",
                Description  = "Buying 10 rubber ducks",
                Source       = stripeToken,
                ReceiptEmail = stripeEmail
            };
            //and Create Method of this object is doing the payment execution.
            var service = new Stripe.ChargeService();

            //Stripe.Charge charge = service.Create(options);

            return(RedirectToAction(nameof(Index)));
        }
        public IHttpActionResult Patch([FromODataUri] int key, Delta <Organization> patch)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var currentUser = CurrentUser();

            var organization = db.Organizations.Find(key);

            // Ensure that object was found
            if (organization == null)
            {
                return(NotFound());
            }

            // Ensure that user is authorized
            if (!currentUser.CanModifyOrganizationDetails ||
                currentUser.OrganizationId != key)
            {
                return(BadRequest());
            }

            // Peform the update
            patch.Patch(organization);

            // Update the Stripe payment source if it is provided
            if (patch.GetChangedPropertyNames().Contains("StripeSourceId"))
            {
                var customerService = new CustomerService();
                var sourceService   = new SourceService();

                // Attach the card source id to the customer
                var attachOptions = new SourceAttachOptions()
                {
                    Source = organization.StripeSourceId
                };
                sourceService.Attach(organization.StripeCustomerId, attachOptions);

                // Update the customer's default source
                var customerOptions = new CustomerUpdateOptions()
                {
                    DefaultSource = organization.StripeSourceId
                };
                Stripe.Customer customer = customerService.Update(organization.StripeCustomerId, customerOptions);

                var source = sourceService.Get(organization.StripeSourceId);

                // Record the card details
                organization.StripeSourceCardLast4           = source.Card.Last4;
                organization.StripeSourceCardBrand           = source.Card.Brand;
                organization.StripeSourceCardExpirationMonth = source.Card.ExpMonth.ToString();
                organization.StripeSourceCardExpirationYear  = source.Card.ExpYear.ToString();
            }

            db.SaveChanges();

            return(Updated(organization));
        }
        /// <summary>
        /// Adds a new customer with account id
        /// </summary>
        /// <param name="id"></param>
        /// <param name="email"></param>
        /// <param name="firstName"></param>
        /// <param name="lastName"></param>
        /// <returns></returns>
        public async Task <dynamic> PostCustomer(string id, string email, string firstName, string lastName)
        {
            try
            {
                StripeConfiguration.ApiKey = key;

                var options = new CustomerCreateOptions
                {
                    Email    = email,
                    Name     = firstName + " " + lastName,
                    Metadata = new Dictionary <string, string>
                    {
                        { "UserId", id },
                    }
                };
                var             service  = new CustomerService();
                Stripe.Customer customer = await service.CreateAsync(options);

                return(customer);
            }
            catch (Exception)
            {
                throw;
            }
        }
Exemplo n.º 4
0
        public void SetCard(string customerId, string number, int month, int year, string cvc)
        {
            Stripe.TokenService tokenService = new Stripe.TokenService();
            var options = new Stripe.TokenCreateOptions()
            {
                Card = new CreditCardOptions()
                {
                    Number   = number,
                    ExpMonth = month,
                    ExpYear  = year,
                    Cvc      = cvc
                }
            };

            Stripe.Token token = tokenService.Create(options);

            var customerOptions = new CustomerUpdateOptions()
            {
                SourceToken = token.Id
            };

            var customerService = new CustomerService();

            Stripe.Customer customer = customerService.Update(customerId, customerOptions);
        }
Exemplo n.º 5
0
        public Stripe.Customer GetCustomer(string customerId)
        {
            var customerService = new Stripe.CustomerService(PrivateKey);

            Stripe.Customer stripeCustomer = customerService.Get(customerId);

            return(stripeCustomer);
        }
        public IActionResult Payment(string stripeToken)
        {
            // retriever order from session
            var order = HttpContext.Session.GetObject <Models.Order>("Order");

            // 1. create Stripe customer
            var customerService = new Stripe.CustomerService();
            var charges         = new Stripe.ChargeService();

            StripeConfiguration.ApiKey = _iconfiguration["Stripe:SecretKey"];
            Stripe.Customer customer = customerService.Create(new Stripe.CustomerCreateOptions
            {
                Source = stripeToken,
                Email  = User.Identity.Name
            });

            // 2. create Stripe charge
            var charge = charges.Create(new Stripe.ChargeCreateOptions
            {
                Amount      = Convert.ToInt32(order.Total * 100),
                Description = "COMP2084 Beer Store Purchase",
                Currency    = "cad",
                Customer    = customer.Id
            });

            // 3. save a new order to our db
            _context.Orders.Add(order);
            _context.SaveChanges();

            // 4. save the cart items as new OrderDetails to our db
            var cartItems = _context.Carts.Where(c => c.CustomerId == HttpContext.Session.GetString("CartUsername"));

            foreach (var item in cartItems)
            {
                var orderDetail = new OrderDetail
                {
                    OrderId   = order.Id,
                    ProductId = item.ProductId,
                    Quantity  = item.Quantity,
                    Cost      = item.Price
                };

                _context.OrderDetails.Add(orderDetail);
            }

            _context.SaveChanges();

            // 5. delete the cart items from this order
            foreach (var item in cartItems)
            {
                _context.Carts.Remove(item);
            }

            _context.SaveChanges();

            // 6. load an order confirmation page
            return(RedirectToAction("Details", "Orders", new { @id = order.Id }));
        }
Exemplo n.º 7
0
        public IActionResult Payment(string stripeEmail, string stripeToken)
        {
            //get secret key from configuration and pass to stripe API
            StripeConfiguration.ApiKey = _iconfiguration.GetSection("Stripe")["SecretKey"];
            var cartUsername = User.Identity.Name;
            var cartItems    = _context.Carts.Where(c => c.Username == cartUsername).ToList();
            var order        = HttpContext.Session.GetObject <Orders>("Order");

            //invoke stripe payment attempt
            var customerService = new Stripe.CustomerService();
            var charges         = new Stripe.ChargeService();

            Stripe.Customer customer = customerService.Create(new Stripe.CustomerCreateOptions
            {
                Source = stripeToken,
                Email  = stripeEmail
            });

            var charge = charges.Create(new Stripe.ChargeCreateOptions
            {
                Amount      = Convert.ToInt32(order.Total * 100),
                Description = "Sample Charge",
                Currency    = "cad",
                Customer    = customer.Id
            });

            //save the order
            _context.Orders.Add(order);
            _context.SaveChanges();

            //save the order details
            foreach (var item in cartItems)
            {
                var orderDetail = new OrderDetails
                {
                    OrderId   = order.OrderId,
                    ProductId = item.ProductId,
                    Quantity  = item.Quantity,
                    Price     = item.Price
                };

                _context.OrderDetails.Add(orderDetail);
            }

            _context.SaveChanges();

            //empty the cart
            foreach (var item in cartItems)
            {
                _context.Carts.Remove(item);
            }

            _context.SaveChanges();


            return(RedirectToAction("Details", "Orders", new { id = order.OrderId }));
        }
        /// <summary>
        /// Creates a payment. Creates new customer or adds payment to existing customer
        /// </summary>
        /// <param name="id"></param>
        /// <param name="email"></param>
        /// <param name="firstName"></param>
        /// <param name="lastName"></param>
        /// <param name="cardnumber"></param>
        /// <param name="month"></param>
        /// <param name="year"></param>
        /// <param name="cvc"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public async Task <dynamic> PayByCreditCard(string id, string email, string firstName, string lastName, string cardnumber, int month, int year, string cvc, int value)
        {
            try
            {
                StripeConfiguration.ApiKey = key;
                Models.Customer customer = await context.customers.Where(c => c.accountId == id).FirstOrDefaultAsync();

                Stripe.Customer paymentCustomer = new Stripe.Customer();

                //create new customer if it doesn't exists
                if (customer == null)
                {
                    paymentCustomer = await PostCustomer(id, email, firstName, lastName);

                    customer            = new Models.Customer();
                    customer.accountId  = id;
                    customer.customerId = paymentCustomer.Id;
                    await context.customers.AddAsync(customer);

                    context.SaveChanges();
                }

                //setup token options
                TokenCreateOptions optionstoken = new TokenCreateOptions
                {
                    Card = new TokenCardOptions
                    {
                        Number   = cardnumber,
                        ExpMonth = month,
                        ExpYear  = year,
                        Cvc      = cvc
                    }
                };

                TokenService tokenService = new TokenService();
                Token        token        = await tokenService.CreateAsync(optionstoken);

                //setup payment options
                ChargeCreateOptions options = new ChargeCreateOptions
                {
                    Amount      = value,
                    Currency    = "eur",
                    Description = "Parking spot reservation. Date: " + DateTime.Now.ToString("dd/MM/yyyy HH:mm"),
                    Source      = token.Id,
                    Customer    = customer.customerId
                };

                ChargeService service = new ChargeService();
                Charge        charge  = await service.CreateAsync(options);

                return(charge.Paid);
            }
            catch (Exception)
            {
                throw;
            }
        }
Exemplo n.º 9
0
        async public Task <string> CreateCustomer(Users user)
        {
            CustomerCreateOptions customerOpts = new CustomerCreateOptions
            {
                Email = user.Email
            };

            Stripe.CustomerService customerService = new Stripe.CustomerService();
            Stripe.Customer        newCustomer     = await customerService.CreateAsync(customerOpts);

            return(newCustomer.Id);
        }
Exemplo n.º 10
0
        public static stripe.Customer GetOrCreateCustomer(this stripe.CustomerService customerService, Core.Domain.Customers.Customer customer, IGenericAttributeService genericAttributeService, StripePaymentSettings paymentSettings)
        {
            string stripeCustomerId = genericAttributeService.GetAttribute <string>(customer, paymentSettings.GetCustomerIdKey());

            stripe.Customer result = customerService.GetOrCreateCustomer(customer, stripeCustomerId, paymentSettings);

            if (string.IsNullOrEmpty(stripeCustomerId))
            {
                genericAttributeService.SaveAttribute(customer, paymentSettings.GetCustomerIdKey(), result.Id);
            }

            return(result);
        }
        /// <summary>
        /// IDeal payment
        /// </summary>
        /// <param name="id"></param>
        /// <param name="email"></param>
        /// <param name="firstName"></param>
        /// <param name="lastName"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public async Task <dynamic> PayByIDeal(string id, string email, string firstName, string lastName, int value)
        {
            try
            {
                StripeConfiguration.ApiKey = key;

                Models.Customer customer = await context.customers.Where(c => c.accountId == id).FirstOrDefaultAsync();

                Stripe.Customer paymentCustomer = new Stripe.Customer();

                //create new customer if it doesn't exists
                if (customer == null)
                {
                    paymentCustomer = await PostCustomer(id, email, firstName, lastName);

                    customer            = new Models.Customer();
                    customer.accountId  = id;
                    customer.customerId = paymentCustomer.Id;
                    await context.customers.AddAsync(customer);

                    context.SaveChanges();
                }

                DateTime     currentTime   = DateTime.Now;
                TimeZoneInfo timeZone      = TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time");
                DateTime     convertedTime = TimeZoneInfo.ConvertTime(currentTime, timeZone);

                //setup payment options
                var options = new PaymentIntentCreateOptions
                {
                    Amount             = value,
                    Currency           = "eur",
                    Customer           = customer.customerId,
                    Description        = "Parking spot reservation. Date: " + convertedTime.ToString("dd/MM/yyyy HH:mm"),
                    PaymentMethodTypes = new List <string>
                    {
                        "ideal",
                    },
                };

                var service = new PaymentIntentService();
                var intent  = service.Create(options);

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Exemplo n.º 12
0
        public async Task <IActionResult> CreateCustomerAsync()
        {
            PayModel paymodel = getPayModel();
            var      options  = new CustomerCreateOptions
            {
                Source = this.Token().Id,
                Name   = paymodel.Name,
                Email  = paymodel.Email,
                Phone  = paymodel.Phone
            };

            var      service  = new CustomerService();
            Customer customer = await service.CreateAsync(options);

            var response = await Task.FromResult(customer);

            return(Ok(response));
        }
Exemplo n.º 13
0
        public ActionResult SetUpStripe(CardInfo cardInfo)  // Create customer then create charge in next view
        {
            Models.Customer currentCustomer = GetLoggedInCustomer();
            Models.Order    currentOrder    = db.Orders.FirstOrDefault(o => o.OrderId == currentCustomer.CurrentOrderId);
            CardInfo        newCard         = new CardInfo();

            newCard.CardName   = cardInfo.CardName;
            newCard.Email      = cardInfo.Email;
            newCard.CustomerId = currentCustomer.CustomerId;
            db.Cards.Add(newCard);

            StripeConfiguration.ApiKey = (APIKeys.StripeApiKey);

            var options = new CustomerCreateOptions
            {
                Description = ("Customer for " + cardInfo.Email),
                Email       = cardInfo.Email,
                Source      = cardInfo.StripeToken
            };
            var service = new CustomerService();

            Stripe.Customer customer = service.Create(options);
            currentCustomer.CustomerStripeId = customer.Id;
            currentCustomer.IsStripeSetUp    = true;
            db.SaveChanges();

            var createOptions = new ChargeCreateOptions
            {
                Amount      = Convert.ToInt64(currentOrder.OrderPrice * 100),
                Currency    = "usd",
                Customer    = currentCustomer.CustomerStripeId, // Have to pass in customer ID since token can't be called twice
                Description = "Order for " + currentCustomer.FirstName + " " + currentCustomer.lastName,
            };
            var    createService = new ChargeService();
            Charge charge        = createService.Create(createOptions);

            var model = new Cart(); //Cart is like the charge view model from video

            model.ChargeId = charge.Id;

            // Perhaps payment will happen with this setup for the first time

            return(RedirectToAction("UniqueIdScreen")); // This redirect may have to change
        }
Exemplo n.º 14
0
        public bool CreateCreditCard(CreaditCardCreateViewModel model)
        {
            StripeConfiguration.SetApiKey(SETTING.Value.SecretStripe);


            var customerTMP = _customerRepository.Get(x => x.Deleted == false && x.Id == model.CustomerId);

            if (customerTMP.StripeId == null || customerTMP.StripeId == "")
            {
                var options = new CustomerCreateOptions
                {
                    Email       = customerTMP.Email,
                    Description = "Customer for " + customerTMP.FullName + " " + customerTMP.Email,
                    SourceToken = model.CardId
                };
                var             service  = new Stripe.CustomerService();
                Stripe.Customer customer = service.Create(options);
                customerTMP.StripeId = customer.Id;
                _customerRepository.Update(customerTMP);
                model.CardId    = customer.DefaultSourceId;
                model.Isdefault = true;
            }
            else
            {
                var optionsCard = new CardCreateOptions
                {
                    SourceToken = model.CardId
                };
                var serviceCard = new Stripe.CardService();
                var card        = serviceCard.Create(customerTMP.StripeId, optionsCard);
                model.CardId = card.Id;
            }
            model.Last4DigitsHash = encrypt(model.Last4DigitsHash);
            var creditCard = _mapper.Map <CreaditCardCreateViewModel, CreditCard>(model);

            _creditCardRepository.Add(creditCard);
            _unitOfWork.CommitChanges();
            return(true);
        }
        /// <summary>
        /// Gets a customer with account id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task <dynamic> GetCustomer(string id)
        {
            try
            {
                Models.Customer customer = await context.customers.Where(c => c.accountId == id).FirstOrDefaultAsync();

                if (customer == null)
                {
                    return(null);
                }

                var service = new CustomerService();

                Stripe.Customer stripeCustomer = await service.GetAsync(customer.customerId);

                return(stripeCustomer);
            }
            catch (Exception)
            {
                return(null);
            }
        }
Exemplo n.º 16
0
        public static Charge RequestCharge(Transactions transactionModel, decimal payAmount, string description, bool isCapture = true)
        {
            // Set your secret key: remember to change this to your live secret key in production
            // See your keys here: https://dashboard.stripe.com/account/apikeys
            StripeConfiguration.SetApiKey(SecretKey);

            // Create a Customer:
            var customerOptions = new CustomerCreateOptions
            {
                SourceToken = transactionModel.PaymentCardToken,
                //Email = "*****@*****.**",
            };
            var customerService = new Stripe.CustomerService();

            Stripe.Customer customer = customerService.Create(customerOptions);

            string PaidAmountString = ConvertDecimalAmountToZeroDecimal(payAmount);

            var options = new ChargeCreateOptions
            {
                Amount   = Convert.ToInt64(PaidAmountString),
                Currency = transactionModel.Currency,
                //SourceId = transactionModel.PaymentCardToken,
                Description = description,
                //ReceiptEmail = "*****@*****.**",
                CustomerId = customer.Id,
                Capture    = isCapture,
                Metadata   = new Dictionary <string, string>()
                {
                    { "order_id", transactionModel.OrderId },
                }
            };
            var    service = new ChargeService();
            Charge charge  = service.Create(options);

            return(charge);
        }
Exemplo n.º 17
0
        public ViewResult makePayment(PaymentInformation cardInfo)
        {
            try
            {
                Stripe.StripeConfiguration.SetApiKey("sk_test_51HqI05B1UsJ4lZg1agboQSE7i0fWn98619xc2FP5NhREH4igqo1AlKTQO8VWMfsQBUs1OlXNBzBkOqORRQP6ZlPf00E2l0QVhL");


                //Create Card Object to create Token
                Stripe.CreditCardOptions card = new Stripe.CreditCardOptions();
                card.Name     = cardInfo.CardOwnerFirstName + " " + cardInfo.CardOwnerLastName;
                card.Number   = cardInfo.CardNumber;
                card.ExpYear  = cardInfo.ExpirationYear;
                card.ExpMonth = cardInfo.ExpirationMonth;
                card.Cvc      = cardInfo.CVV2;

                //Assign Card to Token Object and create Token
                Stripe.TokenCreateOptions token = new Stripe.TokenCreateOptions();
                token.Card = card;
                Stripe.TokenService serviceToken = new Stripe.TokenService();
                Stripe.Token        newToken     = serviceToken.Create(token);

                Stripe.CustomerCreateOptions myCustomer = new Stripe.CustomerCreateOptions();
                myCustomer.Email       = cardInfo.Buyer_Email;
                myCustomer.SourceToken = newToken.Id;
                var             customerService = new Stripe.CustomerService();
                Stripe.Customer stripeCustomer  = customerService.Create(myCustomer);

                //Create Charge Object with details of Charge
                var options = new Stripe.ChargeCreateOptions
                {
                    Amount       = Convert.ToInt32(cardInfo.Amount),
                    Currency     = "USD",
                    ReceiptEmail = cardInfo.Buyer_Email,
                    CustomerId   = stripeCustomer.Id,
                };
                //and Create Method of this object is doing the payment execution.
                var           service = new Stripe.ChargeService();
                Stripe.Charge charge  = service.Create(options); // This will do the Payment


                return(View("Thanks"));
            }
            catch (StripeException e)
            {
                switch (e.StripeError.ErrorType)
                {
                case "card_error":
                    //error = ("Code: " + e.StripeError.Code + "; ");
                    error = (" Error Message: " + e.StripeError.Message);
                    break;

                case "api_connection_error":
                    break;

                case "api_error":
                    break;

                case "authentication_error":
                    break;

                case "invalid_request_error":
                    break;

                case "rate_limit_error":
                    break;

                case "validation_error":
                    break;

                default:
                    // Unknown Error Type
                    break;
                }
                ViewBag.Greeting = error;
                return(View("Error"));
            }
        }
Exemplo n.º 18
0
        public User Register(User user, Organization organization)
        {
            using (var transaction = db.Database.BeginTransaction())
            {
                try
                {
                    // Ensure Email address is unique
                    var duplicate = db.Users.Where(u => u.EmailAddress.ToLower().Equals(user.EmailAddress.ToLower()));
                    if (duplicate.Any())
                    {
                        throw new DuplicateException("Email Address is already taken");
                    }

                    // Generates a password hash and salt
                    var service = new SecurityService();
                    user.PasswordSalt = service.GenerateHash(service.GenerateRandomString());
                    user.PasswordHash = service.GenerateHash(string.Format("{0} {1}", user.Password, user.PasswordSalt));
                    user.Password     = null;

                    // Formatting
                    user.EmailAddress = user.EmailAddress.ToLower();

                    // Auto-generated
                    user.Role                          = "Administrator";
                    user.CreatedAt                     = DateTime.UtcNow;
                    user.AllowedPhoneNumbers           = "*";
                    organization.CreatedAt             = DateTime.UtcNow;
                    organization.MinutesFormat         = "minutes";
                    organization.ShowCustomerNumber    = true;
                    organization.ShowProjectNumber     = true;
                    organization.ShowTaskNumber        = true;
                    organization.SortCustomersByColumn = "Number";
                    organization.SortProjectsByColumn  = "Number";
                    organization.SortTasksByColumn     = "Number";

#if DEBUG
                    organization.StripeCustomerId     = string.Format("RANDOM{0}", new SecurityService().GenerateRandomString());
                    organization.StripeSubscriptionId = string.Format("RANDOM{0}", new SecurityService().GenerateRandomString());
#endif

                    // Determine the actual Stripe Plan Id based on the PlanId
                    var stripePlanId = ConfigurationManager.AppSettings["StripePlanId1"].ToString(); // Default plan is the contractor plan
                    switch (organization.PlanId)
                    {
                    case 1:
                        stripePlanId = ConfigurationManager.AppSettings["StripePlanId1"].ToString();
                        break;

                    case 2:
                        stripePlanId = ConfigurationManager.AppSettings["StripePlanId2"].ToString();
                        break;

                    case 3:
                        stripePlanId = ConfigurationManager.AppSettings["StripePlanId3"].ToString();
                        break;

                    case 4:
                        stripePlanId = ConfigurationManager.AppSettings["StripePlanId4"].ToString();
                        break;
                    }

#if !DEBUG
                    try
                    {
                        // Create a Stripe customer object and save the customer id
                        var customerOptions = new CustomerCreateOptions
                        {
                            Email = user.EmailAddress
                        };
                        var             customers = new CustomerService();
                        Stripe.Customer customer  = customers.Create(customerOptions);
                        organization.StripeCustomerId = customer.Id;

                        // Subscribe the customer to the price and save the subscription id
                        var subscriptionOptions = new SubscriptionCreateOptions
                        {
                            Customer = customer.Id, // ex. cus_IDjvN9UsoFp2mk
                            Items    = new List <SubscriptionItemOptions>
                            {
                                new SubscriptionItemOptions
                                {
                                    Price = stripePlanId // ex. price_1Hd5PvLI44a19MHX9w5EGD4r
                                }
                            },
                            TrialFromPlan = true
                        };
                        var          subscriptions = new SubscriptionService();
                        Subscription subscription  = subscriptions.Create(subscriptionOptions);

                        organization.StripeSubscriptionId = subscription.Id;

                        // Send Welcome Email
                        var apiKey   = ConfigurationManager.AppSettings["SendGridApiKey"].ToString();
                        var client   = new SendGridClient(apiKey);
                        var from     = new EmailAddress("BRIZBEE <*****@*****.**>");
                        var to       = new EmailAddress(user.EmailAddress);
                        var msg      = MailHelper.CreateSingleTemplateEmail(from, to, "d-8c48a9ad2ddd4d73b6e6c10307182f43", null);
                        var response = client.SendEmailAsync(msg);
                    }
                    catch (Exception ex)
                    {
                        Trace.TraceWarning(ex.ToString());
                        throw;
                    }
#endif

                    // Save the organization and user
                    db.Organizations.Add(organization);
                    user.OrganizationId = organization.Id;

                    db.Users.Add(user);

                    db.SaveChanges();

                    transaction.Commit();

                    return(user);
                }
                catch (Exception ex)
                {
                    Trace.TraceWarning(ex.ToString());
                    transaction.Rollback();
                    throw;
                }
            }
        }
Exemplo n.º 19
0
        public ActionResult Charge(StripeChargeModel model)
        { //    4242424242424242
            string errormessage  = "";
            bool   isvalidemail  = false;
            bool   isvalidamount = false;
            HttpResponseMessage responseMessage = new HttpResponseMessage();

            try
            {
                var  addr       = new System.Net.Mail.MailAddress(model.Email);
                bool emailvalid = (addr.Address == model.Email);
                isvalidemail = true;
            }
            catch
            {
                errormessage += "invalid email\r\n";
                isvalidemail  = false;
            }

            if (model.Amount == 0)
            {
                isvalidamount = false;
                errormessage += "invalid amount\r\n";
            }
            else
            {
                isvalidamount = true;
            }



            if (isvalidamount == true && isvalidemail == true)
            {
                try
                {
                    string Name            = model.CardHolderName;
                    string CardNumber      = model.CardNum;
                    long   ExpirationYear  = long.Parse(model.Expyear);
                    long   ExpirationMonth = long.Parse(model.ExpMonth);
                    string CVV2            = model.CVV;
                    string Buyer_Email     = model.Email;
                    int    amount          = (int)model.Amount;


                    Stripe.StripeConfiguration.SetApiKey("sk_test_KVelkjylnQQPOkrHSSu8gCft00dODAP1ie");

                    Stripe.CreditCardOptions card = new Stripe.CreditCardOptions();

                    card.Name = Name;

                    card.Number = CardNumber;

                    card.ExpYear = ExpirationYear;

                    card.ExpMonth       = ExpirationMonth;
                    card.AddressLine1   = model.AddressLine1;
                    card.AddressLine2   = model.AddressLine2;
                    card.AddressState   = model.AddressCity;
                    card.AddressCountry = model.AddressCountry;
                    card.AddressZip     = model.AddressPostcode;
                    card.Cvc            = CVV2;

                    // set card to token object and create token

                    Stripe.TokenCreateOptions tokenCreateOption = new Stripe.TokenCreateOptions();

                    tokenCreateOption.Card = card;

                    Stripe.TokenService tokenService = new Stripe.TokenService();

                    Stripe.Token token = tokenService.Create(tokenCreateOption);

                    //create customer object then register customer on Stripe

                    Stripe.CustomerCreateOptions customer = new Stripe.CustomerCreateOptions();

                    customer.Email = Buyer_Email;

                    var custService = new Stripe.CustomerService();

                    Stripe.Customer stpCustomer = custService.Create(customer);
                    //create credit card charge object with details of charge

                    var options = new Stripe.ChargeCreateOptions
                    {
                        Amount = (int)(amount * 100),

                        //                    Amount = (int)(model.Amount * 100),
                        //                    Currency = "gbp",
                        //                    Description = "Description for test charge",
                        //                    Source = model.Token
                        Currency = "gbp",

                        ReceiptEmail = Buyer_Email,

                        Source      = model.Token,
                        Description = "Description for test charge"
                    };

                    //and Create Method of this object is doing the payment execution.

                    var service = new Stripe.ChargeService();

                    Stripe.Charge charge = service.Create(options); // This will do the Payment            }
                    return(new HttpStatusCodeResult(HttpStatusCode.OK, "Success"));
                }
                catch
                {
                    return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, "error :  " + errormessage));
                }
            }
            else
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, "error :  " + errormessage));
            }
        }
        public PaymentView(DateTime bookingDate, string centerName, string sportName, string courtName, string startingBookingTime, string endingBookingTime, double TotalPaymentAmount)
        {
            InitializeComponent();

            //startingBookingTime AND endingBookingTime  are TimeSpan not DateTime  ...... Done


            var uname = Preferences.Get("UserName", String.Empty);

            if (String.IsNullOrEmpty(uname))
            {
                username.Text = "Guest";
            }
            else
            {
                username.Text = uname;
            }

            centername.Text = centerName;

            courtname.Text = courtName;


            //bookingdate.Text = bookingDate.Date.ToString();
            cvm = new PaymentViewModel(bookingDate);
            this.BindingContext = cvm;

            bookingtime.Text = startingBookingTime.ToString() + " - " + endingBookingTime.ToString();

            double RoundedTotalPaymentAmount = Math.Round(TotalPaymentAmount, 1, MidpointRounding.ToEven);

            totalpaymentamount.Text = "RM " + RoundedTotalPaymentAmount.ToString();

            string totalp = totalpaymentamount.Text;

            DateTime s = Convert.ToDateTime(startingBookingTime);
            DateTime d = Convert.ToDateTime(endingBookingTime);


            NewEventHandler.Clicked += async(sender, args) =>
            {
                // if check payment from Moustafa is true, then add booking to firebase
                try
                {
                    //StripeConfiguration.SetApiKey("sk_test_51IpayhGP2IgUXM55te5JbGRu14MOp6AU6GORVFhqpOilEOp96ERDzKCi1VN9rDLrOmOEwNPqgOvQuIyaNg8YKfkL00Qoq8a7QX");
                    StripeConfiguration.SetApiKey("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");


                    //This are the sample test data use MVVM bindings to send data to the ViewModel

                    Stripe.TokenCardOptions stripcard = new Stripe.TokenCardOptions();

                    stripcard.Number   = cardnumber.Text;
                    stripcard.ExpYear  = Int64.Parse(expiryYear.Text);
                    stripcard.ExpMonth = Int64.Parse(expirymonth.Text);
                    stripcard.Cvc      = cvv.Text;
                    //stripcard.Cvc = Int64.Parse(cvv.Text);



                    //Step 1 : Assign Card to Token Object and create Token

                    Stripe.TokenCreateOptions token = new Stripe.TokenCreateOptions();
                    token.Card = stripcard;
                    Stripe.TokenService serviceToken = new Stripe.TokenService();
                    Stripe.Token        newToken     = serviceToken.Create(token);

                    // Step 2 : Assign Token to the Source

                    var options = new SourceCreateOptions
                    {
                        Type     = SourceType.Card,
                        Currency = "myr",
                        Token    = newToken.Id
                    };

                    var    service = new SourceService();
                    Source source  = service.Create(options);

                    //Step 3 : Now generate the customer who is doing the payment

                    Stripe.CustomerCreateOptions myCustomer = new Stripe.CustomerCreateOptions()
                    {
                        Name        = "Moustafa",
                        Email       = "*****@*****.**",
                        Description = "Customer for [email protected]",
                    };

                    var             customerService = new Stripe.CustomerService();
                    Stripe.Customer stripeCustomer  = customerService.Create(myCustomer);

                    mycustomer = stripeCustomer.Id; // Not needed

                    //Step 4 : Now Create Charge Options for the customer.

                    var chargeoptions = new Stripe.ChargeCreateOptions
                    {
                        //Amount = (Int64.Parse(RoundedTotalPaymentAmount)) * 100,
                        //(int(RoundedTotalPaymentAmount))
                        //Amount = Convert.ToInt32(RoundedTotalPaymentAmount) * 100,
                        //Amount = (long?)(double.Parse(RoundedTotalPaymentAmount) * 100),
                        Amount       = (long?)(double.Parse(totalp) * 100),
                        Currency     = "MYR",
                        ReceiptEmail = "*****@*****.**",
                        Customer     = stripeCustomer.Id,
                        Source       = source.Id
                    };

                    //Step 5 : Perform the payment by  Charging the customer with the payment.
                    var           service1 = new Stripe.ChargeService();
                    Stripe.Charge charge   = service1.Create(chargeoptions); // This will do the Payment


                    getchargedID = charge.Id; // Not needed
                }
                catch (Exception ex)
                {
                    UserDialogs.Instance.Alert(ex.Message, null, "ok");
                    Console.Write("error" + ex.Message);

                    //await Application.Current.MainPage.DisplayAlert("error ", ex.Message, "OK");
                }
                finally
                {
                    //if (getchargedID != null)
                    if (getchargedID != null)
                    {
                        var acd = new AddBookingData(sportName, courtName, username.Text, centerName, s, d, bookingDate, RoundedTotalPaymentAmount);
                        await acd.AddBookingDataAsync();


                        UserDialogs.Instance.Alert("Payment Successed", "Success", "Ok");
                        Xamarin.Forms.Application.Current.MainPage = new MainTabbedView();
                        //await Application.Current.MainPage.DisplayAlert("Payment Successed ", "Success", "OK");
                    }
                    else
                    {
                        UserDialogs.Instance.Alert("Something Wrong", "Faild", "OK");
                        //await Application.Current.MainPage.DisplayAlert("Payment Error ", "faild", "OK");
                    }
                }



                /*
                 * var acd = new AddBookingData(sportName, courtName, username.Text, centerName, s, d, bookingDate, RoundedTotalPaymentAmount);
                 * await acd.AddBookingDataAsync();
                 * /*
                 *
                 *
                 * //Application.Current.MainPage = new MainTabbedView();
                 *
                 * //await Navigation.PopModalAsync();
                 * //await Navigation.PopToRootAsync();
                 * /*
                 * Navigation.InsertPageBefore(new NewPage(), Navigation.NavigationStack[0]);
                 * await Navigation.PopToRootAsync();
                 */
            };

            /*
             * public void GetCustomerInformationID(object sender, EventArgs e)
             * {
             *  var service = new CustomerService();
             *  var customer = service.Get(mycustomer);
             *  var serializedCustomer = JsonConvert.SerializeObject(customer);
             *  //  var UserDetails = JsonConvert.DeserializeObject<CustomerRetriveModel>(serializedCustomer);
             *
             * }
             *
             *
             * public void GetAllCustomerInformation(object sender, EventArgs e)
             * {
             *  var service = new CustomerService();
             *  var options = new CustomerListOptions
             *  {
             *      Limit = 3,
             *  };
             *  var customers = service.List(options);
             *  var serializedCustomer = JsonConvert.SerializeObject(customers);
             * }
             *
             *
             * public void GetRefundForSpecificTransaction(object sender, EventArgs e)
             * {
             *  var refundService = new RefundService();
             *  var refundOptions = new RefundCreateOptions
             *  {
             *      Charge = getchargedID,
             *  };
             *  Refund refund = refundService.Create(refundOptions);
             *  refundID = refund.Id;
             * }
             *
             *
             * public void GetRefundInformation(object sender, EventArgs e)
             * {
             *  var service = new RefundService();
             *  var refund = service.Get(refundID);
             *  var serializedCustomer = JsonConvert.SerializeObject(refund);
             *
             * }
             */

            /*
             *
             * async Task NewEventHandler(object sender, EventArgs e)
             * {
             *  // if check payment from Moustafa is true, then
             *
             *  // add booking to firebase
             *
             *  var acd = new AddBookingData(sportName, courtName, username.Text, centerName, s, d, bookingDate, TotalPaymentAmount);
             *  await acd.AddBookingDataAsync();
             * }
             */
        }
Exemplo n.º 21
0
        // PATCH: odata/Organizations(5)
        public IActionResult Patch([FromODataUri] int key, Delta <Organization> patch)
        {
            var currentUser = CurrentUser();

            var organization = _context.Organizations.Find(key);

            // Ensure that object was found
            if (organization == null)
            {
                return(NotFound());
            }

            // Ensure that user is authorized
            if (!currentUser.CanModifyOrganizationDetails ||
                currentUser.OrganizationId != key)
            {
                return(BadRequest());
            }

            // Do not allow modifying some properties.
            if (patch.GetChangedPropertyNames().Contains("StripeCustomerId") ||
                patch.GetChangedPropertyNames().Contains("StripeSourceCardBrand") ||
                patch.GetChangedPropertyNames().Contains("StripeSourceCardLast4") ||
                patch.GetChangedPropertyNames().Contains("StripeSourceCardExpirationMonth") ||
                patch.GetChangedPropertyNames().Contains("StripeSourceCardExpirationYear") ||
                patch.GetChangedPropertyNames().Contains("StripeSubscriptionId") ||
                patch.GetChangedPropertyNames().Contains("CreatedAt") ||
                patch.GetChangedPropertyNames().Contains("Id"))
            {
                return(BadRequest("Not authorized to modify CreatedAt, Id, StripeCustomerId, StripeSourceCardBrand, StripeSourceCardLast4, StripeSourceCardExpirationMonth, StripeSourceCardExpirationYear, or StripeSubscriptionId."));
            }

            // Peform the update
            patch.Patch(organization);

            // Validate the model.
            ModelState.ClearValidationState(nameof(organization));
            if (!TryValidateModel(organization, nameof(organization)))
            {
                return(BadRequest());
            }

            // Update the Stripe payment source if it is provided
            if (patch.GetChangedPropertyNames().Contains("StripeSourceId"))
            {
                var customerService = new CustomerService();
                var sourceService   = new SourceService();

                // Attach the card source id to the customer
                var attachOptions = new SourceAttachOptions()
                {
                    Source = organization.StripeSourceId
                };
                sourceService.Attach(organization.StripeCustomerId, attachOptions);

                // Update the customer's default source
                var customerOptions = new CustomerUpdateOptions()
                {
                    DefaultSource = organization.StripeSourceId
                };
                Stripe.Customer customer = customerService.Update(organization.StripeCustomerId, customerOptions);

                var source = sourceService.Get(organization.StripeSourceId);

                // Record the card details
                organization.StripeSourceCardLast4           = source.Card.Last4;
                organization.StripeSourceCardBrand           = source.Card.Brand;
                organization.StripeSourceCardExpirationMonth = source.Card.ExpMonth.ToString();
                organization.StripeSourceCardExpirationYear  = source.Card.ExpYear.ToString();
            }

            _context.SaveChanges();

            return(NoContent());
        }
Exemplo n.º 22
0
        public ViewResult makePayment(PaymentInformation cardInfo)
        {
            try
            {
                Stripe.StripeConfiguration.SetApiKey("sk_test_51HqI05B1UsJ4lZg1agboQSE7i0fWn98619xc2FP5NhREH4igqo1AlKTQO8VWMfsQBUs1OlXNBzBkOqORRQP6ZlPf00E2l0QVhL");



                Stripe.CreditCardOptions card = new Stripe.CreditCardOptions();
                card.Name     = cardInfo.CardOwnerFirstName + " " + cardInfo.CardOwnerLastName;
                card.Number   = cardInfo.CardNumber;
                card.ExpYear  = cardInfo.ExpirationYear;
                card.ExpMonth = cardInfo.ExpirationMonth;
                card.Cvc      = cardInfo.CVV2;

                Console.WriteLine(TotalPrice.ToString());


                Stripe.TokenCreateOptions token = new Stripe.TokenCreateOptions();
                token.Card = card;
                Stripe.TokenService serviceToken = new Stripe.TokenService();
                Stripe.Token        newToken     = serviceToken.Create(token);

                Stripe.CustomerCreateOptions myCustomer = new Stripe.CustomerCreateOptions();
                myCustomer.Email       = cardInfo.Buyer_Email;
                myCustomer.SourceToken = newToken.Id;
                var             customerService = new Stripe.CustomerService();
                Stripe.Customer stripeCustomer  = customerService.Create(myCustomer);

                var t = TempData["totalCost"];


                int    t1 = (int)Math.Round(Convert.ToDouble(t)) - 1;
                string total;
                string input_decimal_number = t.ToString();

                var regex = new System.Text.RegularExpressions.Regex("(?<=[\\.])[0-9]+");
                if (regex.IsMatch(input_decimal_number))
                {
                    string decimal_places = regex.Match(input_decimal_number).Value;
                    total = t1.ToString() + decimal_places;
                }
                else
                {
                    total = t1 + "00";
                }


                System.Diagnostics.Trace.WriteLine(t1.ToString());


                var options = new Stripe.ChargeCreateOptions
                {
                    Amount       = Convert.ToInt32(total),
                    Currency     = "USD",
                    ReceiptEmail = cardInfo.Buyer_Email,
                    CustomerId   = stripeCustomer.Id,
                };



                var           service = new Stripe.ChargeService();
                Stripe.Charge charge  = service.Create(options);


                return(View("Thanks"));
            }
            catch (StripeException e)
            {
                switch (e.StripeError.ErrorType)
                {
                case "card_error":

                    error = (" Error Message: " + e.StripeError.Message);
                    break;

                case "api_connection_error":
                    break;

                case "api_error":
                    break;

                case "authentication_error":
                    break;

                case "invalid_request_error":
                    break;

                case "rate_limit_error":
                    break;

                case "validation_error":
                    break;

                default:
                    // Unknown Error Type
                    break;
                }
                ViewBag.Greeting = error;
                return(View("Error"));
            }
        }
        private async void Button_Clicked(object sender, EventArgs e)
        {
            try
            {
                StripeConfiguration.SetApiKey("sk_test_51H7Lu7KJ3FKVwUnlPU8EUYuDPU0UMWNajFeHpVYzqwLkpKFRk9480iV54ZvAIPy4J0xYlKoN9IQaGMoyhhcaxOgl003Kz8FIdL");

                //This are the sample test data use MVVM bindings to send data to the ViewModel

                Stripe.CreditCardOptions stripcard = new Stripe.CreditCardOptions();
                stripcard.Number   = cardNumberEntry.Text;
                stripcard.ExpYear  = Convert.ToInt32(expiryDate.Text.Split('/')[1]);
                stripcard.ExpMonth = Convert.ToInt32(expiryDate.Text.Split('/')[0]);
                stripcard.Cvc      = cvvEntry.Text;


                //Step 1 : Assign Card to Token Object and create Token

                Stripe.TokenCreateOptions token = new Stripe.TokenCreateOptions();
                token.Card = stripcard;
                Stripe.TokenService serviceToken = new Stripe.TokenService();
                Stripe.Token        newToken     = serviceToken.Create(token);

                // Step 2 : Assign Token to the Source

                var options = new SourceCreateOptions
                {
                    Type     = SourceType.Card,
                    Currency = "usd",
                    Token    = newToken.Id
                };

                var    service = new SourceService();
                Source source  = service.Create(options);

                //Step 3 : Now generate the customer who is doing the payment

                Stripe.CustomerCreateOptions myCustomer = new Stripe.CustomerCreateOptions()
                {
                    Name        = nameEntry.Text,
                    Email       = emailEntry.Text,
                    Description = "Amare Payment",
                };

                var             customerService = new Stripe.CustomerService();
                Stripe.Customer stripeCustomer  = customerService.Create(myCustomer);

                mycustomer = stripeCustomer.Id; // Not needed

                //Step 4 : Now Create Charge Options for the customer.

                var chargeoptions = new Stripe.ChargeCreateOptions
                {
                    Amount       = 100,
                    Currency     = "USD",
                    ReceiptEmail = emailEntry.Text,
                    Customer     = stripeCustomer.Id,
                    Source       = source.Id
                };

                //Step 5 : Perform the payment by  Charging the customer with the payment.
                var           service1 = new Stripe.ChargeService();
                Stripe.Charge charge   = service1.Create(chargeoptions); // This will do the Payment

                getchargedID = charge.Id;                                // Not needed
                await DisplayAlert("Payment", "Payment Success", "Okay");

                await Navigation.PopAsync();
            }
            catch (Stripe.StripeException ex)
            {
                await DisplayAlert("Payment Error", ex.Message, "Okay");
            }
        }
Exemplo n.º 24
0
        public ActionResult CompleteCheckout(Cart cart, OrderDetails orderDetails)
        {
            StripeConfiguration.ApiKey = StripeKey.SecretKey;

            var customer = new Stripe.Customer
            {
                Name    = orderDetails.CustomerName,
                Email   = orderDetails.Email,
                Address = new Address
                {
                    Line1      = orderDetails.BillingAddressLine1,
                    Line2      = orderDetails.BillingAddressLine2,
                    City       = orderDetails.BillingCity,
                    State      = orderDetails.BillingState,
                    PostalCode = orderDetails.BillingPostalCode,
                    Country    = orderDetails.BillingCountry
                },
                Phone = orderDetails.CustomerPhone
            };

            if (orderDetails.ShippingAddressLine1 == null)
            {
                orderDetails.ShippingAddressLine1 = orderDetails.BillingAddressLine1;
            }
            if (orderDetails.ShippingAddressLine2 == null)
            {
                orderDetails.ShippingAddressLine2 = orderDetails.BillingAddressLine2;
            }
            if (orderDetails.ShippingCity == null)
            {
                orderDetails.ShippingCity = orderDetails.BillingCity;
            }
            if (orderDetails.ShippingState == null)
            {
                orderDetails.ShippingState = orderDetails.BillingState;
            }
            if (orderDetails.ShippingPostalCode == null)
            {
                orderDetails.ShippingPostalCode = orderDetails.BillingPostalCode;
            }
            if (orderDetails.ShippingCountry == null)
            {
                orderDetails.ShippingCountry = orderDetails.BillingCountry;
            }
            if (orderDetails.ShippingName == null)
            {
                orderDetails.ShippingName = orderDetails.CustomerName;
            }
            if (orderDetails.ShippingPhone == null)
            {
                orderDetails.ShippingPhone = orderDetails.CustomerPhone;
            }
            customer.Shipping = new Shipping
            {
                Address = new Address
                {
                    Line1      = orderDetails.BillingAddressLine1,
                    Line2      = orderDetails.BillingAddressLine2,
                    City       = orderDetails.BillingCity,
                    State      = orderDetails.BillingState,
                    PostalCode = orderDetails.BillingPostalCode,
                    Country    = orderDetails.BillingCountry
                },
                Name  = orderDetails.ShippingName,
                Phone = orderDetails.ShippingPhone
            };
            decimal taxRate = 0.0M;

            try
            {
                taxRate = _transactionManager.RetrieveTaxRateBySalesTaxDateAndZipCode(
                    orderDetails.ShippingPostalCode.Substring(0, 5), _transactionManager.RetrieveLatestSalesTaxDateByZipCode(
                        orderDetails.ShippingPostalCode.Substring(0, 5)));
            }
            catch (Exception)
            {
                taxRate = 0.0M;
            }
            orderDetails.TaxRate = taxRate;

            decimal subTotal = 0.0M;
            decimal total    = 0.0M;

            foreach (var line in cart.Lines)
            {
                if (line.Product.Taxable)
                {
                    subTotal += line.Product.Price * line.Amount;
                }
                else
                {
                    total += line.Product.Price * line.Amount;
                }
            }
            decimal tax = subTotal * taxRate;

            total += subTotal + tax;
            var options = new PaymentIntentCreateOptions
            {
                Customer           = customer.Id,
                Amount             = (int)(total * 100), // stripe totals are in pennies
                Currency           = "usd",
                PaymentMethodTypes = new List <string>
                {
                    "card"
                }
            };
            var           service = new PaymentIntentService();
            PaymentIntent intent  = null;

            try
            {
                intent = service.Create(options);
            }
            catch (Exception)
            {
                return(RedirectToAction("Checkout"));
            }
            var ccvm = new CompleteCheckoutViewModel
            {
                Cart         = cart,
                OrderDetails = orderDetails,
                Subtotal     = subTotal,
                TaxAmount    = tax,
                Total        = total
            };

            ViewData["ClientSecret"] = intent.ClientSecret;

            return(View(ccvm));
        }
Exemplo n.º 25
0
        public IActionResult Register([FromBody] Registration registration)
        {
            _telemetryClient.TrackEvent("Registration:Requested");

            var user         = registration.User;
            var organization = registration.Organization;

            using (var transaction = _context.Database.BeginTransaction())
            {
                try
                {
                    // Ensure Email address is unique.
                    var duplicate = _context.Users.Where(u => u.EmailAddress.ToLower().Equals(user.EmailAddress));
                    if (duplicate.Any())
                    {
                        return(BadRequest("Email address is already taken."));
                    }

                    // Generate an organization code if one is not provided.
                    var code = organization.Code;
                    while (string.IsNullOrEmpty(code))
                    {
                        var generated = GetRandomNumber();

                        var found = _context.Organizations
                                    .Where(o => o.Code == generated);

                        if (!found.Any())
                        {
                            code = generated;
                        }
                    }
                    organization.Code = code;

                    // Generate a user pin if one is not provided.
                    if (string.IsNullOrEmpty(user.Pin))
                    {
                        user.Pin = GetRandomNumber();
                    }

                    // Generates a password hash and salt.
                    var service = new SecurityService();
                    user.PasswordSalt = service.GenerateHash(service.GenerateRandomString());
                    user.PasswordHash = service.GenerateHash(string.Format("{0} {1}", user.Password, user.PasswordSalt));
                    user.Password     = null;

                    // Formatting
                    user.EmailAddress = user.EmailAddress.ToLower();

                    // Auto-generated.
                    user.Role                           = "Administrator";
                    user.CreatedAt                      = DateTime.UtcNow;
                    user.AllowedPhoneNumbers            = "*";
                    user.TimeZone                       = "America/New_York";
                    user.IsActive                       = true;
                    user.CanViewPunches                 = true;
                    user.CanCreatePunches               = true;
                    user.CanModifyPunches               = true;
                    user.CanDeletePunches               = true;
                    user.CanSplitAndPopulatePunches     = true;
                    user.CanViewReports                 = true;
                    user.CanViewLocks                   = true;
                    user.CanCreateLocks                 = true;
                    user.CanUndoLocks                   = true;
                    user.CanViewTimecards               = true;
                    user.CanCreateTimecards             = true;
                    user.CanModifyTimecards             = true;
                    user.CanDeleteTimecards             = true;
                    user.CanViewUsers                   = true;
                    user.CanCreateUsers                 = true;
                    user.CanModifyUsers                 = true;
                    user.CanDeleteUsers                 = true;
                    user.CanViewInventoryItems          = true;
                    user.CanSyncInventoryItems          = true;
                    user.CanViewInventoryConsumptions   = true;
                    user.CanSyncInventoryConsumptions   = true;
                    user.CanDeleteInventoryConsumptions = true;
                    user.CanViewRates                   = true;
                    user.CanCreateRates                 = true;
                    user.CanModifyRates                 = true;
                    user.CanDeleteRates                 = true;
                    user.CanViewOrganizationDetails     = true;
                    user.CanModifyOrganizationDetails   = true;
                    user.CanViewCustomers               = true;
                    user.CanCreateCustomers             = true;
                    user.CanModifyCustomers             = true;
                    user.CanDeleteCustomers             = true;
                    user.CanViewProjects                = true;
                    user.CanCreateProjects              = true;
                    user.CanModifyProjects              = true;
                    user.CanDeleteProjects              = true;
                    user.CanViewTasks                   = true;
                    user.CanCreateTasks                 = true;
                    user.CanModifyTasks                 = true;
                    user.CanDeleteTasks                 = true;
                    organization.CreatedAt              = DateTime.UtcNow;
                    organization.MinutesFormat          = "minutes";
                    organization.StripeCustomerId       = "UNSPECIFIED";
                    organization.StripeSubscriptionId   = "UNSPECIFIED";
                    organization.ShowCustomerNumber     = true;
                    organization.ShowProjectNumber      = true;
                    organization.ShowTaskNumber         = true;
                    organization.SortCustomersByColumn  = "Number";
                    organization.SortProjectsByColumn   = "Number";
                    organization.SortTasksByColumn      = "Number";

                    // Determine the actual Stripe Plan Id based on the PlanId.
                    var stripePlanId = _configuration["StripePlanId1"]; // Default plan is the contractor plan
                    switch (organization.PlanId)
                    {
                    case 1:
                        stripePlanId = _configuration["StripePlanId1"];
                        break;

                    case 2:
                        stripePlanId = _configuration["StripePlanId2"];
                        break;

                    case 3:
                        stripePlanId = _configuration["StripePlanId3"];
                        break;

                    case 4:
                        stripePlanId = _configuration["StripePlanId4"];
                        break;
                    }

                    if (!string.IsNullOrEmpty(stripePlanId))
                    {
                        try
                        {
                            _telemetryClient.TrackEvent("Registration:Subscribe");

                            // Create a Stripe customer object and save the customer id.
                            var customerOptions = new CustomerCreateOptions
                            {
                                Email = user.EmailAddress
                            };
                            var             customers = new CustomerService();
                            Stripe.Customer customer  = customers.Create(customerOptions);
                            organization.StripeCustomerId = customer.Id;

                            // Subscribe the customer to the price and save the subscription id.
                            var subscriptionOptions = new SubscriptionCreateOptions
                            {
                                Customer = customer.Id, // ex. cus_IDjvN9UsoFp2mk
                                Items    = new List <SubscriptionItemOptions>
                                {
                                    new SubscriptionItemOptions
                                    {
                                        Price = stripePlanId // ex. price_1Hd5PvLI44a19MHX9w5EGD4r
                                    }
                                },
                                TrialFromPlan = true
                            };
                            var          subscriptions = new SubscriptionService();
                            Subscription subscription  = subscriptions.Create(subscriptionOptions);

                            organization.StripeSubscriptionId = subscription.Id;

                            // Send Welcome Email.
                            _telemetryClient.TrackEvent("Registration:Email");

                            var apiKey   = _configuration["SendGridApiKey"];
                            var client   = new SendGridClient(apiKey);
                            var from     = new EmailAddress("BRIZBEE <*****@*****.**>");
                            var to       = new EmailAddress(user.EmailAddress);
                            var msg      = MailHelper.CreateSingleTemplateEmail(from, to, "d-8c48a9ad2ddd4d73b6e6c10307182f43", null);
                            var response = client.SendEmailAsync(msg);
                        }
                        catch (Exception ex)
                        {
                            _telemetryClient.TrackException(ex);
                            return(BadRequest(ex.Message));
                        }
                    }

                    // Save the organization and user.
                    _context.Organizations.Add(organization);
                    user.OrganizationId = organization.Id;

                    _context.Users.Add(user);

                    _context.SaveChanges();

                    _telemetryClient.TrackEvent("Registration:Succeeded");

                    transaction.Commit();

                    return(Created("auth/me", user));
                }
                catch (DbUpdateException ex)
                {
                    transaction.Rollback();

                    _telemetryClient.TrackException(ex);

                    return(BadRequest(ex.Message));
                }
                catch (Exception ex)
                {
                    transaction.Rollback();

                    _telemetryClient.TrackException(ex);

                    return(BadRequest(ex.Message));
                }
            }
        }