示例#1
0
        public IViewComponentResult Invoke(int numberOfItems)
        {
            var user = GetCurrentUserAsync();

            if (!string.IsNullOrEmpty(user.StripeCustomerId))
            {
                var customerService = new StripeSubscriptionService(_stripeSettings.Value.SecretKey);
                var subscriptions   = customerService.List(user.StripeCustomerId);

                var customerSubscription = new CustomerPaymentViewModel
                {
                    UserName      = user.Email,
                    Subscriptions = subscriptions.Select(s => new CustomerSubscriptionViewModel
                    {
                        Id       = s.Id,
                        Name     = s.StripePlan.Name,
                        Amount   = s.StripePlan.Amount,
                        Currency = s.StripePlan.Currency,
                        Status   = s.Status
                    }).ToList()
                };
                return(View("View", customerSubscription));
            }
            var subscription = new CustomerPaymentViewModel
            {
                UserName      = user.Email,
                Subscriptions = new List <CustomerSubscriptionViewModel>()
            };

            return(View(subscription));
        }
        public void CreateCustomerPayment(CustomerPaymentViewModel customerPayment)
        {
            var customerPaymentCreate = Mapper.Map <CustomerPaymentViewModel, CustomerPayment_D>(customerPayment);

            _customerPaymentRepository.Add(customerPaymentCreate);
            SaveCustomerPayment();
        }
        public void UpdateCustomerPayment(CustomerPaymentViewModel customerPayment)
        {
            var updateCustomerPayment = Mapper.Map <CustomerPaymentViewModel, CustomerPayment_D>(customerPayment);

            _customerPaymentRepository.Update(updateCustomerPayment);
            SaveCustomerPayment();
        }
 private void UpdateUserEmail(CustomerPaymentViewModel payment, ApplicationUser user)
 {
     if (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)
     {
         var client  = new RestClient("https://hooks.zapier.com/hooks/catch/2318707/z0jmup/");
         var request = new RestRequest(Method.POST);
         request.AddParameter("email", user.Email);
         request.AddParameter("contact_name", payment.Name);
         request.AddParameter("language_preference", _currencyService.GetCurrentLanguage().TwoLetterISOLanguageName);
         request.AddParameter("salutation", payment.Name.Split(' ').Length == 1 ? payment.Name : payment.Name.Split(' ')[0]);
         request.AddParameter("last_name", payment.Name.Split(' ').Length == 1 ? "" : payment.Name.Split(' ')[(payment.Name.Split(' ').Length - 1)]);
         request.AddParameter("address_line_1", payment.AddressLine1);
         request.AddParameter("address_line_2", payment.AddressLine2);
         request.AddParameter("server_location", _currencySettings.Value.ServerLocation);
         request.AddParameter("ip_address", _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString());
         request.AddParameter("time_zone", payment.TimeZone);
         request.AddParameter("city", payment.City);
         request.AddParameter("state", payment.State);
         request.AddParameter("zip", payment.Zip);
         request.AddParameter("country", payment.Country);
         // execute the request
         IRestResponse response = client.Execute(request);
     }
 }
示例#5
0
        public async Task <IActionResult> Payment(int id)
        {
            var user = await GetCurrentUserAsync();

            var donation = _donationService.GetById(id);
            var detail   = (DonationViewModel)donation;

            detail.DonationOptions = _donationService.DonationOptions;

            var model = new CustomerPaymentViewModel
            {
                Name         = user.FullName,
                AddressLine1 = user.AddressLine1,
                AddressLine2 = user.AddressLine2,
                City         = user.City,
                State        = user.State,
                Country      = user.Country,
                Zip          = user.Zip,
                DonationId   = donation.Id,
                Description  = detail.GetDescription(),
                Frequency    = detail.GetCycle(),
                Amount       = detail.GetDisplayAmount()
            };

            return(View(model));
        }
