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,
            };
        }
        public void TestUpdateSubscription()
        {
            StripeSDKMain stripe = new StripeSDKMain();

            string Response  = "";
            string Errors    = "";
            int    ErrorCode = 0;

            var Api_Key        = GetApiKey();
            var SubscriptionId = GetSubscriptionId();

            var stripeSubscriptionUpdateOptions = new StripeSubscriptionUpdateOptions()
            {
                Quantity = 3
            };

            Serializer serializer = new Serializer();
            var        stripeSubscriptionUpdateOptionsJSON = serializer.Serialize <StripeSubscriptionUpdateOptions>(stripeSubscriptionUpdateOptions);

            stripe.UpdateSubscription(Api_Key, SubscriptionId, stripeSubscriptionUpdateOptionsJSON, ref Response, ref Errors, ref ErrorCode);

            if (ErrorCode == 0)
            {
                Console.WriteLine(Response);
            }
            else
            {
                Console.WriteLine(Errors);
            }
        }
Beispiel #3
0
        /// <summary>
        /// Updates the subscription. (Change subscription plan)
        /// </summary>
        /// <param name="customerId">The customer identifier.</param>
        /// <param name="subStripeId">The sub stripe identifier.</param>
        /// <param name="newPlanId">The new plan identifier.</param>
        /// <param name="proRate">if set to <c>true</c> [pro rate].</param>
        /// <returns></returns>
        public bool UpdateSubscription(string customerId, string subStripeId, string newPlanId, bool proRate)
        {
            var result = true;

            try
            {
                var currentSubscription = this._subscriptionService.Get(customerId, subStripeId);

                var myUpdatedSubscription = new StripeSubscriptionUpdateOptions
                {
                    PlanId  = newPlanId,
                    Prorate = proRate
                };

                if (currentSubscription.TrialEnd != null && currentSubscription.TrialEnd > DateTime.UtcNow)
                {
                    myUpdatedSubscription.TrialEnd = currentSubscription.TrialEnd; // Keep the same trial window as initially created.
                }

                _subscriptionService.Update(customerId, subStripeId, myUpdatedSubscription);
            }
            catch (Exception ex)
            {
                // TODO: Log
                result = false;
            }

            return(result);
        }
        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);
        }
Beispiel #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);
        }
Beispiel #6
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);
            }
        }
Beispiel #7
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);
        }
Beispiel #8
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);
        }
Beispiel #9
0
        protected void ReActiveMembershipLinkButton_OnClick(object sender, EventArgs e)
        {
            var subscriptionOptions = new StripeSubscriptionUpdateOptions()
            {
                PlanId = _subscriptions.StripePlanId
            };

            var subscriptionService         = new StripeSubscriptionService();
            StripeSubscription subscription = subscriptionService.Update(_subscriptionBookings.StripeSubscriptionId, subscriptionOptions);

            var bookingRepository = new BookingRepository();

            switch (subscription.Status)
            {
            case "past_due":
            case "unpaid":
                _subscriptionBookings.Status = (int)Enums.SubscriptionBookingStatus.Suspended;
                bookingRepository.ExpiredBookingByCancelledSubscription(PublicDiscounts.Id);
                break;

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

                // Set Date of Subscription Bookings
                _subscriptionBookings.StartDate       = subscription.CurrentPeriodStart;
                _subscriptionBookings.EndDate         = subscription.CurrentPeriodEnd;
                _subscriptionBookings.LastUpdatedDate = DateTime.UtcNow;
                _subscriptionBookings.LastUpdatedBy   = 0;
                break;

            case "canceled":
                _subscriptionBookings.Status = (int)Enums.SubscriptionBookingStatus.End;
                bookingRepository.ExpiredBookingByCancelledSubscription(PublicDiscounts.Id);
                break;

            default:     //trialing
                break;
            }

            _subscriptionBookings.Description = subscription.StripeResponse.ObjectJson;

            _subscriptionBookingRepository.Update(_subscriptionBookings);

            NextCycleLit.Visible           = true;
            cancelMembershipLink.Visible   = true;
            reactiveMembershipLink.Visible = false;
            ErrorMessageLabel.Visible      = true;
            ErrorMessageLabel.Text         = Message.SubscriptionReActive;
            ErrorMessageLabel.CssClass     = "success-message";
        }
