Exemplo n.º 1
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.º 2
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.º 3
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.");
            }
        }
        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);
        }
Exemplo n.º 5
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"));
        }
Exemplo n.º 6
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);
        }
Exemplo n.º 8
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);
        }
        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);
        }
        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 });
            }
        }
Exemplo n.º 11
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);
        }
Exemplo n.º 12
0
 public StripeSubscriptionService CancelSubscription(string subscriptionId)
 {
     try
     {
         var subscriptionService = new StripeSubscriptionService();
         subscriptionService.Cancel(subscriptionId, true);
         return(subscriptionService);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Exemplo n.º 13
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);
        }
Exemplo n.º 14
0
        /// <summary>
        /// Unsubscribes the given subscription
        /// NOTE: Save changes on the underlying context for the model after calling this method
        /// </summary>
        /// <param name="customer"></param>
        /// <param name="subscription"></param>
        /// <returns></returns>
        public static StripeSubscription Unsubscribe(ICustomerEntity customer, ISubscriptionEntity subscription)
        {
            if (string.IsNullOrEmpty(subscription.PaymentSystemId) || string.IsNullOrEmpty(customer.PaymentSystemId))
            {
                return(null);
            }

            var subscriptionService = new StripeSubscriptionService();
            StripeSubscription sub  = subscriptionService.Cancel(customer.PaymentSystemId, subscription.PaymentSystemId);

            subscription.PaymentSystemId = null;

            Logger.Log <StripeManager>("Unsuscribed customer in stripe: '{0}' with new subscription id '{1}", LogLevel.Information, customer.Email, subscription.PaymentSystemId);
            return(sub);
        }
Exemplo n.º 15
0
        public void CancleCustomerSubscription(ApplicationUser dbUser)
        {
            StripeCustomer customer = GetStripeCustomer(dbUser.StripeCustomerId);

            if (customer != null && customer.Subscriptions != null && customer.Subscriptions.TotalCount > 0)
            {
                var service = new StripeSubscriptionService();
                StripeSubscription subscription = service.Cancel(customer.Subscriptions.Data[0].Id);
            }
            else
            {
                //todo log error, no user or subscription here....
            }

            _emailSender.SendEmailAsync(EmailType.CancelSubscription, dbUser.Email, dbUser.FirstName);
        }
Exemplo n.º 16
0
        public bool cancelSubscription([FromBody] JObject report)
        {
            StripeConfiguration.SetApiKey("sk_test_p9FWyo0hC9g8y39CkRR1pnYH");
            Dictionary <string, object> parameters = new Dictionary <string, object>();

            parameters.Add("Username", report.Property("username").Value.ToString());

            Subscription sub = new Subscription().SearchDocument(parameters)[0];

            var service = new StripeSubscriptionService();
            StripeSubscription subscription = service.Cancel(sub.SubID, true);

            sub.DeleteDocument();

            return(true);
        }
        protected void CancelMembershipLinkButton_OnClick(object sender, EventArgs e)
        {
            var subscriptionService         = new StripeSubscriptionService();
            StripeSubscription subscription = subscriptionService.Cancel(_subscriptionBookings.StripeSubscriptionId, true);

            _subscriptionBookings.Status     = (int)Enums.SubscriptionBookingStatus.End;
            _subscriptionBookings.CancelDate = DateTime.UtcNow;

            _subscriptionBookings.Description = subscription.StripeResponse.ObjectJson;

            _subscriptionBookingRepository.Update(_subscriptionBookings);

            CancelMembershipLinkButton.Visible = false;
            ErrorLabel.Visible = true;
            ErrorLabel.Text    = "Your subscription successfully canceled. Your membership is still valid till the end of the period.";
        }
Exemplo n.º 18
0
        public ActionResult CancelSubscription()
        {
            int memberId;

            if (!int.TryParse(Request.Form["membership.Member"], out memberId))
            {
                TempData["ErrorMessage"] =
                    "There was an error whilst canceling the subscription. Try again or contact the system else who might be in the know.... not Nick though as he is probably busy!";

                return(RedirectToCurrentUmbracoPage(Request.QueryString));
            }
            if (Request.Form["membership.StripeSubscriptionId"] == null)
            {
                TempData["ErrorMessage"] =
                    "There was an error whilst canceling the subscription. Try again or contact the system else who might be in the know.... not Nick though as he is probably busy!";

                return(RedirectToCurrentUmbracoPage(Request.QueryString));
            }
            string subscriptionId = Request.Form["membership.StripeSubscriptionId"];
            var    m = new Member(Members.GetById(memberId));

            if (m.StripeUserId.IsNullOrEmpty())
            {
                TempData["ErrorMessage"] =
                    "There was an error whilst canceling the subscription. Try again or contact the system else who might be in the know.... not Nick though as he is probably busy!";

                return(RedirectToCurrentUmbracoPage(Request.QueryString));
            }
            try
            {
                StripeSubscriptionService service =
                    new StripeSubscriptionService(SensativeInformation.StripeKeys.SecretKey);
                service.Cancel(subscriptionId, true);
            }
            catch (StripeException e)
            {
                _log.Error($"Admin tried to cancel subscription but stripe returned the error: {e.Message}");
                TempData["ErrorMessage"] =
                    $"There was an error whilst canceling the subscription. The service retrurned the error {e.Message}";

                return(RedirectToCurrentUmbracoPage(Request.QueryString));
            }
            TempData["SuccessMessage"] =
                $"You have successfully deleted the subsctipn with id {subscriptionId}. This can take a few seconds to take effect.";
            return(RedirectToCurrentUmbracoPage(Request.QueryString));
        }
