Наследование: Stripe.StripeService
Пример #1
0
        public void Cancel(PawzeUser pawzeUser, Subscription pawzeSubscription)
        {
            var subscriptionService         = new Stripe.StripeSubscriptionService(APIKey);
            StripeSubscription subscription = subscriptionService.Cancel(pawzeUser.StripeCustomerId, pawzeSubscription.StripeSubscriptionId);

            pawzeSubscription.StripeSubscriptionId = null;

            _subscriptionRepository.Update(pawzeSubscription);

            _unitOfWork.Commit();
        }
Пример #2
0
    public static string CancelSubscription(int userId)
    {
        Users user = Users.LoadById(userId);
        try
        {
            var subscriptionService = new StripeSubscriptionService();
            foreach (StripeSubscription subscription in subscriptionService.List(user.StripeCustomerId))
            {
                user.Ended = subscription.PeriodEnd;
                user.Cancelled = true;
                user.Save();

                subscriptionService.Cancel(user.StripeCustomerId, subscription.Id);
            }
        }
        catch(Exception ex)
        {
            return "Error: " + ex.Message;
        }
        return "";
    }
Пример #3
0
        /// <summary>
        /// Before calling this method - make sure you have saved the box to the database
        /// </summary>
        public void Create(PawzeUser pawzeUser, Box box, string token)
        {
            if (string.IsNullOrEmpty(pawzeUser.StripeCustomerId))
            {
                var customerService = new StripeCustomerService(APIKey);

                var customer = customerService.Create(new StripeCustomerCreateOptions
                {
                    Email = pawzeUser.Email
                });

                pawzeUser.StripeCustomerId = customer.Id;
            }

            var subscriptionService = new Stripe.StripeSubscriptionService(APIKey);

            StripeSubscription subscription = subscriptionService.Create(pawzeUser.StripeCustomerId, "box", new StripeSubscriptionCreateOptions
            {
                Card = new StripeCreditCardOptions
                {
                    TokenId = token
                }
            });

            var pawzeSubscription = new Subscription
            {
                PawzeUserId          = pawzeUser.Id,
                StartDate            = DateTime.Now,
                StripeSubscriptionId = subscription.Id
            };

            pawzeSubscription.Boxes.Add(box);

            _subscriptionRepository.Add(pawzeSubscription);

            _unitOfWork.Commit();
        }
        public override async Task HandleItemAsync(WorkItemContext context) {
            var workItem = context.GetData<RemoveOrganizationWorkItem>();
            Logger.Info().Message($"Received remove organization work item for: {workItem.OrganizationId}").Write();

            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)) {
                Logger.Info().Message($"Canceling stripe subscription for the organization '{organization.Name}' with Id: '{organization.Id}'.").Write();

                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)) {
                    Logger.Info().Message("Removing user '{0}' as they do not belong to any other organizations.", user.Id, organization.Name, organization.Id).Write();
                    await _userRepository.RemoveAsync(user.Id).AnyContext();
                } else {
                    Logger.Info().Message("Removing user '{0}' from organization '{1}' with Id: '{2}'", user.Id, organization.Name, organization.Id).Write();
                    user.OrganizationIds.Remove(organization.Id);
                    await _userRepository.SaveAsync(user, true).AnyContext();
                }
            }

            await context.ReportProgressAsync(30, "Removing tokens").AnyContext();
            await _tokenRepository.RemoveAllByOrganizationIdsAsync(new[] { organization.Id }).AnyContext();

            await context.ReportProgressAsync(40, "Removing web hooks").AnyContext();
            await _webHookRepository.RemoveAllByOrganizationIdsAsync(new[] { 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) {
                    Logger.Info().Message("Resetting all project data for project '{0}' with Id: '{1}'.", project.Name, project.Id).Write();
                    await _eventRepository.RemoveAllByProjectIdsAsync(new[] { project.Id }).AnyContext();
                    await _stackRepository.RemoveAllByProjectIdsAsync(new[] { project.Id }).AnyContext();
                    await context.ReportProgressAsync(CalculateProgress(projects.Total, completed++, 51, 89), "Removing projects...").AnyContext();
                }

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

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

            await context.ReportProgressAsync(100, "Organization deleted").AnyContext();
        }
 public SubscriptionService(ApplicationUserManager userManager, StripeCustomerService customerService, StripeSubscriptionService subscriptionService)
 {
     this.userManager = userManager;
     this.customerService = customerService;
     this.subscriptionService = subscriptionService;
 }
        public async Task<ActionResult> CancelSubscription()
        {          
            await Task.Run(() =>
            {
                var hasSubscription = getCustomer().HasSubscription;
                if(hasSubscription == true)
                {
                    var uStripeCustomer = getCustomer();
                    var stripeCustomerID = uStripeCustomer.StripeCustomerID;
                    var subscriptionID = uStripeCustomer.StripeSubscriptionID;                    
                  
                    if (uStripeCustomer.SubscriptionType == "ultimate")
                    {
                        // cancel subscription in stripe.com
                        var subscriptionService = new StripeSubscriptionService();
                        subscriptionService.Cancel(stripeCustomerID, subscriptionID);

                        // delete stripe customer as well
                        var customerService = new StripeCustomerService();
                        StripeCustomer customerToDelete = customerService.Get(stripeCustomerID);
                        customerService.Delete(customerToDelete.Id);

                        db.StripeCustomers.Remove(uStripeCustomer); //db
                    }
                    else if (uStripeCustomer.SubscriptionType == "standard")
                    {
                        // cancel subscription in stripe.com
                        var subscriptionService = new StripeSubscriptionService();
                        subscriptionService.Cancel(stripeCustomerID, subscriptionID);

                        // delete stripe customer as well
                        var customerService = new StripeCustomerService();
                        StripeCustomer customerToDelete = customerService.Get(stripeCustomerID);
                        customerService.Delete(customerToDelete.Id);

                        uStripeCustomer.HasSubscription = false; //db
                    }
                    db.SaveChanges();                  
                }
            });
         
            return RedirectToAction("Index", "Home");
        }
        public async Task<ActionResult> DowngradePlan()
        {
            await Task.Run(() =>
            {
                var cust = getCustomer();

                if (cust != null) // downgrade
                {
                    // retrieve customer
                    var customerService = new StripeCustomerService();
                    StripeCustomer currentCustomer = customerService.Get(cust.StripeCustomerID);

                    // change plan
                    StripeSubscriptionService subService = new StripeSubscriptionService();
                    StripeSubscriptionUpdateOptions updateOptions = new StripeSubscriptionUpdateOptions();
                    updateOptions.PlanId = "standard";
                    updateOptions.TrialEnd = currentTime; // no free days allowed when downgrading

                    var myUpdateSuscription = subService.Update(currentCustomer.Id, cust.StripeSubscriptionID, updateOptions);

                    // record changes in db
                    StripeCustomers newRecord = new StripeCustomers();

                    newRecord.StripeCustomerID = myUpdateSuscription.CustomerId;
                    newRecord.CustomerName = User.Identity.Name;
                    newRecord.StripeSubscriptionID = cust.StripeSubscriptionID;
                    newRecord.SubscriptionType = "standard";
                    newRecord.TrialValidUntil = currentTime;
                    newRecord.HasSubscription = true;
                    newRecord.StartDate = currentTime;
                    newRecord.Interval = "Monthly";

                    db.StripeCustomers.Add(newRecord);
                    db.StripeCustomers.Remove(cust);
                    db.SaveChanges();
                }
            });
            return RedirectToAction("Index", "Home");
        }
