Exemplo n.º 1
0
        /// <summary>
        /// Create plan for this donation if is does not exist and return its instance. If it does exist
        /// return the instance.
        /// </summary>
        /// <param name="donation"></param>
        /// <returns></returns>
        public StripePlan GetOrCreatePlan(Donation donation)
        {
            var planService = new StripePlanService(_stripeSettings.Value.SecretKey);

            // Construct plan name from the selected donation type and the cycle
            var cycle = EnumInfo <PaymentCycle> .GetValue(donation.CycleId);

            var frequency = EnumInfo <PaymentCycle> .GetDescription(cycle);

            var amount = donation.DonationAmount ?? 0;

            if (donation.DonationAmount == null)
            {
                var model = (DonationViewModel)donation;
                model.DonationOptions = DonationOptions;

                amount = model.GetDisplayAmount();
            }
            var planName = $"{frequency}_{amount}".ToLower();

            // Create new plan is this one does not exist
            if (!Exists(planService, planName))
            {
                var plan = new StripePlanCreateOptions
                {
                    Id                  = planName,
                    Amount              = amount * 100,
                    Currency            = "usd",
                    Name                = planName,
                    StatementDescriptor = _stripeSettings.Value.StatementDescriptor
                };

                // Take care intervals
                if (cycle == PaymentCycle.Quarter)
                {
                    plan.IntervalCount = 3;
                    plan.Interval      = "month";
                }
                else
                {
                    plan.Interval = cycle.ToString().ToLower(); // day/month/year
                }
                return(planService.Create(plan));
            }
            else
            {
                return(planService.Get(planName));
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Create plan for this donation if is does not exist and return its instance. If it does exist
        /// return the instance.
        /// </summary>
        /// <param name="donation"></param>
        /// <returns></returns>
        public StripePlan GetOrCreatePlan(Donation donation)
        {
            var planService = new StripePlanService(_stripeSettings.Value.SecretKey);

            // Construct plan name from the selected donation type and the cycle
            var cycle = EnumInfo <PaymentCycle> .GetValue(donation.CycleId);

            var frequency = EnumInfo <PaymentCycle> .GetDescription(cycle);

            decimal amount   = donation.DonationAmount ?? 0;
            string  currency = donation.Currency;
            var     planName = $"{frequency}_{amount}_{currency}".ToLower(); //

            // Create new plan is this one does not exist
            if (!Exists(planService, planName))
            {
                var plan = new StripePlanCreateOptions
                {
                    Id       = planName,
                    Amount   = Convert.ToInt32(amount * 100),
                    Currency = currency.ToLower(),
                    Nickname = planName,
                    Product  = new StripePlanProductCreateOptions()
                    {
                        Name = planName
                    }
                    //StatementDescriptor = _stripeSettings.Value.StatementDescriptor
                };

                // Take care intervals
                if (cycle == PaymentCycle.Quarter)
                {
                    plan.IntervalCount = 3;
                    plan.Interval      = "month";
                }
                else
                {
                    plan.Interval = cycle.ToString().ToLower(); // day/month/year
                }


                return(planService.Create(plan));
            }
            else
            {
                return(planService.Get(planName));
            }
        }
Exemplo n.º 3
0
        public async Task <AccessTokenDTO> GenerateEncodedToken(string id, string userName, string[] roles)
        {
            var identity = GenerateClaimsIdentity(id, userName);

            var claims = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.Sub, userName),
                new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()),
                new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64),
                new Claim(ClaimTypes.Email, userName),
                new Claim(JwtRegisteredClaimNames.Iss, _jwtOptions.Issuer),
                identity.FindFirst(Constants.Strings.JwtClaimIdentifiers.Id)
            };

            List <string> audiences = new List <string>();

            // add role claims
            roles.ToList().ForEach(role =>
            {
                if (Enum.TryParse(value: role, ignoreCase: true, out Permission permission))
                {
                    claims.Add(new Claim(ClaimTypes.Role, permission.GetValue().ToString()));
                    audiences.Add(permission.GetAudience()); // separate audiences
                }
            });
            // add audience claims related to permissions
            claims.AddRange(audiences.Distinct()
                            .Select(audience => new Claim(JwtRegisteredClaimNames.Aud, audience)));

            claims.AddRange(roles.Where(d => Enum.TryParse <Permission>(d, ignoreCase: true, out _))
                            .Select(role => new Claim(ClaimTypes.Role, EnumInfo.GetValue <Permission>(role).ToString())));
            // Create the JWT security token and encode it.
            var jwt = new JwtSecurityToken(
                issuer: _jwtOptions.Issuer,
                audience: _jwtOptions.Audience,
                claims: claims,
                notBefore: _jwtOptions.NotBefore,
                expires: _jwtOptions.Expiration,
                signingCredentials: _jwtOptions.SigningCredentials);

            return(new AccessTokenDTO(_jwtTokenHandler.WriteToken(jwt), (int)_jwtOptions.ValidFor.TotalSeconds));
        }
        public async Task <IActionResult> CampaignRePayment(CustomerRePaymentViewModel payment)
        {
            var user = await GetCurrentUserAsync();

            try
            {
                List <CountryViewModel> countryList = GetCountryList();
                payment.countries = countryList;
                if (!ModelState.IsValid)
                {
                    return(View(payment));
                }

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

                UpdateUserRepaymentEmail(payment, user);
                await UpdateRepaymentUserDetail(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"
                    }));
                }
                donation.Currency = "usd";//payment.Currency;
                // Add to existing subscriptions and charge
                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"
            }));
        }
        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"
            }));
        }
        public string GetCycle(string CycleId)
        {
            var pc = EnumInfo <PaymentCycle> .GetValue(CycleId);

            return(EnumInfo <PaymentCycle> .GetDescription(pc));
        }
Exemplo n.º 7
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"));
        }