示例#6
0
        public int?CreateUpdateCustomerPayment(CustomerPaymentViewModel customerPaymentViewModel)
        {
            CustomerPayment customerPayment = null;

            if (customerPaymentViewModel.CustomerPaymentId > 0)
            {
                customerPayment = _repository.Find <CustomerPayment>(x => x.CustomerPaymentId == customerPaymentViewModel.CustomerPaymentId);
                if (customerPayment == null)
                {
                    return(null);
                }

                customerPayment.InvoiceId    = customerPaymentViewModel.InvoiceId;
                customerPayment.CustomerId   = customerPaymentViewModel.CustomerId;
                customerPayment.PaymentDate  = customerPaymentViewModel.PaymentDate;
                customerPayment.Amount       = customerPaymentViewModel.Amount;
                customerPayment.Comments     = customerPaymentViewModel.Comments;
                customerPayment.ModifiedBy   = customerPaymentViewModel.ModifiedBy;
                customerPayment.ModifiedDate = DateTime.Now;

                _repository.Modify <CustomerPayment>(customerPayment);
                return(customerPayment.CustomerPaymentId);
            }

            Mapper.CreateMap <CustomerPaymentViewModel, CustomerPayment>();
            customerPayment = Mapper.Map <CustomerPaymentViewModel, CustomerPayment>(customerPaymentViewModel);

            customerPayment.CreatedDate = DateTime.Now;
            customerPayment.CreatedBy   = customerPaymentViewModel.CreatedBy;
            customerPayment.IsDeleted   = false;
            return(_repository.Insert <CustomerPayment>(customerPayment));
        }
        public async Task <IActionResult> Payment(int id)
        {
            var user = await GetCurrentUserAsync();

            try
            {
                var donation = _donationService.GetById(id);
                var detail   = (DonationViewModel)donation;
                List <CountryViewModel> countryList = GetCountryList();

                // Check for existing customer
                // edit = 1 means user wants to edit the credit card information
                if (!string.IsNullOrEmpty(user.StripeCustomerId))
                {
                    try
                    {
                        var            CustomerService   = new StripeCustomerService(_stripeSettings.Value.SecretKey);
                        StripeCustomer objStripeCustomer = CustomerService.Get(user.StripeCustomerId);
                        StripeCard     objStripeCard     = null;

                        if (objStripeCustomer.Sources != null && objStripeCustomer.Sources.TotalCount > 0 && objStripeCustomer.Sources.Data.Any())
                        {
                            objStripeCard = objStripeCustomer.Sources.Data.FirstOrDefault().Card;
                        }

                        if (objStripeCard != null && !string.IsNullOrEmpty(objStripeCard.Id))
                        {
                            CustomerRePaymentViewModel customerRePaymentViewModel = CustomerRepaymentModelData(user, donation, detail, countryList, objStripeCustomer, objStripeCard);
                            return(View("RePayment", customerRePaymentViewModel));
                        }
                    }
                    catch (StripeException ex)
                    {
                        log = new EventLog()
                        {
                            EventId = (int)LoggingEvents.GET_ITEM, LogLevel = LogLevel.Error.ToString(), Message = ex.Message, StackTrace = ex.StackTrace, Source = ex.Source, EmailId = user.Email
                        };
                        _loggerService.SaveEventLogAsync(log);
                        ModelState.AddModelError("CustomerNotFound", ex.Message);
                    }
                }

                CustomerPaymentViewModel customerPaymentViewModel = GetCustomerPaymentModel(user, donation, detail, countryList);
                return(View("Payment", customerPaymentViewModel));
            }
            catch (Exception ex)
            {
                log = new EventLog()
                {
                    EventId = (int)LoggingEvents.GET_ITEM, 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
                }));
            }
        }
 private static CustomerCreateOptions GetCustomerCreateOptions(CustomerPaymentViewModel payment, User user)
 {
     return(new CustomerCreateOptions
     {
         Email = user.Email,
         Description = $"{user.Email} {user.Id}",
         Source = payment.cardtoken
     });
 }
 private async Task UpdateUserDetail(CustomerPaymentViewModel payment, ApplicationUser user)
 {
     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);
 }
        public ActionResult CreateUpdateCustomerPayment(CustomerPaymentViewModel customerPaymentViewModel)
        {
            ActiveUser activeUser = new JavaScriptSerializer().Deserialize <ActiveUser>(System.Web.HttpContext.Current.User.Identity.Name);

            customerPaymentViewModel.CreatedBy  = activeUser.UserId;
            customerPaymentViewModel.ModifiedBy = activeUser.UserId;

            var result = _customerPaymentComponent.CreateUpdateCustomerPayment(customerPaymentViewModel);

            return(Json(result, JsonRequestBehavior.AllowGet));
        }
        public ActionResult CreateUpdateCustomerPaymentPopup(int id)
        {
            var customerPayment = _customerPaymentComponent.GetCustomerPayment(id);

            if (customerPayment == null)
            {
                customerPayment = new CustomerPaymentViewModel();
            }
            customerPayment.CustomerList = new SelectList(_customerComponent.GetAllCustomer(), "CustomerId", "NameEmail");
            //customerPayment.InvoiceList = new SelectList(_customerInvoiceComponent.GetAllCustomerInvoice(), "InvoiceId", "InvoiceNo");
            return(PartialView("/Views/Shared/Partials/_CustomerPayment.cshtml", customerPayment));
        }
        public ActionResult Subscription()
        {
            ViewBag.isLoggedIn = HttpContext.Session.GetInt32("isLoggedIn");
            if (ViewBag.isLoggedIn != 1)
            {
                return(RedirectToAction(nameof(Login)));
            }

            CustomerPaymentViewModel payment = new CustomerPaymentViewModel();

            payment.massage = "";
            return(View(payment));
        }
