Esempio n. 1
0
        public static bool UnSubscribe(string CustId)
        {
            var subsService = new StripeSubscriptionService();

            StripeList <StripeSubscription> activeSub = subsService.List(new StripeSubscriptionListOptions()
            {
                CustomerId = CustId,
                Limit      = 10
            });

            try
            {
                if (activeSub.Count() > 0)
                {
                    foreach (var sub in activeSub)
                    {
                        StripeSubscription subs = subsService.Cancel(sub.Id);
                    }
                }
                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
Esempio n. 2
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 int CancelSubscription(string userMail, string plansId)
        {
            StripeConfiguration.SetApiKey("sk_test_YskwifolV97dD2Iu0v8YgDt5");


            var customerService = new StripeCustomerService();
            StripeList <StripeCustomer> customerItems = customerService.List(
                new StripeCustomerListOptions()
            {
                Limit = 300
            }
                );
            bool found = false;

            var customer = new StripeCustomer();

            foreach (StripeCustomer cus in customerItems)
            {
                if (cus.Email == userMail)
                {
                    found    = true;
                    customer = cus;
                    break;
                }
            }

            if (found)
            {
                var subscriptionService = new StripeSubscriptionService();
                StripeList <StripeSubscription> response = subscriptionService.List(new StripeSubscriptionListOptions
                {
                    Limit = 3333
                });


                found = false;

                var subscript = new StripeSubscription();

                foreach (StripeSubscription subs in response)
                {
                    if (subs.CustomerId == customer.Id && subs.StripePlan.Id == plansId)
                    {
                        found     = true;
                        subscript = subs;
                        break;
                    }
                }

                if (found)
                {
                    StripeSubscription subscription = subscriptionService.Cancel(subscript.Id, new StripeSubscriptionCancelOptions());
                }
            }



            return(0);
        }
        public ActionResult ManageSubscription()
        {
            var model = new ManageSubscriptionViewModel();

            try
            {
                //GetUptodate plan prices from stripe
                var planService = new StripePlanService(SensativeInformation.StripeKeys.SecretKey);
                var ordPlan     = planService.Get(StaticIdentifiers.OrdinaryMemberPlanId);
                var socialPlan  = planService.Get(StaticIdentifiers.SocialMemberPlanId);
                var patronPlan  = planService.Get(StaticIdentifiers.PatronPlanId);
                if (ordPlan != null)
                {
                    model.OrdinaryPrice = (ordPlan.Amount / 100m).ToString("N");
                }
                if (socialPlan != null)
                {
                    model.SocialPrice = (socialPlan.Amount / 100m).ToString("N");
                }
                if (patronPlan != null)
                {
                    model.PatronPrice = (patronPlan.Amount / 100m).ToString("N");
                }
            }
            catch (StripeException e)
            {
                _log.Error($"There was a stripe error whilst trying to load the current subscriptions prices for the manage membership page. The error was {e.Message}.");
            }
            try
            {
                var stripeAccountId = new Member(Members.GetCurrentMember()).StripeUserId;
                var dm = new DataManager();
                if (stripeAccountId.IsNotNullOrEmpty())
                {
                    model.IsStripeUser            = true;
                    model.HasExistingSubscription = false;
                    //Get plan status
                    var subscriptionService = new StripeSubscriptionService(SensativeInformation.StripeKeys.SecretKey);
                    var listOption          = new StripeSubscriptionListOptions {
                        CustomerId = stripeAccountId
                    };
                    var stripeSubscriptions = subscriptionService.List(listOption);

                    if (stripeSubscriptions != null && stripeSubscriptions.Any())
                    {
                        model.IsOrdinaryMember        = stripeSubscriptions.Any(m => m.StripePlan.Id == StaticIdentifiers.OrdinaryMemberPlanId && m.Status == StripeSubscriptionStatuses.Active);
                        model.IsSocialMember          = stripeSubscriptions.Any(m => m.StripePlan.Id == StaticIdentifiers.SocialMemberPlanId && m.Status == StripeSubscriptionStatuses.Active);
                        model.IsPatron                = stripeSubscriptions.Any(m => m.StripePlan.Id == StaticIdentifiers.PatronPlanId && m.Status == StripeSubscriptionStatuses.Active);
                        model.HasExistingSubscription = stripeSubscriptions.Any(m => m.Status == StripeSubscriptionStatuses.Active);
                    }
                }
            }
            catch (StripeException e)
            {
                _log.Error($"There was a stripe error whilst trying to load the current subscriptions for the managemembership page for user {Members.GetCurrentMember().Name} and id {Members.GetCurrentMember().Id}. The error was {e.Message}.");
            }

            return(PartialView("ManageSubscription", model));
        }
Esempio n. 5
0
        public static IEnumerable <StripeSubscription> ExpiredTrialSubs()
        {
            var subscriptionService = new StripeSubscriptionService();
            var subs = new List <StripeSubscription>();

            try
            {
                var allSubs = subscriptionService.List().ToList();
                subs = subscriptionService.List().Where(s => s.CurrentPeriodEnd == DateTime.Now).ToList();
                //subs = subs.Where(s => s.CurrentPeriodEnd <= DateTime.Now.AddDays(-1)).ToList();
            }
            catch (Exception ex)
            {
                String msg = ex.Message;
            }
            return(subs);
        }
        protected override void DeleteModels(ICollection <Organization> organizations)
        {
            var currentUser = ExceptionlessUser;

            foreach (var organization in organizations)
            {
                Log.Info().Message("User {0} deleting organization {1} with {2} total events.", currentUser.Id, organization.Id, organization.TotalEventCount).Write();

                if (!String.IsNullOrEmpty(organization.StripeCustomerId))
                {
                    Log.Info().Message("Canceling stripe subscription for the organization '{0}' with Id: '{1}'.", organization.Name, organization.Id).Write();

                    var subscriptionService = new StripeSubscriptionService();
                    var subs = subscriptionService.List(organization.StripeCustomerId).Where(s => !s.CanceledAt.HasValue);
                    foreach (var sub in subs)
                    {
                        subscriptionService.Cancel(organization.StripeCustomerId, sub.Id);
                    }
                }

                List <User> users = _userRepository.GetByOrganizationId(organization.Id).ToList();
                foreach (User user in users)
                {
                    // delete the user if they are not associated to any other organizations and they are not the current user
                    if (user.OrganizationIds.All(oid => String.Equals(oid, organization.Id)) && !String.Equals(user.Id, currentUser.Id))
                    {
                        Log.Info().Message("Removing user '{0}' as they do not belong to any other organizations.", user.Id, organization.Name, organization.Id).Write();
                        _userRepository.Remove(user.Id);
                    }
                    else
                    {
                        Log.Info().Message("Removing user '{0}' from organization '{1}' with Id: '{2}'", user.Id, organization.Name, organization.Id).Write();
                        user.OrganizationIds.Remove(organization.Id);
                        _userRepository.Save(user);
                    }
                }

                List <Project> projects = _projectRepository.GetByOrganizationId(organization.Id).ToList();
                if (User.IsInRole(AuthorizationRoles.GlobalAdmin) && projects.Count > 0)
                {
                    foreach (Project project in projects)
                    {
                        Log.Info().Message("Resetting all project data for project '{0}' with Id: '{1}'.", project.Name, project.Id).Write();
                        _projectController.ResetDataAsync(project.Id).Wait();
                    }

                    Log.Info().Message("Deleting all projects for organization '{0}' with Id: '{1}'.", organization.Name, organization.Id).Write();
                    _projectRepository.Save(projects);
                }

                Log.Info().Message("Deleting organization '{0}' with Id: '{1}'.", organization.Name, organization.Id).Write();
                base.DeleteModels(new[] { organization });
            }
        }
Esempio n. 7
0
        public string CloseCustomerPlan(string customerId)
        {
            var subscriptionService = new StripeSubscriptionService();
            var subscription        = subscriptionService.List(customerId).FirstOrDefault();

            if (subscription == null)
            {
                throw new NullReferenceException("Subscription for stripe customer is not found");
            }
            subscription = subscriptionService.Cancel(customerId, subscription.Id);
            return(subscription.Status);
        }
Esempio n. 8
0
        public subscription_fixture()
        {
            SubscriptionCreateOptions = new StripeSubscriptionCreateOptions
            {
                TrialEnd = DateTime.Now.AddMinutes(5),
                Items    = new List <StripeSubscriptionItemOption>
                {
                    new StripeSubscriptionItemOption {
                        PlanId = Cache.GetPlan().Id, Quantity = 1
                    },
                    new StripeSubscriptionItemOption {
                        PlanId = Cache.GetPlan("silver").Id, Quantity = 2
                    }
                },
                BillingCycleAnchor = DateTime.UtcNow.AddDays(1),
            };

            var service     = new StripeSubscriptionService(Cache.ApiKey);
            var customer_id = Cache.GetCustomer().Id;

            Subscription = service.Create(customer_id, SubscriptionCreateOptions);
            service.Create(customer_id, SubscriptionCreateOptions);
            SubscriptionList = service.List(new StripeSubscriptionListOptions {
                CustomerId = customer_id
            });

            SubscriptionUpdateOptions = new StripeSubscriptionUpdateOptions
            {
                Items = new List <StripeSubscriptionItemUpdateOption>
                {
                    new StripeSubscriptionItemUpdateOption {
                        Id = Subscription.Items.Data[0].Id, Deleted = true
                    },
                    new StripeSubscriptionItemUpdateOption
                    {
                        Id       = Subscription.Items.Data[1].Id,
                        Quantity = 5,
                        Metadata = new Dictionary <string, string> {
                            { "key", "value" }
                        }
                    }
                }
            };

            SubscriptionUpdated = service.Update(Subscription.Id, SubscriptionUpdateOptions);

            SubscriptionEndedOptions = new StripeSubscriptionUpdateOptions
            {
                EndTrialNow = true
            };

            SubscriptionEnded = service.Update(Subscription.Id, SubscriptionEndedOptions);
        }
        // GET: Subscriptions
        public ActionResult Index()
        {
            var userId = User.Identity.GetUserId();
            var user   = UserManager.FindById(userId);

            if (user.SubscriptionId == 0)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            var subscription = db.Subscriptions.Find(user.SubscriptionId);

            if (subscription == null)
            {
                return(HttpNotFound());
            }

            var customerService = new StripeCustomerService();
            var stripeCustomer  = customerService.Get(subscription.StripeCustomerId);

            var subscriptionview = new SubscriptionDetailsViewModel
            {
                AdminEmail     = stripeCustomer.Email,
                CardExpiration = new DateTime(),
                CardLastFour   = "n/a",
                MonthlyPrice   = "n/a",
                SubscribedPlan = "n/a"
            };

            var subscriptionService = new StripeSubscriptionService();
            IEnumerable <StripeSubscription> stripeSubscriptions = subscriptionService.List(subscription.StripeCustomerId);

            if (stripeSubscriptions.Any())
            {
                subscriptionview.SubscribedPlan = stripeSubscriptions.FirstOrDefault().StripePlan.Name;
                subscriptionview.MonthlyPrice   = stripeSubscriptions.FirstOrDefault().StripePlan.Amount.ToString();
            }

            var cardService = new StripeCardService();
            IEnumerable <StripeCard> stripeCards = cardService.List(subscription.StripeCustomerId);

            if (stripeCards.Any())
            {
                var dateString = string.Format("{1}/1/{0}", stripeCards.FirstOrDefault().ExpirationYear,
                                               stripeCards.FirstOrDefault().ExpirationMonth);

                subscriptionview.CardExpiration = DateTime.Parse(dateString);
                subscriptionview.CardLastFour   = "XXXX XXXX XXXX " + stripeCards.FirstOrDefault().Last4;
            }

            return(View(subscriptionview));
        }
Esempio n. 10
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));
        }
        // GET: Purchase
        public async Task <ActionResult> Index()
        {
            var             userId = User.Identity.GetUserId();
            ApplicationUser user   = await UserManager.FindByIdAsync(userId);

            if (!string.IsNullOrEmpty(user.CustomerIdentifier))
            {
                StripeConfiguration.SetApiKey("sk_test_ILBG36E21hK6nO8C6fOpQvWs");
                var subscriptionSerive = new StripeSubscriptionService();
                StripeSubscriptionListOptions listOptions = new StripeSubscriptionListOptions();
                listOptions.CustomerId = user.CustomerIdentifier;
                IEnumerable <StripeSubscription> response = subscriptionSerive.List(listOptions);
                ViewBag.StripeKey = "pk_test_rAvojOoog9JrtM0vSmKm4r0D";
            }
            return(View());
        }