Beispiel #10
0
        public static StripeSubscription UpdatePlan(string subsId, StripeSubscriptionUpdateOptions obj)
        {
            var subscriptionService = new StripeSubscriptionService();

            try
            {
                StripeSubscription stripeSubscription = subscriptionService.Update(subsId, obj);
                return(stripeSubscription);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
        /// <summary>
        /// Changes the given subscription to use the new plan
        /// </summary>
        /// <param name="customer"></param>
        /// <param name="subscription"></param>
        /// <param name="newPlan"></param>
        /// <returns></returns>
        public static StripeSubscription ChangeSubscriptionPlan(ICustomerEntity customer, ISubscriptionEntity subscription, IPlanEntity newPlan)
        {
            StripeSubscriptionUpdateOptions options = new StripeSubscriptionUpdateOptions()
            {
                PlanId = newPlan.PaymentSystemId
            };

            var subscriptionService = new StripeSubscriptionService();
            StripeSubscription changedSubscription = subscriptionService.Update(customer.PaymentSystemId, subscription.PaymentSystemId, options);

            Logger.Log <StripeManager>("Changed subscription for customer in stripe: '{0}' with new subscription id '{1}", LogLevel.Information, customer.Email, subscription.PaymentSystemId);

            return(changedSubscription);
        }
        public string ChangeAccountPlan(string planId, string customerId)
        {
            var            customerService = new StripeCustomerService();
            StripeCustomer stripeCustomer  = customerService.Get(customerId);
            var            subscriptionId  = stripeCustomer.Subscriptions.First().Id;

            var subscriptionService = new StripeSubscriptionService();
            StripeSubscriptionUpdateOptions ssuo = new StripeSubscriptionUpdateOptions();

            ssuo.PlanId = planId;

            StripeSubscription stripeSubscription = subscriptionService.Update(subscriptionId, ssuo);

            return(null);
            // optional StripeSubscriptionUpdateOptions            return null;
        }
Beispiel #13
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);
        }
Beispiel #14
0
        public async Task <string> ChangePlan(RechargeInput input)
        {
            var user        = AuthHelper.GetCurrentUser();
            var usermanager = AuthHelper.GetUserManager();

            try
            {
                StripeConfiguration.SetApiKey(System.Configuration.ConfigurationManager.AppSettings["StripeApiKey"]);
            }
            catch (Exception ex)
            {
                //log the exception and return the message to the caller
                return(ex.Message);
            }

            return(await System.Threading.Tasks.Task.Run(() =>
            {
                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);

                        var options = new StripeSubscriptionUpdateOptions();
                        options.PlanId = input.PlanID;
                        options.Prorate = false;

                        sub_svc.Update(cust.Id, sub.Id, options);
                    }
                    else
                    {
                        throw new ApplicationException("Could not find the customer in stripe to change the plan");
                    }
                    return "Success";
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }));
        }