Пример #8
0
        /// <summary>
        /// Unsubscribes the given subscription
        /// NOTE: Save changes on the underlying context for the model after calling this method
        /// </summary>
        /// <param name="subscription"></param>
        public static void Unsubscribe(IStripeUser user, IStripeSubscription subscription)
        {
            if (string.IsNullOrEmpty(subscription.PaymentSystemId) || string.IsNullOrEmpty(user.PaymentSystemId))
                return;

            var subscriptionService = new StripeSubscriptionService();
            subscriptionService.Cancel(subscription.PaymentSystemId, user.PaymentSystemId);
            subscription.PaymentSystemId = null;

            System.Diagnostics.Trace.TraceInformation("Unsuscribed customer in stripe: '{0}' with new subscription id '{1}", user.Email, subscription.PaymentSystemId);
        }
Пример #9
0
        /// <summary>
        /// Changes the given subscription to use the new plan
        /// </summary>
        /// <param name="subscription"></param>
        /// <param name="newPlan"></param>
        public static void ChangeSubscriptionPlan(IStripeUser user, IStripeSubscription subscription, IStripeSubscriptionPlan newPlan)
        {
            StripeSubscriptionUpdateOptions options = new StripeSubscriptionUpdateOptions() { PlanId = newPlan.PaymentSystemId };

            var subscriptionService = new StripeSubscriptionService();
            subscriptionService.Update(user.PaymentSystemId, subscription.PaymentSystemId, options);

            System.Diagnostics.Trace.TraceInformation("Changed subscription for customer in stripe: '{0}' with new subscription id '{1}", user.Email, subscription.PaymentSystemId);
        }