Esempio n. 12
0
        public subscription_fixture()
        {
            SubscriptionCreateOptions = new StripeSubscriptionCreateOptions
            {
                TrialEnd = DateTime.Now.AddMinutes(5),
                Items    = new List <StripeSubscriptionItemOption>
                {
                    new StripeSubscriptionItemOption {
                        PlanId = Cache.GetPlan().Id, Quantity = 1
                    },
                    new StripeSubscriptionItemOption {
                        PlanId = Cache.GetPlan("silver").Id, Quantity = 2
                    }
                }
            };

            var service     = new StripeSubscriptionService(Cache.ApiKey);
            var customer_id = Cache.GetCustomer().Id;

            Subscription = service.Create(customer_id, SubscriptionCreateOptions);
            service.Create(customer_id, SubscriptionCreateOptions);
            SubscriptionList = service.List(new StripeSubscriptionListOptions {
                CustomerId = customer_id
            });

            SubscriptionUpdateOptions = new StripeSubscriptionUpdateOptions
            {
                Items = new List <StripeSubscriptionItemUpdateOption>
                {
                    new StripeSubscriptionItemUpdateOption {
                        Id = Subscription.Items.Data[0].Id, Deleted = true
                    },
                    new StripeSubscriptionItemUpdateOption {
                        Id = Subscription.Items.Data[1].Id, Quantity = 5
                    }
                }
            };

            SubscriptionUpdated = service.Update(Subscription.Id, SubscriptionUpdateOptions);

            SubscriptionEndedOptions = new StripeSubscriptionUpdateOptions
            {
                EndTrialNow = true
            };

            SubscriptionEnded = service.Update(Subscription.Id, SubscriptionEndedOptions);
        }