Beispiel #15
0
        public bool updateSubscription([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.Get(sub.SubID);

            var items = new List <StripeSubscriptionItemUpdateOption> {
                new StripeSubscriptionItemUpdateOption {
                    PlanId = report.Property("newPlan").Value.ToString(),
                    Id     = subscription.Items.Data[0].Id
                },
            };
            StripeSubscriptionUpdateOptions options;

            if (report.Property("coupon").Value.ToString().Equals(string.Empty) || (!report.Property("coupon").Value.ToString().Equals("Partner25") && !report.Property("coupon").Value.ToString().Equals("tellnpfree6") && !report.Property("coupon").Value.ToString().Equals("tellnpfree12")))
            {
                options = new StripeSubscriptionUpdateOptions {
                    Items             = items,
                    CancelAtPeriodEnd = false
                };
            }
            else
            {
                options = new StripeSubscriptionUpdateOptions {
                    Items             = items,
                    CancelAtPeriodEnd = false,
                    CouponId          = report.Property("coupon").Value.ToString()
                };
            }

            subscription = service.Update(sub.SubID, options);
            sub.PlanName = report.Property("newPlan").Value.ToString();
            sub.UpdateDocument(sub);

            return(true);
        }
Beispiel #16
0
        /// <summary>
        /// Updates the subscription tax.
        /// </summary>
        /// <param name="customerId">The customer identifier.</param>
        /// <param name="subStripeId">The sub stripe identifier.</param>
        /// <param name="taxPercent">The tax percent.</param>
        /// <returns></returns>
        public bool UpdateSubscriptionTax(string customerId, string subStripeId, decimal taxPercent = 0)
        {
            var result = true;

            try
            {
                var myUpdatedSubscription = new StripeSubscriptionUpdateOptions
                {
                    TaxPercent = taxPercent
                };
                _subscriptionService.Update(customerId, subStripeId, myUpdatedSubscription);
            }
            catch (Exception ex)
            {
                // TODO: log
                result = false;
            }

            return(result);
        }
        public ActionResult Charge(string stripeEmail, string stripeToken)
        {
            var req       = this.HttpContext.Request.Form;
            var customers = new StripeCustomerService();
            var charges   = new StripeChargeService();

            var customer = customers.Create(new StripeCustomerCreateOptions
            {
                Email       = stripeEmail,
                SourceToken = stripeToken
            });

            var charge = charges.Create(new StripeChargeCreateOptions
            {
                Amount      = 500,//charge in cents
                Description = "Sample Charge",
                Currency    = "usd",
                CustomerId  = customer.Id
            });

            StripeSubscriptionService subscriptionSvc = new StripeSubscriptionService();

            subscriptionSvc.Create(customer.Id, "EBSystems");

            var subscriptionOptions = new StripeSubscriptionUpdateOptions()
            {
                PlanId   = "EBSystems",
                Prorate  = false,
                TrialEnd = DateTime.Now.AddMinutes(2)
            };

            var subscriptionService         = new StripeSubscriptionService();
            StripeSubscription subscription = subscriptionService.Update("sub_BlX0rziJyWis7k", subscriptionOptions);

            //StripeSubscriptionService subscriptionSvc = new StripeSubscriptionService();
            //subscriptionSvc.Create(customer.Id, "ebsystems_standard");
            // further application specific code goes here

            return(View());
        }
Beispiel #18
0
        public StripeSubscription UpdateSubscription(PurchaseInformation info, string customerIdOfStripe, string subscriptionId)
        {
            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);

                StripeSubscriptionUpdateOptions options = new StripeSubscriptionUpdateOptions()
                {
                    PlanId   = info.PlanId,
                    Quantity = 1,
                    CouponId = !string.IsNullOrEmpty(info.Coupon) ? info.Coupon : null
                };

                var subscriptionService = new StripeSubscriptionService();
                StripeSubscription stripeSubscription = subscriptionService.Update(subscriptionId, options); // optional StripeSubscriptionCreateOptions
                return(stripeSubscription);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #19
0
        private StripeSubscription UpdateUserSubscription(string id, string currentSubscriptionId, string planToSubscribeTo, StripeSubscriptionService service, ApplicationUser dbUser)
        {
            StripeSubscription subscription = service.Get(currentSubscriptionId);

            var items = new List <StripeSubscriptionItemUpdateOption> {
                new StripeSubscriptionItemUpdateOption {
                    Id     = subscription.Items.Data[0].Id,
                    PlanId = GetPlanIdFromPlanName(planToSubscribeTo),
                },
            };
            var options = new StripeSubscriptionUpdateOptions
            {
                CancelAtPeriodEnd = false,
                Items             = items,
            };

            subscription = service.Update(currentSubscriptionId, options);

            _emailSender.SendEmailAsync(GetUpgradeOrDowngradeStatus(currentSubscriptionId, subscription.Id), dbUser.Email, dbUser.FirstName);

            return(subscription);
        }
Beispiel #20
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);
        }
        /// <summary>
        /// Updates the subscription. (Change subscription plan)
        /// </summary>
        /// <param name="customerId">The customer identifier.</param>
        /// <param name="subStripeId">The sub stripe identifier.</param>
        /// <param name="newPlanId">The new plan identifier.</param>
        /// <returns></returns>
        public bool UpdateSubscription(string customerId, string subStripeId, string newPlanId)
        {
            var result = true;

            try
            {
                var currentSubscription = this._subscriptionService.Get(customerId, subStripeId);

                var myUpdatedSubscription = new StripeSubscriptionUpdateOptions
                {
                    PlanId   = newPlanId,
                    TrialEnd = currentSubscription.TrialEnd // Keep the same trial window as initially created.
                };

                _subscriptionService.Update(customerId, subStripeId, myUpdatedSubscription);
            }
            catch (Exception ex)
            {
                // TODO: Log
                result = false;
            }

            return(result);
        }
		public StripeSubscription Update(string customerId, string subscriptionId, StripeSubscriptionUpdateOptions updateOptions)
		{
			return _stripeSubscriptionService.Update(customerId, subscriptionId, updateOptions);
		}
        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 }));
        }
