public async Task <IActionResult> Payment(CustomerPaymentViewModel payment)
        {
            var user = await GetCurrentUserAsync();

            try
            {
                List <CountryViewModel> countryList = GetCountryList();
                payment.countries = countryList;
                payment.yearList  = GeneralUtility.GetYeatList();

                if (!ModelState.IsValid)
                {
                    return(View(payment));
                }

                var customerService = new StripeCustomerService(_stripeSettings.Value.SecretKey);
                var donation        = _donationService.GetById(payment.DonationId);

                // Construct payment
                if (string.IsNullOrEmpty(user.StripeCustomerId))
                {
                    StripeCustomerCreateOptions customer = GetCustomerCreateOptions(payment, user);
                    var stripeCustomer = customerService.Create(customer);
                    user.StripeCustomerId = stripeCustomer.Id;
                }
                else
                {
                    //Check for existing credit card, if new credit card number is same as exiting credit card then we delete the existing
                    //Credit card information so new card gets generated automatically as default card.
                    //try
                    //{
                    //    var ExistingCustomer = customerService.Get(user.StripeCustomerId);
                    //    if (ExistingCustomer.Sources != null && ExistingCustomer.Sources.TotalCount > 0 && ExistingCustomer.Sources.Data.Any())
                    //    {
                    //        var cardService = new StripeCardService(_stripeSettings.Value.SecretKey);
                    //        foreach (var cardSource in ExistingCustomer.Sources.Data)
                    //        {
                    //            cardService.Delete(user.StripeCustomerId, cardSource.Card.Id);
                    //        }
                    //    }
                    //}
                    //catch (Exception ex)
                    //{
                    //    log = new EventLog() { EventId = (int)LoggingEvents.GET_CUSTOMER, LogLevel = LogLevel.Error.ToString(), Message = ex.Message, StackTrace = ex.StackTrace, Source = ex.Source, EmailId = user.Email };
                    //    _loggerService.SaveEventLogAsync(log);
                    //    return RedirectToAction("Error", "Error500", new ErrorViewModel() { Error = ex.Message });
                    //}

                    StripeCustomerUpdateOptions customer = GetCustomerUpdateOption(payment);
                    try
                    {
                        var stripeCustomer = customerService.Update(user.StripeCustomerId, customer);
                        user.StripeCustomerId = stripeCustomer.Id;
                    }
                    catch (StripeException ex)
                    {
                        log = new EventLog()
                        {
                            EventId = (int)LoggingEvents.GET_CUSTOMER, LogLevel = LogLevel.Error.ToString(), Message = ex.Message, StackTrace = ex.StackTrace, Source = ex.Source, EmailId = user.Email
                        };
                        _loggerService.SaveEventLogAsync(log);
                        if (ex.Message.ToLower().Contains("customer"))
                        {
                            return(RedirectToAction("Error", "Error500", new ErrorViewModel()
                            {
                                Error = ex.Message
                            }));
                        }
                        else
                        {
                            ModelState.AddModelError("error", _localizer[ex.Message]);
                            return(View(payment));
                        }
                    }
                }

                UpdateUserEmail(payment, user);
                await UpdateUserDetail(payment, user);

                // Add customer to Stripe
                if (EnumInfo <PaymentCycle> .GetValue(donation.CycleId) == PaymentCycle.OneTime)
                {
                    var model   = (DonationViewModel)donation;
                    var charges = new StripeChargeService(_stripeSettings.Value.SecretKey);

                    // Charge the customer
                    var charge = charges.Create(new StripeChargeCreateOptions
                    {
                        Amount              = Convert.ToInt32(donation.DonationAmount * 100),
                        Description         = DonationCaption,
                        Currency            = "usd",//payment.Currency.ToLower(),
                        CustomerId          = user.StripeCustomerId,
                        StatementDescriptor = _stripeSettings.Value.StatementDescriptor,
                    });

                    if (charge.Paid)
                    {
                        var completedMessage = new CompletedViewModel
                        {
                            Message          = donation.DonationAmount.ToString(),
                            HasSubscriptions = false
                        };
                        return(RedirectToAction("Thanks", completedMessage));
                    }
                    return(RedirectToAction("Error", "Error", new ErrorViewModel()
                    {
                        Error = "Error"
                    }));
                }

                // Add to existing subscriptions and charge
                donation.Currency = "usd"; //payment.Currency;
                var plan = _donationService.GetOrCreatePlan(donation);

                var subscriptionService = new StripeSubscriptionService(_stripeSettings.Value.SecretKey);
                var result = subscriptionService.Create(user.StripeCustomerId, plan.Id);
                if (result != null)
                {
                    CompletedViewModel completedMessage = new CompletedViewModel();
                    completedMessage = GetSubscriptionMessage(result, true);
                    return(RedirectToAction("Thanks", completedMessage));
                }
            }
            catch (StripeException ex)
            {
                log = new EventLog()
                {
                    EventId = (int)LoggingEvents.INSERT_ITEM, LogLevel = LogLevel.Error.ToString(), Message = ex.Message, StackTrace = ex.StackTrace, Source = ex.Source, EmailId = user.Email
                };
                _loggerService.SaveEventLogAsync(log);
                if (ex.Message.ToLower().Contains("customer"))
                {
                    return(RedirectToAction("Error", "Error500", new ErrorViewModel()
                    {
                        Error = ex.Message
                    }));
                }
                else
                {
                    ModelState.AddModelError("error", _localizer[ex.Message]);
                    return(View(payment));
                }
            }
            catch (Exception ex)
            {
                log = new EventLog()
                {
                    EventId = (int)LoggingEvents.INSERT_ITEM, LogLevel = LogLevel.Error.ToString(), Message = ex.Message, StackTrace = ex.StackTrace, Source = ex.Source, EmailId = user.Email
                };
                _loggerService.SaveEventLogAsync(log);
                return(RedirectToAction("Error", "Error", new ErrorViewModel()
                {
                    Error = ex.Message
                }));
            }

            return(RedirectToAction("Error", "Error", new ErrorViewModel()
            {
                Error = "Error"
            }));
        }