Esempio n. 13
0
        private void CreateStripeCustomer(string stripeToken, string coupon)
        {
            var customer = new Stripe.StripeCustomerCreateOptions();

            using (var db = InitializeSettings.DbFactory)
            {
                var data = db.Get <Majorsilence.Vpn.Poco.Users>(_userId);


                // If it is the first time the customer has paid we have not created an account yet
                // so do it now.
                customer.Email       = data.Email;
                customer.Description = string.Format("{0} {1} ({2})", data.FirstName, data.LastName, data.Email);
                customer.TokenId     = stripeToken;
                customer.PlanId      = Helpers.SiteInfo.StripePlanId;
                //customer.TrialEnd = DateTime.Now.AddDays(30);
                if (coupon.Trim() != "")
                {
                    customer.CouponId = coupon;
                }
                var customerService = new StripeCustomerService(Helpers.SiteInfo.StripeAPISecretKey);
                var cust            = customerService.Create(customer);

                var subscriptionInfo = new StripeSubscriptionService(Helpers.SiteInfo.StripeAPISecretKey);
                var subscriptionList = subscriptionInfo.List(cust.Id).ToList();

                if (subscriptionList.Count() > 1)
                {
                    throw new Exceptions.StripeSubscriptionException(
                              string.Format("More then one subscription detected for vpn customer: {0}, stripe customer: {1}", _userId, cust.Id)
                              );
                }

                data.StripeCustomerAccount = cust.Id;
                data.StripeSubscriptionId  = subscriptionList.First().Id;



                db.Update(data);
            }
        }