Beispiel #24
0
        public async Task UpgradePlanAsync(Guid organizationId, PlanType plan, int additionalSeats)
        {
            var organization = await _organizationRepository.GetByIdAsync(organizationId);

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

            if (string.IsNullOrWhiteSpace(organization.StripeCustomerId))
            {
                throw new BadRequestException("No payment method found.");
            }

            var existingPlan = StaticStore.Plans.FirstOrDefault(p => p.Type == organization.PlanType);

            if (existingPlan == null)
            {
                throw new BadRequestException("Existing plan not found.");
            }

            var newPlan = StaticStore.Plans.FirstOrDefault(p => p.Type == plan && !p.Disabled);

            if (newPlan == null)
            {
                throw new BadRequestException("Plan not found.");
            }

            if (existingPlan.Type == newPlan.Type)
            {
                throw new BadRequestException("Organization is already on this plan.");
            }

            if (existingPlan.UpgradeSortOrder >= newPlan.UpgradeSortOrder)
            {
                throw new BadRequestException("You cannot upgrade to this plan.");
            }

            if (!newPlan.CanBuyAdditionalSeats && additionalSeats > 0)
            {
                throw new BadRequestException("Plan does not allow additional seats.");
            }

            if (newPlan.CanBuyAdditionalSeats && newPlan.MaxAdditionalSeats.HasValue &&
                additionalSeats > newPlan.MaxAdditionalSeats.Value)
            {
                throw new BadRequestException($"Selected plan allows a maximum of " +
                                              $"{newPlan.MaxAdditionalSeats.Value} additional seats.");
            }

            var newPlanSeats = (short)(newPlan.BaseSeats + (newPlan.CanBuyAdditionalSeats ? additionalSeats : 0));

            if (!organization.Seats.HasValue || organization.Seats.Value > newPlanSeats)
            {
                var userCount = await _organizationUserRepository.GetCountByOrganizationIdAsync(organization.Id);

                if (userCount >= newPlanSeats)
                {
                    throw new BadRequestException($"Your organization currently has {userCount} seats filled. Your new plan " +
                                                  $"only has ({newPlanSeats}) seats. Remove some users.");
                }
            }

            if (newPlan.MaxSubvaults.HasValue &&
                (!organization.MaxSubvaults.HasValue || organization.MaxSubvaults.Value > newPlan.MaxSubvaults.Value))
            {
                var subvaultCount = await _subvaultRepository.GetCountByOrganizationIdAsync(organization.Id);

                if (subvaultCount > newPlan.MaxSubvaults.Value)
                {
                    throw new BadRequestException($"Your organization currently has {subvaultCount} subvaults. " +
                                                  $"Your new plan allows for a maximum of ({newPlan.MaxSubvaults.Value}) subvaults. " +
                                                  "Remove some subvaults.");
                }
            }

            var subscriptionService = new StripeSubscriptionService();

            if (string.IsNullOrWhiteSpace(organization.StripeSubscriptionId))
            {
                // They must have been on a free plan. Create new sub.
                var subCreateOptions = new StripeSubscriptionCreateOptions
                {
                    Items = new List <StripeSubscriptionItemOption>
                    {
                        new StripeSubscriptionItemOption
                        {
                            PlanId   = newPlan.StripePlanId,
                            Quantity = 1
                        }
                    }
                };

                if (additionalSeats > 0)
                {
                    subCreateOptions.Items.Add(new StripeSubscriptionItemOption
                    {
                        PlanId   = newPlan.StripeSeatPlanId,
                        Quantity = additionalSeats
                    });
                }

                await subscriptionService.CreateAsync(organization.StripeCustomerId, subCreateOptions);
            }
            else
            {
                // Update existing sub.
                var subUpdateOptions = new StripeSubscriptionUpdateOptions
                {
                    Items = new List <StripeSubscriptionItemUpdateOption>
                    {
                        new StripeSubscriptionItemUpdateOption
                        {
                            PlanId   = newPlan.StripePlanId,
                            Quantity = 1
                        }
                    }
                };

                if (additionalSeats > 0)
                {
                    subUpdateOptions.Items.Add(new StripeSubscriptionItemUpdateOption
                    {
                        PlanId   = newPlan.StripeSeatPlanId,
                        Quantity = additionalSeats
                    });
                }

                await subscriptionService.UpdateAsync(organization.StripeSubscriptionId, subUpdateOptions);
            }
        }
