Exemplo n.º 1
0
        public async Task ReinstateSubscriptionAsync(Guid organizationId)
        {
            var organization = await _organizationRepository.GetByIdAsync(organizationId);

            if (organization == null)
            {
                throw new NotFoundException();
            }

            if (string.IsNullOrWhiteSpace(organization.StripeSubscriptionId))
            {
                throw new BadRequestException("Organization has no subscription.");
            }

            var subscriptionService = new StripeSubscriptionService();
            var sub = await subscriptionService.GetAsync(organization.StripeSubscriptionId);

            if (sub == null)
            {
                throw new BadRequestException("Organization subscription was not found.");
            }

            if (sub.Status != "active" || !sub.CanceledAt.HasValue)
            {
                throw new BadRequestException("Organization subscription is not marked for cancellation.");
            }

            // Just touch the subscription.
            var updatedSub = await subscriptionService.UpdateAsync(sub.Id, new StripeSubscriptionUpdateOptions { });

            if (updatedSub.CanceledAt.HasValue)
            {
                throw new BadRequestException("Unable to reinstate subscription.");
            }
        }
Exemplo n.º 2
0
        public StripeSubscription CreateSubscription(PurchaseInformation info, string customerIdOfStripe)
        {
            try
            {
                var customer = new StripeCustomerUpdateOptions();

                customer.SourceCard = new SourceCard()
                {
                    Number          = info.CC_number,
                    ExpirationYear  = Convert.ToInt32(info.ExpireYear),
                    ExpirationMonth = Convert.ToInt32(info.ExpireMonth),
                    Cvc             = info.CCVCode,
                    Name            = info.NameOnCard
                };


                if (!string.IsNullOrEmpty(info.Coupon))
                {
                    customer.Coupon = info.Coupon;
                }


                var            customerService = new StripeCustomerService();
                StripeCustomer stripeCustomer  = customerService.Update(customerIdOfStripe, customer);

                var subscriptionService = new StripeSubscriptionService();
                StripeSubscription stripeSubscription = subscriptionService.Create(customerIdOfStripe, info.PlanId); // optional StripeSubscriptionCreateOptions
                return(stripeSubscription);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public StripeSubscriptionServiceTest()
        {
            this.service = new StripeSubscriptionService();

            this.createOptions = new StripeSubscriptionCreateOptions()
            {
                Items = new List <StripeSubscriptionItemOption>
                {
                    new StripeSubscriptionItemOption
                    {
                        PlanId   = "plan_123",
                        Quantity = 2
                    },
                    new StripeSubscriptionItemOption
                    {
                        PlanId   = "plan_124",
                        Quantity = 3
                    },
                },
            };

            this.updateOptions = new StripeSubscriptionUpdateOptions()
            {
                Metadata = new Dictionary <string, string>()
                {
                    { "key", "value" },
                },
            };

            this.listOptions = new StripeSubscriptionListOptions()
            {
                Limit = 1,
            };
        }
Exemplo n.º 4
0
        public async Task ReinstateSubscriptionAsync(ISubscriber subscriber)
        {
            if (subscriber == null)
            {
                throw new ArgumentNullException(nameof(subscriber));
            }

            if (string.IsNullOrWhiteSpace(subscriber.GatewaySubscriptionId))
            {
                throw new GatewayException("No subscription.");
            }

            var subscriptionService = new StripeSubscriptionService();
            var sub = await subscriptionService.GetAsync(subscriber.GatewaySubscriptionId);

            if (sub == null)
            {
                throw new GatewayException("Subscription was not found.");
            }

            if ((sub.Status != "active" && sub.Status != "trialing") || !sub.CanceledAt.HasValue)
            {
                throw new GatewayException("Subscription is not marked for cancellation.");
            }

            // Just touch the subscription.
            var updatedSub = await subscriptionService.UpdateAsync(sub.Id, new StripeSubscriptionUpdateOptions { });

            if (updatedSub.CanceledAt.HasValue)
            {
                throw new GatewayException("Unable to reinstate subscription.");
            }
        }
Exemplo n.º 5
0
        public creating_and_updating_subscriptions_with_manual_invoicing()
        {
            var customerService     = new StripeCustomerService(Cache.ApiKey);
            var subscriptionService = new StripeSubscriptionService(Cache.ApiKey);

            var CustomerCreateOptions = new StripeCustomerCreateOptions
            {
                Email = "*****@*****.**",
            };
            var Customer = customerService.Create(CustomerCreateOptions);

            var SubscriptionCreateOptions = new StripeSubscriptionCreateOptions
            {
                Billing      = StripeBilling.SendInvoice,
                DaysUntilDue = 7,
                PlanId       = Cache.GetPlan("silver").Id
            };

            SubscriptionCreated = subscriptionService.Create(Customer.Id, SubscriptionCreateOptions);

            var SubscriptionUpdateOptions = new StripeSubscriptionUpdateOptions
            {
                DaysUntilDue = 2,
            };

            SubscriptionUpdated = subscriptionService.Update(SubscriptionCreated.Id, SubscriptionUpdateOptions);
        }
Exemplo n.º 6
0
        public async Task <BillingInfo.BillingInvoice> GetUpcomingInvoiceAsync(ISubscriber subscriber)
        {
            if (!string.IsNullOrWhiteSpace(subscriber.GatewaySubscriptionId))
            {
                var subscriptionService = new StripeSubscriptionService();
                var invoiceService      = new StripeInvoiceService();
                var sub = await subscriptionService.GetAsync(subscriber.GatewaySubscriptionId);

                if (sub != null)
                {
                    if (!sub.CanceledAt.HasValue && !string.IsNullOrWhiteSpace(subscriber.GatewayCustomerId))
                    {
                        try
                        {
                            var upcomingInvoice = await invoiceService.UpcomingAsync(subscriber.GatewayCustomerId);

                            if (upcomingInvoice != null)
                            {
                                return(new BillingInfo.BillingInvoice(upcomingInvoice));
                            }
                        }
                        catch (StripeException) { }
                    }
                }
            }
            return(null);
        }
Exemplo n.º 7
0
        public void CancelSubscription()
        {
            Helpers.SslSecurity.Callback();

            var customerDetails = GetSavedCustomerStripeDetails();

            if (customerDetails != null)
            {
                var subscriptionService = new StripeSubscriptionService(Helpers.SiteInfo.StripeAPISecretKey);
                subscriptionService.Cancel(customerDetails.Item1, customerDetails.Item2);
            }

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

                this.email.SendMail_BackgroundThread("Your vpn account subscription has been cancelled.  " +
                                                     "You will not be billed again.  You will continue to have access until your current payment expires.",
                                                     "VPN Account Subscription Cancelled", data.Email, true, null, Majorsilence.Vpn.Logic.Email.EmailTemplates.Generic);
            }

            if (customerDetails == null)
            {
                throw new Exceptions.InvalidDataException("Attempting to cancel an account but the customer does not have any stripe details.  Only removed from database.  Nothing removed from stripe.");
            }
        }
Exemplo n.º 8
0
        public StripeSubscription SubscribeToPlan(ApplicationUser dbUser, string stripeToken, string planToSubscribeTo)
        {
            StripeCustomer customer = CreateStripeCustomer(dbUser, stripeToken);
            var            currentSubscriptionId = String.Empty;

            if (customer.Subscriptions != null && customer.Subscriptions.TotalCount > 0)
            {
                currentSubscriptionId = customer.Subscriptions.Data[0].Id;
            }

            var service = new StripeSubscriptionService();
            StripeSubscription subscription = null;

            if (String.IsNullOrEmpty(currentSubscriptionId))
            {
                subscription = AddNewUserSubscription(customer.Id, planToSubscribeTo, service, dbUser);
            }
            else if (!planToSubscribeTo.Contains("Free"))
            {
                subscription = UpdateUserSubscription(customer.Id, currentSubscriptionId, planToSubscribeTo, service, dbUser);
            }
            else
            {
                CancleCustomerSubscription(dbUser);
            }

            return(subscription);
        }
Exemplo n.º 9
0
        public void CancelSubscription()
        {
            var user        = AuthHelper.GetCurrentUser();
            var usermanager = AuthHelper.GetUserManager();

            try
            {
                var cust = new StripeCustomerService().Get(user.StripeCustomerId);
                if (cust != null)
                {
                    var sub_svc = new StripeSubscriptionService();
                    var sub     = sub_svc.Get(cust.Id, cust.StripeSubscriptionList.Data[0].Id);

                    sub_svc.Cancel(cust.Id, sub.Id, true);
                }
                else
                {
                    throw new ApplicationException("Could not find the customer in stripe to change the plan");
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 10
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));
        }
Exemplo n.º 11
0
        public usage_record_fixture()
        {
            var subOptions = new StripeSubscriptionCreateOptions
            {
                Items = new List <StripeSubscriptionItemOption>
                {
                    new StripeSubscriptionItemOption {
                        PlanId = Cache.GetPlan("Metered Plan", "metered").Id
                    }
                }
            };

            var service              = new StripeSubscriptionService(Cache.ApiKey);
            var customer_id          = Cache.GetCustomer().Id;
            var subscription         = service.Create(customer_id, subOptions);
            var subscription_item_id = subscription.Items.Data[0].Id;

            UsageRecordCreateOptions = new StripeUsageRecordCreateOptions()
            {
                Action           = "increment",
                SubscriptionItem = subscription_item_id,
                Timestamp        = DateTime.Now,
                Quantity         = 2000
            };

            var usageRecordService = new StripeUsageRecordService(Cache.ApiKey);

            UsageRecord = usageRecordService.Create(UsageRecordCreateOptions);
        }
Exemplo n.º 12
0
        public async Task CancelAndRecoverChargesAsync(ISubscriber subscriber)
        {
            if (!string.IsNullOrWhiteSpace(subscriber.GatewaySubscriptionId))
            {
                var subscriptionService = new StripeSubscriptionService();
                await subscriptionService.CancelAsync(subscriber.GatewaySubscriptionId, false);
            }

            if (string.IsNullOrWhiteSpace(subscriber.GatewayCustomerId))
            {
                return;
            }

            var chargeService = new StripeChargeService();
            var charges       = await chargeService.ListAsync(new StripeChargeListOptions
            {
                CustomerId = subscriber.GatewayCustomerId
            });

            if (charges?.Data != null)
            {
                var refundService = new StripeRefundService();
                foreach (var charge in charges.Data.Where(c => !c.Refunded))
                {
                    await refundService.CreateAsync(charge.Id);
                }
            }

            var customerService = new StripeCustomerService();
            await customerService.DeleteAsync(subscriber.GatewayCustomerId);
        }
Exemplo n.º 13
0
        private static bool ChangeSubscription(StripeSubscription subscription, string option)
        {
            try
            {
                var subscriptionService = new StripeSubscriptionService();

                var subscriptionToChange = (Subscriptions)(int.Parse(option));
                var actualSubscription   = (Subscriptions)Enum.Parse(typeof(Subscriptions), subscription.Items.Data.First().Plan.Id);

                var isUpgrade = subscriptionToChange > actualSubscription ? true : false;

                var updateSubscription = new StripeSubscriptionUpdateOptions()
                {
                    Items = new List <StripeSubscriptionItemUpdateOption>()
                    {
                        new StripeSubscriptionItemUpdateOption()
                        {
                            Id     = subscription.Items.Data.First().Id,
                            PlanId = subscriptionToChange.ToString()
                        }
                    },
                    Prorate = isUpgrade
                };

                StripeSubscription updatedSubscription = subscriptionService.Update(subscription.Id, updateSubscription);

                return(true);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"An error ocurred while updating your subscription.\nError: { ex.Message }");
                return(false);
            }
        }