Esempio n. 14
0
        public ActionResult ChangePlan(CustomerChangePlanViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var subscriptionService = new StripeSubscriptionService();
            var subs = subscriptionService.List(model.CustomerId);

            if (subs.Any())
            {
                foreach (var sub in subs)
                {
                    subscriptionService.Cancel(model.CustomerId, sub.Id);
                }
            }

            subscriptionService.Create(model.CustomerId, model.SelectedPlan);

            return(RedirectToAction("Details", new { id = model.CustomerId }));
        }
Esempio n. 15
0
        public string AssignCustomerPlan(string customerId, string planId, string cardNumber,
                                         string cardCvc, int cardExpirationMonth, int cardExpirationYear)
        {
            // Create token
            var token = CreateToken(cardNumber, cardCvc, cardExpirationMonth, cardExpirationYear);

            var subscriptionService = new StripeSubscriptionService();
            var subscription        = subscriptionService.List(customerId).FirstOrDefault();

            if (subscription == null)
            {
                var options = new StripeSubscriptionCreateOptions
                {
                    Card = new StripeCreditCardOptions
                    {
                        TokenId = token.Id
                    },
                    PlanId = planId
                };

                subscription = subscriptionService.Create(customerId, planId, options);
            }
            else
            {
                var options = new StripeSubscriptionUpdateOptions
                {
                    Card = new StripeCreditCardOptions
                    {
                        TokenId = token.Id
                    },
                    PlanId = planId
                };

                subscription = subscriptionService.Update(customerId, subscription.Id, options);
            }


            return(subscription.Status);
        }
Esempio n. 16
0
        private void CreateStripeSubscription(string stripeToken, string coupon)
        {
            using (var db = InitializeSettings.DbFactory)
            {
                var data = db.Get <Majorsilence.Vpn.Poco.Users>(_userId);


                var options = new Stripe.StripeSubscriptionCreateOptions();
                options.TokenId = stripeToken;
                if (coupon.Trim() != "")
                {
                    options.CouponId = coupon;
                }

                var subscriptionService = new StripeSubscriptionService();
                StripeSubscription stripeSubscription = subscriptionService.Create(data.StripeCustomerAccount,
                                                                                   Helpers.SiteInfo.StripePlanId, options);


                var subscriptionInfo = new StripeSubscriptionService(Helpers.SiteInfo.StripeAPISecretKey);
                var subscriptionList = subscriptionInfo.List(data.StripeCustomerAccount).ToList();

                if (subscriptionList.Count() > 1)
                {
                    throw new Exceptions.StripeSubscriptionException(
                              string.Format("More then one subscription detected for vpn customer: {0}, stripe customer: {1}",
                                            _userId, data.StripeCustomerAccount)
                              );
                }



                data.StripeSubscriptionId = subscriptionList.First().Id;

                db.Update(data);
            }
        }