Example #2
0
        public async Task <IActionResult> Payment(CustomerPaymentViewModel payment)
        {
            var user = await GetCurrentUserAsync();

            // Can be better
            if ((payment.ExpiryYear + 2000) == DateTime.Now.Year && payment.ExpiryMonth <= DateTime.Now.Month)
            {
                ModelState.AddModelError("expiredCard", "Expired card");
            }

            if (!ModelState.IsValid)
            {
                return(View(payment));
            }

            var customerService = new StripeCustomerService(_stripeSettings.Value.SecretKey);
            var donation        = _donationService.GetById(payment.DonationId);

            // Construct payment
            var customer = new StripeCustomerCreateOptions
            {
                Email       = user.Email,
                Description = $"{user.Email} {user.Id}",
                SourceCard  = new SourceCard
                {
                    Name                = payment.Name,
                    Number              = payment.CardNumber,
                    Cvc                 = payment.Cvc,
                    ExpirationMonth     = payment.ExpiryMonth,
                    ExpirationYear      = payment.ExpiryYear,
                    StatementDescriptor = _stripeSettings.Value.StatementDescriptor,

                    Description = DonationCaption,

                    AddressLine1   = payment.AddressLine1,
                    AddressLine2   = payment.AddressLine2,
                    AddressCity    = payment.City,
                    AddressState   = payment.State,
                    AddressCountry = payment.Country,
                    AddressZip     = payment.Zip
                }
            };

            if (string.IsNullOrEmpty(user.StripeCustomerId))
            {
                var stripeCustomer = customerService.Create(customer);
                user.StripeCustomerId = stripeCustomer.Id;
            }

            user.FullName     = payment.Name;
            user.AddressLine1 = payment.AddressLine1;
            user.AddressLine2 = payment.AddressLine2;
            user.City         = payment.City;
            user.State        = payment.State;
            user.Country      = payment.Country;
            user.Zip          = payment.Zip;
            await _userManager.UpdateAsync(user);


            // Add customer to Stripe
            if (EnumInfo <PaymentCycle> .GetValue(donation.CycleId) == PaymentCycle.OneOff)
            {
                var model = (DonationViewModel)donation;
                model.DonationOptions = _donationService.DonationOptions;

                var charges = new StripeChargeService(_stripeSettings.Value.SecretKey);

                // Charge the customer
                var charge = charges.Create(new StripeChargeCreateOptions
                {
                    Amount      = model.GetAmount(),
                    Description = DonationCaption,
                    Currency    = "usd",
                    CustomerId  = user.StripeCustomerId,
                    //ReceiptEmail = user.Email,
                    StatementDescriptor = _stripeSettings.Value.StatementDescriptor,
                });

                if (charge.Paid)
                {
                    var completedMessage = new CompletedViewModel
                    {
                        Message = $"Thank you donating {model.GetDisplayAmount()} for the payment {model.GetDescription()} "
                    };
                    return(View("Thanks", completedMessage));
                }
                return(View("Error"));
            }

            // Add to existing subscriptions and charge
            var plan = _donationService.GetOrCreatePlan(donation);

            var subscriptionService = new StripeSubscriptionService(_stripeSettings.Value.SecretKey);
            var result = subscriptionService.Create(user.StripeCustomerId, plan.Id);

            if (result != null)
            {
                var completedMessage = new CompletedViewModel
                {
                    Message          = $"You have added a subscription {result.StripePlan.Name} for this donation",
                    HasSubscriptions = true
                };
                return(View("Thanks", completedMessage));
            }
            return(View("Error"));
        }