Exemplo n.º 14
0
        public subscription_fixture()
        {
            SubscriptionCreateOptions = new StripeSubscriptionCreateOptions
            {
                Items = new List <StripeSubscriptionItemOption>
                {
                    new StripeSubscriptionItemOption {
                        PlanId = Cache.GetPlan().Id, Quantity = 1
                    },
                    new StripeSubscriptionItemOption {
                        PlanId = Cache.GetPlan2().Id, Quantity = 2
                    }
                }
            };

            var service = new StripeSubscriptionService(Cache.ApiKey);

            Subscription = service.Create(Cache.GetCustomer().Id, SubscriptionCreateOptions);

            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);
        }
Exemplo n.º 15
0
        public async Task CancelSubscriptionAsync(Guid organizationId, bool endOfPeriod = false)
        {
            var organization = await _organizationRepository.GetByIdAsync(organizationId);

            if (organization == null)
            {
                throw new NotFoundException();
            }

            if (string.IsNullOrWhiteSpace(organization.StripeSubscriptionId))
            {
                throw new BadRequestException("Organization has no subscription.");
            }

            var subscriptionService = new StripeSubscriptionService();
            var sub = await subscriptionService.GetAsync(organization.StripeSubscriptionId);

            if (sub == null)
            {
                throw new BadRequestException("Organization subscription was not found.");
            }

            if (sub.CanceledAt.HasValue)
            {
                throw new BadRequestException("Organization subscription is already canceled.");
            }

            var canceledSub = await subscriptionService.CancelAsync(sub.Id, endOfPeriod);

            if (!canceledSub.CanceledAt.HasValue)
            {
                throw new BadRequestException("Unable to cancel subscription.");
            }
        }