Esempio n. 17
0
        public CancelRecurringPaymentResult CancelRecurringPayment(CancelRecurringPaymentRequest cancelPaymentRequest)
        {
            var result = new CancelRecurringPaymentResult();
            var order  = cancelPaymentRequest.Order;

            try
            {
                var stripeSubscriptionService = new StripeSubscriptionService();

                var customerId            = order.SubscriptionTransactionId;
                var customerSubscriptions = stripeSubscriptionService.List(customerId);
                foreach (var productId in
                         order.OrderItems.Where(orderItem => orderItem.Product.IsRecurring)
                         .Select(orderItem => orderItem.Product.Id.ToString()))
                {
                    stripeSubscriptionService.Cancel(customerId, customerSubscriptions.FirstOrDefault(x => x.StripePlan.Id == productId).Id);
                }
            }
            catch (Exception exception)
            {
                result.AddError(exception.Message);
            }
            return(result);
        }
        public IHttpActionResult ChangePlan(string id, string planId, string stripeToken = null, string last4 = null, string couponId = null)
        {
            if (String.IsNullOrEmpty(id) || !CanAccessOrganization(id))
            {
                return(BadRequest("Invalid organization id."));
            }

            if (!Settings.Current.EnableBilling)
            {
                return(Ok(new { Success = false, Message = "Plans cannot be changed while billing is disabled." }));
            }

            Organization organization = _repository.GetById(id);

            if (organization == null)
            {
                return(Ok(new { Success = false, Message = "Invalid OrganizationId." }));
            }

            BillingPlan plan = BillingManager.GetBillingPlan(planId);

            if (plan == null)
            {
                return(Ok(new { Success = false, Message = "Invalid PlanId." }));
            }

            if (String.Equals(organization.PlanId, plan.Id) && String.Equals(BillingManager.FreePlan.Id, plan.Id))
            {
                return(Ok(new { Success = true, Message = "Your plan was not changed as you were already on the free plan." }));
            }

            // Only see if they can downgrade a plan if the plans are different.
            string message;

            if (!String.Equals(organization.PlanId, plan.Id) && !_billingManager.CanDownGrade(organization, plan, ExceptionlessUser, out message))
            {
                return(Ok(new { Success = false, Message = message }));
            }

            var customerService     = new StripeCustomerService();
            var subscriptionService = new StripeSubscriptionService();

            try {
                // If they are on a paid plan and then downgrade to a free plan then cancel their stripe subscription.
                if (!String.Equals(organization.PlanId, BillingManager.FreePlan.Id) && String.Equals(plan.Id, BillingManager.FreePlan.Id))
                {
                    if (!String.IsNullOrEmpty(organization.StripeCustomerId))
                    {
                        var subs = subscriptionService.List(organization.StripeCustomerId).Where(s => !s.CanceledAt.HasValue);
                        foreach (var sub in subs)
                        {
                            subscriptionService.Cancel(organization.StripeCustomerId, sub.Id);
                        }
                    }

                    organization.BillingStatus = BillingStatus.Trialing;
                    organization.RemoveSuspension();
                }
                else if (String.IsNullOrEmpty(organization.StripeCustomerId))
                {
                    if (String.IsNullOrEmpty(stripeToken))
                    {
                        return(Ok(new { Success = false, Message = "Billing information was not set." }));
                    }

                    organization.SubscribeDate = DateTime.Now;

                    var createCustomer = new StripeCustomerCreateOptions {
                        TokenId     = stripeToken,
                        PlanId      = planId,
                        Description = organization.Name,
                        Email       = ExceptionlessUser.EmailAddress
                    };

                    if (!String.IsNullOrWhiteSpace(couponId))
                    {
                        createCustomer.CouponId = couponId;
                    }

                    StripeCustomer customer = customerService.Create(createCustomer);

                    organization.BillingStatus = BillingStatus.Active;
                    organization.RemoveSuspension();
                    organization.StripeCustomerId = customer.Id;
                    if (customer.StripeCardList.StripeCards.Count > 0)
                    {
                        organization.CardLast4 = customer.StripeCardList.StripeCards[0].Last4;
                    }
                }
                else
                {
                    var update = new StripeSubscriptionUpdateOptions {
                        PlanId = planId
                    };
                    var  create      = new StripeSubscriptionCreateOptions();
                    bool cardUpdated = false;

                    if (!String.IsNullOrEmpty(stripeToken))
                    {
                        update.TokenId = stripeToken;
                        create.TokenId = stripeToken;
                        cardUpdated    = true;
                    }

                    var subscription = subscriptionService.List(organization.StripeCustomerId).FirstOrDefault(s => !s.CanceledAt.HasValue);
                    if (subscription != null)
                    {
                        subscriptionService.Update(organization.StripeCustomerId, subscription.Id, update);
                    }
                    else
                    {
                        subscriptionService.Create(organization.StripeCustomerId, planId, create);
                    }

                    customerService.Update(organization.StripeCustomerId, new StripeCustomerUpdateOptions {
                        Email = ExceptionlessUser.EmailAddress
                    });

                    if (cardUpdated)
                    {
                        organization.CardLast4 = last4;
                    }

                    organization.BillingStatus = BillingStatus.Active;
                    organization.RemoveSuspension();
                }

                _billingManager.ApplyBillingPlan(organization, plan, ExceptionlessUser);
                _repository.Save(organization);

                _messagePublisher.Publish(new PlanChanged {
                    OrganizationId = organization.Id
                });
            } catch (Exception e) {
                Log.Error().Exception(e).Message("An error occurred while trying to update your billing plan: " + e.Message).Report(r => r.MarkAsCritical()).Write();
                return(Ok(new { Success = false, Message = e.Message }));
            }

            return(Ok(new { Success = true }));
        }