Beispiel #25
0
 public static StripeSubscription UpdateSubscription(string custId, string subId, StripeSubscriptionUpdateOptions options, out string msg)
 {
     msg = "";
     try
     {
         var subscriptionServrive = new StripeSubscriptionService();
         var subscription         = subscriptionServrive.Update(subId, options);
         return(subscription);
     }
     catch (Exception ex)
     {
         msg = ex.Message.ToString();
         return(null);
     }
 }
        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());
        }
        public ActionResult ManageSubscription(string sToken, string sCustomerID, string PlanID)
        {
            objResponse Response = new objResponse();

            session = new SessionHelper();

            try
            {
                if (sCustomerID == "")
                {
                    var myCustomer = new StripeCustomerCreateOptions();

                    // set these properties if it makes you happy
                    myCustomer.Email       = session.UserSession.Email;
                    myCustomer.Description = session.UserSession.FullName;
                    myCustomer.SourceToken = sToken;


                    var            customerService  = new StripeCustomerService();
                    StripeCustomer stripeCustomer   = customerService.Create(myCustomer);
                    var            StripeCustomerId = stripeCustomer.Id;

                    var subscriptionService = new StripeSubscriptionService();
                    StripeSubscription stripeSubscription = subscriptionService.Create(StripeCustomerId, PlanID);

                    Response = objSubManager.SubscribeUser(StripeCustomerId.ToString(), stripeSubscription.Id, PlanID, Convert.ToInt64(session.UserSession.PIN));

                    if (Response.ErrorCode == 0)
                    {
                        return(Json("success", JsonRequestBehavior.AllowGet));
                    }
                    else
                    {
                        return(Json("", JsonRequestBehavior.AllowGet));
                    }
                }
                else
                {
                    var subscriptionService = new StripeSubscriptionService();
                    var stripeUpdateOption  = new StripeSubscriptionUpdateOptions()
                    {
                        PlanId = PlanID
                    };
                    StripeSubscription stripeSubscription = subscriptionService.Update(session.UserSubscription.sSubscriptionID, stripeUpdateOption);

                    Response = objSubManager.UpdateUserSubscription(PlanID, Convert.ToInt64(session.UserSession.PIN));

                    if (Response.ErrorCode == 0)
                    {
                        return(Json("success", JsonRequestBehavior.AllowGet));
                    }
                    else
                    {
                        return(Json("", JsonRequestBehavior.AllowGet));
                    }
                }


                //stripeSubscription.i
                //  stripeSubscription.Status
            }
            catch (Exception ex)
            {
                BAL.Common.LogManager.LogError("SubscribeUser Post Method", 1, Convert.ToString(ex.Source), Convert.ToString(ex.Message), Convert.ToString(ex.StackTrace));
                return(Json("", JsonRequestBehavior.AllowGet));
            }
        }