Exemplo n.º 16
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);
            }
        }
Exemplo n.º 17
0
        static void Main(string[] args)
        {
            // Set Stripe Api Key
            StripeConfiguration.SetApiKey(AppConfiguration.StripeApiKey);

            using (var subscriptionBookingRepository = new SubscriptionBookingRepository())
            {
                var subscriptionBookingList = subscriptionBookingRepository.SubscriptionBookingsList.Where(sb => ids.Contains(sb.Id)).ToList();

                // Each Subscription Bookings
                subscriptionBookingList.ForEach(subscriptionBookings =>
                {
                    var customerInfos = subscriptionBookingRepository.CustomerInfoList
                                        .FirstOrDefault(ci => ci.CustomerId == subscriptionBookings.CustomerId);

                    // Customer Infos
                    if (customerInfos != null)
                    {
                        var subscriptionService         = new StripeSubscriptionService();
                        StripeSubscription subscription = subscriptionService.Get(subscriptionBookings.StripeSubscriptionId);
                        DateTime?canceledDate           = subscription.CanceledAt;

                        if (canceledDate.HasValue)
                        {
                            subscriptionBookings.CancelDate = canceledDate;
                        }
                    }
                });

                subscriptionBookingRepository.UpdateSubscriptionBookingCanceledDate(subscriptionBookingList);

                Console.WriteLine("Done!!!");
                Console.ReadLine();
            }
        }