Esempio n. 19
0
        public bool BackupData(User user)
        {
            try
            {
                var    startTime        = DateTime.UtcNow;
                string loggerInfoFormat = "User {0} succesfully backuped his data";
                if (user == null || ((user.GoogleDriveAccount == null || !user.GoogleDriveAccount.Enabled) &&
                                     (user.DropboxAccount == null || !user.DropboxAccount.Enabled)) ||
                    ((user.ActiveCampaignAccount == null || !user.ActiveCampaignAccount.Enabled) &&
                     (user.AweberAccount == null || !user.AweberAccount.Enabled) &&
                     (user.InfusionSoftAccount == null || !user.InfusionSoftAccount.Enabled)))
                {
                    throw new Exception();
                }
                OnProgress(new BackupEventArgs("Validation of payment ..."));

                StripeCustomerService        customerService  = new StripeCustomerService();
                IEnumerable <StripeCustomer> customerResponse = customerService.List();
                string customerId = customerResponse.FirstOrDefault(m => m.Email == user.Email).Id;
                StripeSubscriptionService        subscriptionService  = new StripeSubscriptionService();
                IEnumerable <StripeSubscription> subscriptionResponse = subscriptionService.List(customerId);
                StripeSubscription subscription = subscriptionResponse.First();
                string             status       = subscription.Status;
                if (user.Payment == null || status != "active")
                {
                    user.Payment.Status = status;
                    _unitOfWork.Commit();
                    throw new Exception("The payment subscription isn't being processed successfully.");
                }

                OnProgress(new BackupEventArgs("Validation is completed. Getting the data from the connected services ..."));
                string backupedFrom     = "";
                string backupedTo       = "";
                var    backupDataHelper = new BackupDataHelper();

                var sourcesTaskList = new List <Task <bool> >();
                if (user.InfusionSoftAccount != null && user.InfusionSoftAccount.Enabled)
                {
                    sourcesTaskList.Add(Task.Factory.StartNew((x) => InfusionSoft(user, backupDataHelper), null));
                    backupedFrom += "InfusionSoft ";
                }
                if (user.ActiveCampaignAccount != null && user.ActiveCampaignAccount.Enabled)
                {
                    sourcesTaskList.Add(Task.Factory.StartNew((x) => ActiveCampaign(user, backupDataHelper), null));
                    backupedFrom += "ActiveCampaign ";
                }
                if (user.AweberAccount != null && user.AweberAccount.Enabled)
                {
                    sourcesTaskList.Add(Task.Factory.StartNew((x) => Aweber(user, backupDataHelper), null));
                    backupedFrom += "Aweber ";
                }
                if (user.MailChimpAccount != null && user.MailChimpAccount.Enabled)
                {
                    sourcesTaskList.Add(Task.Factory.StartNew((x) => MailChimp(user, backupDataHelper), null));
                    backupedFrom += "MailChimp ";
                }
                if (user.GetResponseAccount != null && user.GetResponseAccount.Enabled)
                {
                    sourcesTaskList.Add(Task.Factory.StartNew((x) => GetResponse(user, backupDataHelper), null));
                    backupedFrom += "GetResponse";
                }
                Task.WaitAll(sourcesTaskList.ToArray());
                int countSuccessAccounts = sourcesTaskList.Count(x => x.Result);
                if (countSuccessAccounts == 0)
                {
                    throw new Exception();
                }

                OnProgress(new BackupEventArgs("Getting the data is completed. Converting to CSV files ..."));
                byte[] data = backupDataHelper.Save();
                OnProgress(new BackupEventArgs("Converting to CSV file is completed. Saving data to the connected services .."));

                var deliverTaskList = new List <Task <bool> >();
                if (user.DropboxAccount != null && user.DropboxAccount.Enabled)
                {
                    deliverTaskList.Add(Task.Factory.StartNew((x) => Dropbox(user, data), null));
                    backupedTo += "Dropbox ";
                }
                if (user.GoogleDriveAccount != null && user.GoogleDriveAccount.Enabled)
                {
                    deliverTaskList.Add(Task.Factory.StartNew((x) => GoogleDrive(user, data), null));
                    backupedTo += "GoogleDrive";
                }

                //Save a copy to server----------------------------------

                System.IO.Directory.CreateDirectory(serverFilePath + user.Email.Replace('@', '_'));
                string path     = Path.Combine(serverFilePath, user.Email.Replace('@', '_'));
                string fileName = "ListDefender " + DateTime.Now + ".zip";

                var invalidChars = Path.GetInvalidFileNameChars();
                fileName = string.Join("", fileName.Select(c => invalidChars.Contains(c) ? '_' : c));

                path = Path.Combine(path, fileName);


                System.IO.File.WriteAllBytes(path, data);

                //-------------------------------------------------------

                Task.WaitAll(deliverTaskList.ToArray());
                int countSuccessDeliverAccounts = deliverTaskList.Count(x => x.Result);
                if (countSuccessDeliverAccounts == 0)
                {
                    throw new Exception();
                }

                user.Backups.Add(new Backup
                {
                    TimeOfBackup = DateTime.UtcNow,
                    BackupedFrom = backupedFrom,
                    BackupedTo   = backupedTo
                });
                _unitOfWork.Commit();
                logger.Info(String.Format(loggerInfoFormat, user.Email));
                var ts = DateTime.UtcNow - startTime;
                OnProgress(new BackupEventArgs("Backup is completed."));
                OnBackupComplete(new BackupEventArgs("Done " + ts.Minutes + ":" + ts.Seconds + ":" + ts.Milliseconds));
                return(true);
            }
            catch (Exception e)
            {
                OnProgress(new BackupEventArgs("Backup fail. " + e.Message));
                OnBackupComplete(new BackupEventArgs(""));
                return(false);
            }
        }
        public ActionResult SubmitSubscribeToStripeSubscriptionForm(StripeSubscriptionCheckout model)
        {
            var loggedOnMember = Members.GetCurrentMember();
            var memberService  = Services.MemberService;
            var member         = memberService.GetById(loggedOnMember.Id);

            var stripeUserId = member.Properties.Contains("stripeUserId")
                ? member.Properties["stripeUserId"].Value as string
                : null;

            try
            {
                //Add subscription
                var subscriptionService = new StripeSubscriptionService(SensativeInformation.StripeKeys.SecretKey);
                var listOptions         = new StripeSubscriptionListOptions {
                    CustomerId = stripeUserId
                };
                var stripeSubscriptions = subscriptionService.List(listOptions);
                var update = stripeSubscriptions.Any(m => m.Status == StripeSubscriptionStatuses.Active);

                //if existingsubscripton update else create a new subscription
                if (update)
                {
                    var subscription =
                        stripeSubscriptions.FirstOrDefault(m => m.Status == StripeSubscriptionStatuses.Active);
                    if (subscription != null)
                    {
                        StripeSubscriptionUpdateOptions so = new StripeSubscriptionUpdateOptions {
                            PlanId = model.PlanId
                        };
                        so.PlanId = model.PlanId;

                        subscriptionService.Update(subscription.Id, so);
                        TempData["SuccessMessage"] =
                            "Congratulations! You have subscribed successfully. No more worrying about subs :)";
                        return(RedirectToCurrentUmbracoPage());
                    }
                    else
                    {
                        _log.Error(
                            $"Tried to update a stripe subsciption for user with id {member.Id} but could not find any stripe subscriptions for this user.");
                        ModelState.AddModelError("",
                                                 "There was an error upgrading your subscription. Please try again. If the issue persists please contact us");
                        return(CurrentUmbracoPage());
                    }
                }
                else
                {
                    StripeSubscription stripeSubscription = subscriptionService.Create(stripeUserId, model.PlanId);
                    TempData["SuccessMessage"] =
                        "Congratulations! You have subscribed successfully. No more worrying about subs :)";
                    return(RedirectToCurrentUmbracoPage());
                }
            }
            catch (StripeException e)
            {
                _log.Error(e.StripeError.Message);
                ModelState.AddModelError("",
                                         "There was an error setting up your subscription. Please try again. If the issue persists please contact us");
            }
            return(CurrentUmbracoPage());
        }