Exemplo n.º 19
0
        public ActionResult Cancel(int subscriptionId)
        {
            var subscription = db.Subscriptions.Find(subscriptionId);

            subscription.AutoRenewal = false;
            db.SaveChanges();
            //do Stripe cancellation
            KeyManager keyManager      = new KeyManager();
            string     StripeSecretKey = keyManager.StripeSecretKey;

            StripeConfiguration.SetApiKey(StripeSecretKey);

            var subscriptionService = new StripeSubscriptionService();
            StripeSubscription stripeSubscription = subscriptionService.Cancel(subscription.StripeSubscriptionId);

            TempData["infoMessage"] = "Your subscription has been cancelled. You will no longer be able to use BandMate after your subscription end date.";
            return(RedirectToAction("Index"));
        }
        public async Task <dynamic> Post()
        {
            try
            {
                var    item  = RequestContext.Principal.Identity;
                string value = await Request.Content.ReadAsStringAsync();

                var entidad = System.Web.Helpers.Json.Decode(value);

                var subscriptionService = new StripeSubscriptionService("sk_test_CBdkobSnlUEOyOjsLQ8fpqof");
                var result = subscriptionService.Cancel(entidad.customerId, entidad.subscriptionId);
                return(result);
            }
            catch (Exception ex)
            {
                return(ex);
            }
        }
Exemplo n.º 21
0
        protected void CancelMembershipLinkButton_OnClick(object sender, EventArgs e)
        {
            var subscriptionService         = new StripeSubscriptionService();
            StripeSubscription subscription = subscriptionService.Cancel(_subscriptionBookings.StripeSubscriptionId, true);

            _subscriptionBookings.Status     = (int)Enums.SubscriptionBookingStatus.End;
            _subscriptionBookings.CancelDate = DateTime.UtcNow;

            _subscriptionBookings.Description = subscription.StripeResponse.ObjectJson;

            _subscriptionBookingRepository.Update(_subscriptionBookings);

            NextCycleLit.Visible           = false;
            cancelMembershipLink.Visible   = false;
            reactiveMembershipLink.Visible = true;
            ErrorMessageLabel.Visible      = true;
            ErrorMessageLabel.Text         = Message.SubscriptionCancel;
            ErrorMessageLabel.CssClass     = "error-message";
        }