示例#13
0
        public IViewComponentResult Invoke(int numberOfItems)
        {
            var user = GetCurrentUserAsync();

            if (!string.IsNullOrEmpty(user.StripeCustomerId))
            {
                var customerService = new StripeSubscriptionService(_stripeSettings.Value.SecretKey);

                var StripSubscriptionListOption = new StripeSubscriptionListOptions()
                {
                    CustomerId = user.StripeCustomerId,
                    Limit      = 100
                };

                var customerSubscription = new CustomerPaymentViewModel();

                try
                {
                    var subscriptions = customerService.List(StripSubscriptionListOption);
                    customerSubscription = new CustomerPaymentViewModel
                    {
                        UserName      = user.Email,
                        Subscriptions = subscriptions.Select(s => new CustomerSubscriptionViewModel
                        {
                            Id       = s.Id,
                            Name     = s.StripePlan.Id,
                            Amount   = s.StripePlan.Amount,
                            Currency = s.StripePlan.Currency,
                            Status   = s.Status
                        }).ToList()
                    };
                }
                catch (StripeException sex)
                {
                    ModelState.AddModelError("CustmoerNotFound", sex.Message);
                }

                return(View("View", customerSubscription));
            }

            var subscription = new CustomerPaymentViewModel
            {
                UserName = user.Email,

                Subscriptions = new List <CustomerSubscriptionViewModel>()
            };

            return(View("View", subscription));
        }
        public async Task <IActionResult> Payment(int id, int edit)
        {
            var user = await GetCurrentUserAsync();

            try
            {
                var donation = _donationService.GetById(id);
                var detail   = (DonationViewModel)donation;
                CustomerPaymentViewModel model = new CustomerPaymentViewModel();

                try
                {
                    var customerService  = new StripeCustomerService(_stripeSettings.Value.SecretKey);
                    var ExistingCustomer = customerService.Get(user.StripeCustomerId);
                    List <CountryViewModel> countryList = GetCountryList();
                    model = GetCustomerPaymentModel(user, donation, detail, countryList);
                    model.DisableCurrencySelection = "1"; // Disable currency selection for already created customer as stripe only allow same currency for one customer,
                }
                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);
                    ModelState.AddModelError("CustomerNotFound", ex.Message);
                }

                return(View("Payment", model));
            }
            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
                }));
            }
        }
 private static StripeCustomerUpdateOptions GetCustomerUpdateOption(CustomerPaymentViewModel payment)
 {
     return(new StripeCustomerUpdateOptions
     {
         SourceCard = new SourceCard
         {
             Name = payment.Name,
             Number = payment.CardNumber,
             Cvc = payment.Cvc,
             ExpirationMonth = payment.ExpiryMonth,
             ExpirationYear = payment.ExpiryYear,
             AddressLine1 = payment.AddressLine1,
             AddressLine2 = payment.AddressLine2,
             AddressCity = payment.City,
             AddressState = payment.State,
             AddressCountry = payment.Country,
             AddressZip = payment.Zip
         }
     });
 }
 private static StripeCustomerCreateOptions GetCustomerCreateOptions(CustomerPaymentViewModel payment, ApplicationUser user)
 {
     return(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,
             AddressLine1 = payment.AddressLine1,
             AddressLine2 = payment.AddressLine2,
             AddressCity = payment.City,
             AddressState = payment.State,
             AddressCountry = payment.Country,
             AddressZip = payment.Zip
         }
     });
 }
 public void Put(CustomerPaymentViewModel customerPayment)
 {
     _customerPaymentService.UpdateCustomerPayment(customerPayment);
 }
        public IActionResult Subscription(CustomerPaymentViewModel payment)
        {
            string email = HttpContext.Session.GetString("User");

            ViewBag.isLoggedIn = 1;

            try
            {
                NewWebSubContext context = HttpContext.RequestServices.GetService(typeof(new_websub.NewWebSubContext)) as NewWebSubContext;

                string          query = "select * from useraccounts u inner join address a on u.AddressId=a.addresskey where u.Email=@Email";
                MySqlConnection conn  = context.GetConnection();

                conn.Open();

                MySqlCommand   cmd   = new MySqlCommand(query, conn);
                MySqlParameter param = new MySqlParameter("@Email", email);
                param.MySqlDbType = MySqlDbType.VarChar;
                cmd.Parameters.Add(param);
                MySqlDataReader reader = cmd.ExecuteReader();

                if (reader.Read())
                {
                    User user = new User();
                    user.Email            = email;
                    user.Id               = reader["UserID"].ToString();
                    user.FullName         = reader["UserName"].ToString();
                    user.StripeCustomerId = "";
                    user.AddressLine1     = reader["Address1"].ToString();
                    user.AddressLine2     = reader["Address2"].ToString();
                    user.City             = reader["City"].ToString();
                    user.State            = reader["State"].ToString();
                    user.Zip              = reader["Zipcode"].ToString();
                    user.Country          = reader["Country"].ToString();
                    user.HistoryView      = true;

                    StripeConfiguration.SetApiKey(_stripeSettings.Value.SecretKey);

                    var tokenoptions = new TokenCreateOptions
                    {
                        Card = new CreditCardOptions
                        {
                            Number   = payment.CardNumber,
                            ExpYear  = payment.ExpiryYear,
                            ExpMonth = payment.ExpiryMonth,
                            Cvc      = payment.Cvc
                        }
                    };

                    var   tokenservice = new TokenService();
                    Token stripeToken  = tokenservice.Create(tokenoptions);
                    payment.cardtoken = stripeToken.Id;
                    CustomerCreateOptions customerCreateOptions = GetCustomerCreateOptions(payment, user);
                    var          cusservice = new CustomerService();
                    var          customers  = cusservice.Create(customerCreateOptions);
                    Subscription subscription;
                    var          plservice = new PlanService();
                    try
                    {
                        var plplan = plservice.Get(payment.subsctype);

                        var items = new List <SubscriptionItemOption> {
                            new SubscriptionItemOption {
                                PlanId = plplan.Id
                            }
                        };
                        var suboptions = new SubscriptionCreateOptions
                        {
                            CustomerId = customers.Id,
                            Items      = items
                        };

                        var subservice = new SubscriptionService();
                        subscription = subservice.Create(suboptions);
                    }
                    catch
                    {
                        var options = new PlanCreateOptions
                        {
                            Product = new PlanProductCreateOptions
                            {
                                Id   = payment.subsctype,
                                Name = payment.subsctype
                            },
                            Amount   = payment.Amount,
                            Currency = payment.Currency,
                            Interval = payment.subsctype,
                            Id       = payment.subsctype
                        };

                        var  service = new PlanService();
                        Plan plan    = service.Create(options);
                        var  items   = new List <SubscriptionItemOption> {
                            new SubscriptionItemOption {
                                PlanId = plan.Id
                            }
                        };
                        var suboptions = new SubscriptionCreateOptions
                        {
                            CustomerId = customers.Id,
                            Items      = items
                        };

                        var subservice = new SubscriptionService();
                        subscription = subservice.Create(suboptions);
                    }

                    reader.Close();
                    // insert into subscriptions table

                    query = "insert into subscriptions(Email, CustomerId, SubscriptionId, Subscription_Started, Subscription_Ended) values(@Email," +
                            "@CustomerId, @SubscriptionId, @Subscription_Started, @Subscription_Ended)";
                    MySqlCommand   cmd1   = new MySqlCommand(query, conn);
                    MySqlParameter param1 = new MySqlParameter("@Email", user.Email);
                    param1.MySqlDbType = MySqlDbType.VarChar;
                    cmd1.Parameters.Add(param1);

                    param1             = new MySqlParameter("@CustomerId", subscription.CustomerId);
                    param1.MySqlDbType = MySqlDbType.VarChar;
                    cmd1.Parameters.Add(param1);

                    param1             = new MySqlParameter("@SubscriptionId", subscription.Id);
                    param1.MySqlDbType = MySqlDbType.VarChar;
                    cmd1.Parameters.Add(param1);

                    param1             = new MySqlParameter("@Subscription_Started", subscription.StartDate);
                    param1.MySqlDbType = MySqlDbType.DateTime;
                    cmd1.Parameters.Add(param1);

                    param1             = new MySqlParameter("@Subscription_Ended", subscription.EndedAt);
                    param1.MySqlDbType = MySqlDbType.DateTime;
                    cmd1.Parameters.Add(param1);

                    cmd1.ExecuteNonQuery();

                    HttpContext.Session.SetInt32("isLoggedIn", 1);
                    payment.massage = "Payment created successfully";

                    //return View("Success"); // render Success.cshtml
                    return(View(payment));
                }
                else
                {
                    return(RedirectToAction(nameof(Login)));
                }
            }
            catch (Exception ex)
            {
                MailMessage mail = new MailMessage();
                mail.From       = new MailAddress(_emailSettings.Value.PrimaryEmail);
                mail.Subject    = "Subscription Fail";
                mail.IsBodyHtml = true;
                mail.Body       = ex.Message;
                mail.Sender     = new MailAddress(_emailSettings.Value.PrimaryEmail);
                mail.To.Add(email);
                SmtpClient smtp = new SmtpClient();
                smtp.Host = _emailSettings.Value.PrimaryDomain; //Or Your SMTP Server Address
                smtp.Port = _emailSettings.Value.PrimaryPort;
                smtp.UseDefaultCredentials = false;
                smtp.DeliveryMethod        = SmtpDeliveryMethod.Network;
                smtp.Credentials           = new System.Net.NetworkCredential(_emailSettings.Value.PrimaryEmail, _emailSettings.Value.PrimaryPassword);
                //Or your Smtp Email ID and Password
                smtp.EnableSsl = _emailSettings.Value.EnableSsl;
                smtp.Send(mail);
                payment.massage = ex.Message;
                return(View(payment));
            }
        }
示例#19
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"));
        }
        public async Task <IActionResult> CampaignPayment(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        = _campaignService.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.INSERT_ITEM, 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 = _campaignService.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", 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"
            }));
        }
示例#21
0
        public CustomerPaymentPage(CustomerPaymentViewModel viewModel)
        {
            InitializeComponent();

            BindingContext = this.viewModel = viewModel;
        }
 public void Post(CustomerPaymentViewModel category)
 {
     _customerPaymentService.CreateCustomerPayment(category);
 }