Exemplo n.º 18
0
        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));
        }
Exemplo n.º 20
0
        public void CreateSubscription(CustomerInfo customerInfo, string planId)
        {
            string customerId = GetCustomerId(customerInfo);
            StripeSubscriptionService subscriptionService = new StripeSubscriptionService();
            StripeSubscription        stripeSubscription  = subscriptionService.Create(customerId, planId);

            PaymentId = stripeSubscription.Id;
        }
		public StripeSubscriptionServiceFacade()
		{
#if DEBUG
			_stripeSubscriptionService = new StripeSubscriptionService(Config.PaymentProviderConfig.TestKey);
#else
			_stripeSubscriptionService = new StripeSubscriptionService(Config.PaymentProviderConfig.ProductionKey);
#endif
		}
Exemplo n.º 22
0
        public IActionResult Delete(string subscriptionId)
        {
            var subscriptionService = new StripeSubscriptionService(_stripeSettings.Value.SecretKey);
            var result = subscriptionService.Cancel(subscriptionId);

            SetTempMessage($"You have successfully deleted '{result.StripePlan.Name}' subscription");
            return(RedirectToAction("Index", "Manage"));
        }
        public string SubscribeAccountPlan(string planId, string customerId)
        {
            var subscriptionService = new StripeSubscriptionService();
            StripeSubscription stripeSubscription = subscriptionService.Create(customerId, planId);

            return(null);
            // optional StripeSubscriptionUpdateOptions            return null;
        }
Exemplo n.º 24
0
        public Subscription CancelSubscription(int companyId)
        {
            var subscription        = GetSubscription(companyId);
            var subscriptionService = new StripeSubscriptionService();

            subscriptionService.Cancel(subscription.StripeCustomerId, subscription.StripeSubscriptionId); // optional cancelAtPeriodEnd flag

            return(subscription);
        }
        public void RemoveCustomerFromSubscription(string customerId)
        {
            var customerService     = new StripeCustomerService(Constants.StripeSecretKey);
            var stripeCustomer      = customerService.Get(customerId);
            var subscriptionId      = stripeCustomer.StripeSubscriptionList.Data.Select(s => s.Id).Distinct().FirstOrDefault();
            var subscriptionService = new StripeSubscriptionService(Constants.StripeSecretKey);

            subscriptionService.Cancel(customerId, subscriptionId);
        }
        public void UnsubscribePlan(string customerId)
        {
            var            customerService = new StripeCustomerService();
            StripeCustomer stripeCustomer  = customerService.Get(customerId);
            var            subscriptionId  = stripeCustomer.Subscriptions.First().Id;

            var subscriptionService = new StripeSubscriptionService();

            subscriptionService.Cancel(subscriptionId);
        }