Esempio n. 21
0
        public async Task <IHttpActionResult> ChangePlanAsync(string id, string planId, string stripeToken = null, string last4 = null, string couponId = null)
        {
            if (String.IsNullOrEmpty(id) || !CanAccessOrganization(id))
            {
                return(NotFound());
            }

            if (!Settings.Current.EnableBilling)
            {
                return(Ok(ChangePlanResult.FailWithMessage("Plans cannot be changed while billing is disabled.")));
            }

            Organization organization = await _repository.GetByIdAsync(id);

            if (organization == null)
            {
                return(Ok(ChangePlanResult.FailWithMessage("Invalid OrganizationId.")));
            }

            BillingPlan plan = BillingManager.GetBillingPlan(planId);

            if (plan == null)
            {
                return(Ok(ChangePlanResult.FailWithMessage("Invalid PlanId.")));
            }

            if (String.Equals(organization.PlanId, plan.Id) && String.Equals(BillingManager.FreePlan.Id, plan.Id))
            {
                return(Ok(ChangePlanResult.SuccessWithMessage("Your plan was not changed as you were already on the free plan.")));
            }

            // Only see if they can downgrade a plan if the plans are different.
            if (!String.Equals(organization.PlanId, plan.Id))
            {
                var result = await _billingManager.CanDownGradeAsync(organization, plan, ExceptionlessUser);

                if (!result.Success)
                {
                    return(Ok(result));
                }
            }

            var customerService     = new StripeCustomerService(Settings.Current.StripeApiKey);
            var subscriptionService = new StripeSubscriptionService(Settings.Current.StripeApiKey);

            try {
                // If they are on a paid plan and then downgrade to a free plan then cancel their stripe subscription.
                if (!String.Equals(organization.PlanId, BillingManager.FreePlan.Id) && String.Equals(plan.Id, BillingManager.FreePlan.Id))
                {
                    if (!String.IsNullOrEmpty(organization.StripeCustomerId))
                    {
                        var subs = subscriptionService.List(organization.StripeCustomerId).Where(s => !s.CanceledAt.HasValue);
                        foreach (var sub in subs)
                        {
                            subscriptionService.Cancel(organization.StripeCustomerId, sub.Id);
                        }
                    }

                    organization.BillingStatus = BillingStatus.Trialing;
                    organization.RemoveSuspension();
                }
                else if (String.IsNullOrEmpty(organization.StripeCustomerId))
                {
                    if (String.IsNullOrEmpty(stripeToken))
                    {
                        return(Ok(ChangePlanResult.FailWithMessage("Billing information was not set.")));
                    }

                    organization.SubscribeDate = DateTime.Now;

                    var createCustomer = new StripeCustomerCreateOptions {
                        Card = new StripeCreditCardOptions {
                            TokenId = stripeToken
                        },
                        PlanId      = planId,
                        Description = organization.Name,
                        Email       = ExceptionlessUser.EmailAddress
                    };

                    if (!String.IsNullOrWhiteSpace(couponId))
                    {
                        createCustomer.CouponId = couponId;
                    }

                    StripeCustomer customer = customerService.Create(createCustomer);

                    organization.BillingStatus = BillingStatus.Active;
                    organization.RemoveSuspension();
                    organization.StripeCustomerId = customer.Id;
                    if (customer.StripeCardList.StripeCards.Count > 0)
                    {
                        organization.CardLast4 = customer.StripeCardList.StripeCards[0].Last4;
                    }
                }
                else
                {
                    var update = new StripeSubscriptionUpdateOptions {
                        PlanId = planId
                    };
                    var  create      = new StripeSubscriptionCreateOptions();
                    bool cardUpdated = false;

                    if (!String.IsNullOrEmpty(stripeToken))
                    {
                        update.Card = new StripeCreditCardOptions {
                            TokenId = stripeToken
                        };
                        create.Card = new StripeCreditCardOptions {
                            TokenId = stripeToken
                        };
                        cardUpdated = true;
                    }

                    var subscription = subscriptionService.List(organization.StripeCustomerId).FirstOrDefault(s => !s.CanceledAt.HasValue);
                    if (subscription != null)
                    {
                        subscriptionService.Update(organization.StripeCustomerId, subscription.Id, update);
                    }
                    else
                    {
                        subscriptionService.Create(organization.StripeCustomerId, planId, create);
                    }

                    customerService.Update(organization.StripeCustomerId, new StripeCustomerUpdateOptions {
                        Email = ExceptionlessUser.EmailAddress
                    });

                    if (cardUpdated)
                    {
                        organization.CardLast4 = last4;
                    }

                    organization.BillingStatus = BillingStatus.Active;
                    organization.RemoveSuspension();
                }

                BillingManager.ApplyBillingPlan(organization, plan, ExceptionlessUser);
                await _repository.SaveAsync(organization);

                await _messagePublisher.PublishAsync(new PlanChanged { OrganizationId = organization.Id });
            } catch (Exception e) {
                Logger.Error().Exception(e).Message("An error occurred while trying to update your billing plan: " + e.Message).Critical().Identity(ExceptionlessUser.EmailAddress).Property("User", ExceptionlessUser).SetActionContext(ActionContext).Write();
                return(Ok(ChangePlanResult.FailWithMessage(e.Message)));
            }

            return(Ok(new ChangePlanResult {
                Success = true
            }));
        }