Exemplo n.º 22
0
        public ActionResult CancelSubscription(long userID)
        {
            string         customerID      = Convert.ToString(SessionController.UserSession.CustomerID);
            var            customerService = new StripeCustomerService();
            StripeCustomer stripeCustomer  = customerService.Get(customerID);

            var subscriptionID = stripeCustomer.Subscriptions.Data[0].Id;

            var subscriptionService = new StripeSubscriptionService();
            var status = subscriptionService.Cancel(subscriptionID, true); // optional cancelAtPeriodEnd flag

            SessionController.UserSession.IsPaid = false;

            //Delete the customer's card from stripe
            var           cardService = new StripeCardService();
            StripeCard    stripeCard  = cardService.Get(customerID, stripeCustomer.DefaultSourceId);
            StripeDeleted card        = cardService.Delete(customerID, stripeCard.Id);

            return(Json(status, JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 23
0
        public StripeSubscription CancelCustomerSubscription(string sStripeCustomerId)
        {
            try
            {
                StripeConfiguration.SetApiKey(ConfigurationManager.AppSettings["stripeApi_LiveKey"]);

                var            customerService = new StripeCustomerService();
                StripeCustomer customer        = customerService.Get(sStripeCustomerId);

                var subscriptionService         = new StripeSubscriptionService();
                StripeSubscription subscription = subscriptionService.Cancel(customer.Subscriptions.FirstOrDefault().Id);

                return(subscription);
            }
            catch (Exception ex)
            {
                oLogger.LogData("METHOD: CreateStripeCustomer; ERROR: TRUE; EXCEPTION: " + ex.Message + "; INNER EXCEPTION: " + ex.InnerException + "; STACKTRACE: " + ex.StackTrace);
                throw;
            }
        }
        public void CancelSubscription(string Api_Key, string SubscriptionId, bool CancelAtPeriodEnd, ref string Response, ref string Errors, ref int ErrorCode)
        {
            try
            {
                StripeConfiguration.SetApiKey(Api_Key);

                var stripeSubscriptionService = new StripeSubscriptionService();

                var stripeSubscription = stripeSubscriptionService.Cancel(SubscriptionId, CancelAtPeriodEnd);
                Response  = stripeSubscription.StripeResponse.ResponseJson;
                ErrorCode = 0;
            }
            catch (StripeException e)
            {
                ErrorCode = 1;
                Serializer  serializer  = new Serializer();
                StripeError stripeError = e.StripeError;
                Errors = serializer.Serialize <StripeError>(stripeError);
            }
        }
Exemplo n.º 25
0
        static void Main(string[] args)
        {
            // Set Stripe Api Key
            StripeConfiguration.SetApiKey(AppConfiguration.StripeApiKey);

            using (var subscriptionBookingRepository = new SubscriptionBookingRepository())
            {
                var subscriptionBookingList = subscriptionBookingRepository.SubscriptionBookingsList.ToList();

                var invoiceService = new StripeInvoiceService();
                var invoiceItems   = invoiceService.List(
                    new StripeInvoiceListOptions
                {
                    Limit = Int32.MaxValue
                }
                    ).ToList();

                invoiceItems.ForEach(invoice =>
                {
                    var subscription = subscriptionBookingList
                                       .FirstOrDefault(sb => sb.StripeSubscriptionId.Equals(invoice.SubscriptionId, StringComparison.OrdinalIgnoreCase));
                    if (subscription == null)
                    {
                        try
                        {
                            var subscriptionService = new StripeSubscriptionService();
                            var stripeSubscription  = subscriptionService.Cancel(invoice.SubscriptionId);
                            Console.WriteLine("Cancel - " + invoice.SubscriptionId);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Error - " + ex.Message);
                        }
                    }
                });

                Console.WriteLine("Done!!!");
                Console.ReadLine();
            }
        }
Exemplo n.º 26
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 }));
        }
        public ActionResult CancelSubscription(string subscriptionId)
        {
            if (subscriptionId.IsNullOrEmpty())
            {
                _log.Error("Canceling the subscription but the subscriptionId passed in was null or empty");
                ModelState.AddModelError("",
                                         "There was an error whilst trying to cancel your subscription. Please try again or contact us so we can help you resolve this.");
                return(CurrentUmbracoPage());
            }
            var loggedOnMember = Members.GetCurrentMember();


            var member = new Member(Umbraco.TypedMember(loggedOnMember.Id));

            if (member.StripeUserId.IsNotNullOrEmpty())
            {
                try
                {
                    var subscriptionService = new StripeSubscriptionService(SensativeInformation.StripeKeys.SecretKey);
                    StripeSubscription stripeSubscription = subscriptionService.Cancel(subscriptionId, true);
                    TempData["CancelMessage"] =
                        "You have successfully canceled your membership subscription. It can take five minutes to process.";
                    return(RedirectToCurrentUmbracoPage());
                }
                catch (StripeException e)
                {
                    _log.Error(e.StripeError.Message);
                }
            }
            else
            {
                _log.Error($"The retrieved user had a null or empty stripe user id. The username is {member.Name}");
            }
            ModelState.AddModelError("",
                                     "There was an error cancelling your subscription. Please try again. If the issue persists please contact us");
            return(CurrentUmbracoPage());
        }
Exemplo n.º 28
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 IActionResult Delete(string subscriptionId)
        {
            try
            {
                var subscriptionService = new StripeSubscriptionService(_stripeSettings.Value.SecretKey);
                var result = subscriptionService.Cancel(subscriptionId);

                SetTempMessage(_localizer["You have successfully deleted"] + result.StripePlan.Nickname
                               + _localizer["subscription"]);
                return(RedirectToAction("Index", "Manage"));
            }
            catch (Exception ex)
            {
                log = new EventLog()
                {
                    EventId = (int)LoggingEvents.DELETE_ITEM, LogLevel = LogLevel.Error.ToString(), Message = ex.Message, StackTrace = ex.StackTrace, Source = ex.Source
                };
                _loggerService.SaveEventLogAsync(log);
                return(RedirectToAction("Error", "Error500", new ErrorViewModel()
                {
                    Error = ex.Message
                }));
            }
        }
        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 }));
        }