示例#1
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);
        }
示例#2
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);
        }
示例#3
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);
            }
        }
示例#4
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);
        }
示例#5
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);
        }
示例#6
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);
        }
示例#7
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);
        }
示例#8
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";
        }
示例#9
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);
            }
        }
示例#10
0
        /// <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);
        }
示例#11
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);
     }
 }
示例#12
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>
        /// <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 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;
        }
示例#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;
                }
            }));
        }
示例#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);
        }
示例#16
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;
            }
        }
示例#17
0
        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());
        }
示例#18
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);
        }
示例#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);
        }
        public void UpdateSubscription(string Api_Key, string SubscriptionId, string stripeSubscriptionUpdateOptionsJSON, ref string Response, ref string Errors, ref int ErrorCode)
        {
            try
            {
                StripeConfiguration.SetApiKey(Api_Key);

                Serializer serializer = new Serializer();
                var        stripeSubscriptionUpdateOptions = serializer.Deserialize <StripeSubscriptionUpdateOptions>(stripeSubscriptionUpdateOptionsJSON);
                var        stripeSubscriptionService       = new StripeSubscriptionService();

                var stripeSubscription = stripeSubscriptionService.Update(SubscriptionId, stripeSubscriptionUpdateOptions);

                Response  = stripeSubscription.StripeResponse.ResponseJson;
                ErrorCode = 0;
            }
            catch (StripeException e)
            {
                ErrorCode = 1;
                Serializer  serializer  = new Serializer();
                StripeError stripeError = e.StripeError;
                Errors = serializer.Serialize <StripeError>(stripeError);
            }
        }
        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 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 }));
        }
        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));
            }
        }
        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);
            }
        }
		public StripeSubscription Update(string customerId, string subscriptionId, StripeSubscriptionUpdateOptions updateOptions)
		{
			return _stripeSubscriptionService.Update(customerId, subscriptionId, updateOptions);
		}
示例#26
0
        public async Task <IHttpActionResult> ChangePlanAsync(string id, string planId, string stripeToken = null, string last4 = null, string couponId = null)
        {
            if (String.IsNullOrEmpty(id) || !CanAccessOrganization(id))
            {
                return(NotFound());
            }

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

            Organization organization = await _repository.GetByIdAsync(id);

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

            BillingPlan plan = BillingManager.GetBillingPlan(planId);

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

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

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

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

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

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

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

                    organization.SubscribeDate = DateTime.Now;

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

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

                    StripeCustomer customer = customerService.Create(createCustomer);

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

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

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

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

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

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

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

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

            return(Ok(new ChangePlanResult {
                Success = true
            }));
        }