Esempio n. 22
0
        public override async Task HandleItemAsync(WorkItemContext context)
        {
            var workItem = context.GetData <RemoveOrganizationWorkItem>();

            Log.Info("Received remove organization work item for: {0}", workItem.OrganizationId);

            await context.ReportProgressAsync(0, "Starting deletion...").AnyContext();

            var organization = await _organizationRepository.GetByIdAsync(workItem.OrganizationId).AnyContext();

            if (organization == null)
            {
                await context.ReportProgressAsync(100, "Organization deleted").AnyContext();

                return;
            }

            await context.ReportProgressAsync(10, "Removing subscriptions").AnyContext();

            if (!String.IsNullOrEmpty(organization.StripeCustomerId))
            {
                Log.Info("Canceling stripe subscription for the organization '{0}' with Id: '{1}'.", organization.Name, organization.Id);

                var subscriptionService = new StripeSubscriptionService(Settings.Current.StripeApiKey);
                var subscriptions       = subscriptionService.List(organization.StripeCustomerId).Where(s => !s.CanceledAt.HasValue);
                foreach (var subscription in subscriptions)
                {
                    subscriptionService.Cancel(organization.StripeCustomerId, subscription.Id);
                }
            }

            await context.ReportProgressAsync(20, "Removing users").AnyContext();

            var users = await _userRepository.GetByOrganizationIdAsync(organization.Id).AnyContext();

            foreach (User user in users.Documents)
            {
                // delete the user if they are not associated to any other organizations and they are not the current user
                if (user.OrganizationIds.All(oid => String.Equals(oid, organization.Id)) && !String.Equals(user.Id, workItem.CurrentUserId))
                {
                    Log.Info("Removing user '{0}' as they do not belong to any other organizations.", user.Id, organization.Name, organization.Id);
                    await _userRepository.RemoveAsync(user.Id).AnyContext();
                }
                else
                {
                    Log.Info("Removing user '{0}' from organization '{1}' with Id: '{2}'", user.Id, organization.Name, organization.Id);
                    user.OrganizationIds.Remove(organization.Id);
                    await _userRepository.SaveAsync(user, true).AnyContext();
                }
            }

            await context.ReportProgressAsync(30, "Removing tokens").AnyContext();

            await _tokenRepository.RemoveAllByOrganizationIdAsync(organization.Id).AnyContext();

            await context.ReportProgressAsync(40, "Removing web hooks").AnyContext();

            await _webHookRepository.RemoveAllByOrganizationIdAsync(organization.Id).AnyContext();

            await context.ReportProgressAsync(50, "Removing projects").AnyContext();

            var projects = await _projectRepository.GetByOrganizationIdAsync(organization.Id).AnyContext();

            if (workItem.IsGlobalAdmin && projects.Total > 0)
            {
                var completed = 1;
                foreach (Project project in projects.Documents)
                {
                    Log.Info("Resetting all project data for project '{0}' with Id: '{1}'.", project.Name, project.Id);
                    await _eventRepository.RemoveAllByProjectIdAsync(organization.Id, project.Id).AnyContext();

                    await _stackRepository.RemoveAllByProjectIdAsync(organization.Id, project.Id).AnyContext();

                    await context.ReportProgressAsync(CalculateProgress(projects.Total, completed++, 51, 89), "Removing projects...").AnyContext();
                }

                Log.Info("Deleting all projects for organization '{0}' with Id: '{1}'.", organization.Name, organization.Id);
                await _projectRepository.RemoveAsync(projects.Documents).AnyContext();
            }

            Log.Info("Deleting organization '{0}' with Id: '{1}'.", organization.Name, organization.Id);
            await context.ReportProgressAsync(90, "Removing organization").AnyContext();

            await _organizationRepository.RemoveAsync(organization.Id).AnyContext();

            await context.ReportProgressAsync(100, "Organization deleted").AnyContext();
        }
		public IEnumerable<StripeSubscription> List(string customerId, StripeListOptions listOptions = null)
		{
			return _stripeSubscriptionService.List(customerId, listOptions);
		}