Exemplo n.º 27
0
        public void CancelPayment(string email)
        {
            StripeCustomerService        customerService = new StripeCustomerService();
            IEnumerable <StripeCustomer> response        = customerService.List();
            string customerId = response.FirstOrDefault(m => m.Email == email).Id;
            StripeSubscriptionService subscriptionService = new StripeSubscriptionService();

            subscriptionService.Cancel(customerId, PaymentId);
            customerService.Delete(customerId);
        }
Exemplo n.º 28
0
        public async Task PurchasePremiumAsync(User user, string paymentToken, short additionalStorageGb)
        {
            var customerService = new StripeCustomerService();
            var customer        = await customerService.CreateAsync(new StripeCustomerCreateOptions
            {
                Description = user.Name,
                Email       = user.Email,
                SourceToken = paymentToken
            });

            var subCreateOptions = new StripeSubscriptionCreateOptions
            {
                CustomerId = customer.Id,
                Items      = new List <StripeSubscriptionItemOption>(),
                Metadata   = new Dictionary <string, string>
                {
                    ["userId"] = user.Id.ToString()
                }
            };

            subCreateOptions.Items.Add(new StripeSubscriptionItemOption
            {
                PlanId   = PremiumPlanId,
                Quantity = 1
            });

            if (additionalStorageGb > 0)
            {
                subCreateOptions.Items.Add(new StripeSubscriptionItemOption
                {
                    PlanId   = StoragePlanId,
                    Quantity = additionalStorageGb
                });
            }

            StripeSubscription subscription = null;

            try
            {
                var subscriptionService = new StripeSubscriptionService();
                subscription = await subscriptionService.CreateAsync(subCreateOptions);
            }
            catch (StripeException)
            {
                await customerService.DeleteAsync(customer.Id);

                throw;
            }

            user.Gateway               = Enums.GatewayType.Stripe;
            user.GatewayCustomerId     = customer.Id;
            user.GatewaySubscriptionId = subscription.Id;
            user.Premium               = true;
            user.PremiumExpirationDate = subscription.CurrentPeriodEnd;
        }
        static void Main(string[] args)
        {
            // Set Stripe Api Key
            StripeConfiguration.SetApiKey(AppConfiguration.StripeApiKey);

            using (var subscriptionBookingRepository = new SubscriptionBookingRepository())
            {
                var subscriptionBookingList = subscriptionBookingRepository.SubscriptionBookingsList.Where(sb => ids.Contains(sb.Id)).ToList();

                // Each Subscription Bookings
                subscriptionBookingList.ForEach(subscriptionBookings =>
                {
                    var customerInfos = subscriptionBookingRepository.CustomerInfoList
                                        .FirstOrDefault(ci => ci.CustomerId == subscriptionBookings.CustomerId);

                    // Customer Infos
                    if (customerInfos != null)
                    {
                        var subscriptionService         = new StripeSubscriptionService();
                        StripeSubscription subscription = subscriptionService.Get(subscriptionBookings.StripeSubscriptionId);
                        DateTime?canceledDate           = subscription.CanceledAt;

                        if (canceledDate.HasValue)
                        {
                            subscriptionBookings.CancelDate = canceledDate;
                        }

                        switch (subscription.Status)
                        {
                        case "past_due":
                        case "unpaid":
                            subscriptionBookings.Status = (int)Enums.SubscriptionBookingStatus.Suspended;
                            break;

                        case "active":
                            // Set Date of Discounts
                            //subscriptionBookings.Status = (int)Enums.SubscriptionBookingStatus.Active;
                            break;

                        case "canceled":
                            //subscriptionBookings.Status = (int)Enums.SubscriptionBookingStatus.End;
                            break;

                        default:     //trialing
                            break;
                        }
                    }
                });

                subscriptionBookingRepository.UpdateSubscriptionBookingCanceledDate(subscriptionBookingList);

                Console.WriteLine("Done!!!");
                Console.ReadLine();
            }
        }
        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 });
            }
        }