Пример #10
0
        /// <summary>
        /// Subscribes the given user to the given plan, using the payment information already in stripe for that user
        /// NOTE: Save changes on the underlying context for the model after calling this method
        /// </summary>
        /// <param name="subscription"></param>
        public static void Subscribe(IStripeUser user, IStripeSubscription subscription, IStripeSubscriptionPlan plan)
        {
            if (!string.IsNullOrEmpty(subscription.PaymentSystemId))
                return;

            var subscriptionService = new StripeSubscriptionService();
            StripeSubscription stripeSubscription = subscriptionService.Create(user.PaymentSystemId, plan.PaymentSystemId);
            subscription.PaymentSystemId = stripeSubscription.Id;

            System.Diagnostics.Trace.TraceInformation("Subscribed customer in stripe: '{0}' with new subscription id '{1}", user.Email, subscription.PaymentSystemId);
        }
Пример #11
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SubscriptionProvider"/> class.
 /// </summary>
 /// <param name="apiKey">The API key.</param>
 public SubscriptionProvider(string apiKey)
 {
     this._subscriptionService = new StripeSubscriptionService(apiKey);
 }
Пример #12
0
 public StripeAccessorService(StripeSubscriptionService subService, StripeChargeService charService, StripeCustomerService cusService)
 {
     this.subService = subService;
     this.charService = charService;
     this.cusService = cusService;
 }
Пример #13
0
        public void ChargeFromExistingDetails(int existingPlanID, int quantities, string couponID)
        {
            // get selected plan
            User userObj = (User)Session["user"];
            var planID = accountRepo.Accounts.FirstOrDefault(aid => aid.ID == userObj.AccountID).PlanID;

            // get selected plan details
            Plan selectedPlanName = new Plan();
            selectedPlanName = planRepository.Plans.FirstOrDefault(pid => pid.ID == planID);

            // get Existing plan name
            var existingPlan = planRepository.Plans.FirstOrDefault(pid => pid.ID == existingPlanID);

            var customerService = new StripeCustomerService();
            customerService.ApiKey = "sk_test_4Xusc3Meo8gniONh6dDRZvlp";

            var currentAccountDetails = accountRepo.Accounts.FirstOrDefault(aid => aid.ID == userObj.AccountID);
            if (currentAccountDetails.StripeCustomerID != null)
            {
                //update subscription
                var subscribeDetails = customerService.Get(currentAccountDetails.StripeCustomerID);
                var allCurrentSubscriptions = subscribeDetails.StripeSubscriptionList.StripeSubscriptions.Where(sid => sid.CustomerId == currentAccountDetails.StripeCustomerID).ToList();
                var subID = "";
                try
                {
                    subID = subscribeDetails.StripeSubscriptionList.StripeSubscriptions.FirstOrDefault(sid => sid.CustomerId == currentAccountDetails.StripeCustomerID && sid.StripePlan.Name == existingPlan.Name).Id;
                }
                catch(Exception ex)
                {
                    subID = subscribeDetails.StripeSubscriptionList.StripeSubscriptions.FirstOrDefault(sid => sid.CustomerId == currentAccountDetails.StripeCustomerID && sid.StripePlan.Name == "Empty Plan").Id;
                }

                var subs = new StripeSubscriptionService();
                subs.ApiKey = "sk_test_4Xusc3Meo8gniONh6dDRZvlp";
                if (couponID != "")
                {
                    var updateRes = subs.Update(currentAccountDetails.StripeCustomerID, subID, new StripeSubscriptionUpdateOptions() { PlanId = selectedPlanName.Name, Quantity = quantities, CouponId = couponID });
                }
                else
                {
                    var updateRes = subs.Update(currentAccountDetails.StripeCustomerID, subID, new StripeSubscriptionUpdateOptions() { PlanId = selectedPlanName.Name, Quantity = quantities});
                }

            }
        }