Beispiel #28
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.")));
            }

            var organization = await GetModelAsync(id, false);

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

            var 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, CurrentUser);

                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 = await subscriptionService.ListAsync(new StripeSubscriptionListOptions { CustomerId = organization.StripeCustomerId });

                        foreach (var sub in subs.Where(s => !s.CanceledAt.HasValue))
                        {
                            await subscriptionService.CancelAsync(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 = SystemClock.UtcNow;

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

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

                    var customer = await customerService.CreateAsync(createCustomer);

                    organization.BillingStatus = BillingStatus.Active;
                    organization.RemoveSuspension();
                    organization.StripeCustomerId = customer.Id;
                    if (customer.Sources.TotalCount > 0)
                    {
                        organization.CardLast4 = customer.Sources.Data.First().Card.Last4;
                    }
                }
                else
                {
                    var update = new StripeSubscriptionUpdateOptions {
                        PlanId = planId
                    };
                    var  create      = new StripeSubscriptionCreateOptions();
                    bool cardUpdated = false;

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

                    var subscriptionList = await subscriptionService.ListAsync(new StripeSubscriptionListOptions { CustomerId = organization.StripeCustomerId });

                    var subscription = subscriptionList.FirstOrDefault(s => !s.CanceledAt.HasValue);
                    if (subscription != null)
                    {
                        await subscriptionService.UpdateAsync(subscription.Id, update);
                    }
                    else
                    {
                        await subscriptionService.CreateAsync(organization.StripeCustomerId, planId, create);
                    }

                    await customerService.UpdateAsync(organization.StripeCustomerId, new StripeCustomerUpdateOptions {
                        Email = CurrentUser.EmailAddress
                    });

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

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

                BillingManager.ApplyBillingPlan(organization, plan, CurrentUser);
                await _repository.SaveAsync(organization, o => o.Cache());

                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(CurrentUser.EmailAddress).Property("User", CurrentUser).SetActionContext(ActionContext).Write();
                return(Ok(ChangePlanResult.FailWithMessage(e.Message)));
            }

            return(Ok(new ChangePlanResult {
                Success = true
            }));
        }
        public void Test1()
        {
            StripeConfiguration.SetApiKey("sk_test_YskwifolV97dD2Iu0v8YgDt5");
            //var req = this.HttpContext.Request.Form;
            var customers = new StripeCustomerService();
            var charges   = new StripeChargeService();

            try
            {
                var tokenOptions = new StripeTokenCreateOptions()
                {
                    Card = new StripeCreditCardOptions()
                    {
                        Number          = "4242424242424242",
                        ExpirationYear  = 2019,
                        ExpirationMonth = 9,
                        Cvc             = "123"
                    }
                };

                var         tokenService = new StripeTokenService();
                StripeToken stripeToken  = tokenService.Create(tokenOptions);



                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 == "*****@*****.**")
                    {
                        found    = true;
                        customer = cus;
                        break;
                    }
                }



                if (!found)
                {
                    customer = customers.Create(new StripeCustomerCreateOptions
                    {
                        Email       = "*****@*****.**",
                        SourceToken = stripeToken.Id
                    });
                }

                var charge = charges.Create(new StripeChargeCreateOptions
                {
                    Amount      = 500,//charge in cents
                    Description = "Sample Charge",
                    Currency    = "usd",
                    CustomerId  = customer.Id
                });



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



                StripeSubscriptionService subscriptionSvc = new StripeSubscriptionService();
                //subscriptionSvc.Create(customer.Id, "EBSystems");

                var subscriptionOptions = new StripeSubscriptionUpdateOptions()
                {
                    PlanId   = "testPlan",
                    Prorate  = false,
                    TrialEnd = DateTime.Now.AddMinutes(2)
                };

                var subscriptionService         = new StripeSubscriptionService();
                StripeSubscription subscription = subscriptionService.Update("sub_DfH8fv8g0MNQau", subscriptionOptions);


                //  --------------------------------------------------------------------
            }
            catch (Exception e)
            {
                string error = e.Message;
                //throw new Exception(error);
            }
        }