Exemplo n.º 1
0
        public async Task UpdateSubscriptionShouldReturnNotModified()
        {
            using (var store = GetDocumentStore())
            {
                var updateOptions = new SubscriptionUpdateOptions
                {
                    Query = "from Users",
                    Name  = "Created"
                };
                store.Subscriptions.Create(updateOptions);

                var subscriptions = await store.Subscriptions.GetSubscriptionsAsync(0, 5);

                var state = subscriptions.First();
                Assert.Equal(1, subscriptions.Count);
                Assert.Equal("Created", state.SubscriptionName);
                Assert.Equal("from Users", state.Query);

                store.Subscriptions.Update(updateOptions);

                var newSubscriptions = await store.Subscriptions.GetSubscriptionsAsync(0, 5);

                var newState = newSubscriptions.First();
                Assert.Equal(1, newSubscriptions.Count);
                Assert.Equal(state.SubscriptionName, newState.SubscriptionName);
                Assert.Equal(state.Query, newState.Query);
                Assert.Equal(state.SubscriptionId, newState.SubscriptionId);
            }
        }
Exemplo n.º 2
0
        public void UpdateSubscription(StripeChargeRequest req)
        {
            var newPlan = GetById(req.TenantId, req.SubscriptionLevel);
            var info    = GetByBusinessId(req.BusinessId);

            var items = new List <SubscriptionItemUpdateOption> {
                new SubscriptionItemUpdateOption {
                    PlanId = newPlan.StripePlanId
                }
            };
            var options = new SubscriptionUpdateOptions
            {
                Items   = items,
                Prorate = false
            };

            var          service      = new SubscriptionService();
            Subscription subscription = service.Update(info.StripeSubscriptionId, options);



            dataProvider.ExecuteNonQuery(
                "Subscriptions_Update",
                (parameters) =>
            {
                parameters.AddWithValue("@SubscriptionLevel", req.SubscriptionLevel);
                parameters.AddWithValue("@StripeSubscriptionId", info.StripeSubscriptionId);
                parameters.AddWithValue("@BusinessId", req.BusinessId);
            }

                );
        }
Exemplo n.º 3
0
        public ActionResult Pause()
        {
            try
            {
                StripeConfiguration.ApiKey            = key;
                StripeConfiguration.MaxNetworkRetries = 2;

                var options = new SubscriptionUpdateOptions
                {
                    PauseCollection = new SubscriptionPauseCollectionOptions
                    {
                        Behavior  = "void",
                        ResumesAt = DateTime.Today.AddDays(1)
                    },
                };
                var service = new SubscriptionService();
                service.Update(subscriptionId, options);

                return(View("OrderStatus"));
            }
            catch (StripeException e)
            {
                var x = new
                {
                    status  = "Failed",
                    message = e.Message
                };
                return(this.Json(x));
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Updates or downgrades current subscription
        /// </summary>
        /// <returns></returns>
        public async Task <Subscription> UpdateSubscription(PaymentModel payment)
        {
            var customerSubscription = await GetCustomerSubscription(payment.CustomerId); // get current

            var subscriptionService = new SubscriptionService();

            var subscriptions = new List <SubscriptionItemOptions>()
            {
                new SubscriptionItemOptions()
                {
                    Id   = customerSubscription.Id,
                    Plan = payment.PlanId,
                }
            };

            var options = new SubscriptionUpdateOptions
            {
                CancelAtPeriodEnd = false,
                Items             = subscriptions,
            };

            var subscription = await subscriptionService.UpdateAsync(customerSubscription.Id, options);

            return(subscription);
        }
Exemplo n.º 5
0
        private async Task <Subscription> VerifyCorrectTaxRateForCharge(Invoice invoice, Subscription subscription)
        {
            if (!string.IsNullOrWhiteSpace(invoice?.CustomerAddress?.Country) && !string.IsNullOrWhiteSpace(invoice?.CustomerAddress?.PostalCode))
            {
                var localBitwardenTaxRates = await _taxRateRepository.GetByLocationAsync(
                    new TaxRate()
                {
                    Country    = invoice.CustomerAddress.Country,
                    PostalCode = invoice.CustomerAddress.PostalCode
                }
                    );

                if (localBitwardenTaxRates.Any())
                {
                    var stripeTaxRate = await new TaxRateService().GetAsync(localBitwardenTaxRates.First().Id);
                    if (stripeTaxRate != null && !subscription.DefaultTaxRates.Any(x => x == stripeTaxRate))
                    {
                        subscription.DefaultTaxRates = new List <Stripe.TaxRate> {
                            stripeTaxRate
                        };
                        var subscriptionOptions = new SubscriptionUpdateOptions()
                        {
                            DefaultTaxRates = new List <string>()
                            {
                                stripeTaxRate.Id
                            }
                        };
                        subscription = await new SubscriptionService().UpdateAsync(subscription.Id, subscriptionOptions);
                    }
                }
            }
            return(subscription);
        }
        public async Task <bool> CancelSubcription(string customerId)
        {
            var subcription = await _context.Subcriptions.Where(sub => sub.StripeCustomerId == customerId && sub.IsDisable == false).FirstOrDefaultAsync();

            if (subcription != null)
            {
                StripeConfiguration.ApiKey = this._configuration.GetSection("Stripe")["SecretKey"];

                var options = new SubscriptionUpdateOptions
                {
                    CancelAtPeriodEnd = true,
                };

                var service     = new SubscriptionService();
                var resultToken = await service.UpdateAsync(subcription.StripeSubCriptionID, options);

                if (resultToken.CancelAtPeriodEnd)
                {
                    return(true);
                }

                else
                {
                    return(false);
                }
            }
            else
            {
                return(false);
            }
        }
Exemplo n.º 7
0
        private Stripe.Subscription UpdateStripeSubscriptionPlan(StripeSubUpdatePlanRequest request)
        {
            StripeConfiguration.ApiKey = _appKeys.StripeApiKey;

            var service = new SubscriptionService();

            Stripe.Subscription subscription = service.Get(request.SubscriptionId);

            var items = new List <SubscriptionItemOptions>
            {
                new SubscriptionItemOptions
                {
                    Id    = subscription.Items.Data[0].Id,
                    Price = request.PriceId,
                }
            };

            var options = new SubscriptionUpdateOptions
            {
                Items = items,
            };

            options.AddExpand("latest_invoice.payment_intent");
            subscription = service.Update(request.SubscriptionId, options);
            return(subscription);
        }
        public async Task CancelCommunitySubscription(Community community, BillingRecord billing)
        {
            var plan = plans.GetPlan(billing.PlanId) !;

            if (plan.Stripe is StripePlan stripePlan)
            {
                try
                {
                    var update = new SubscriptionUpdateOptions()
                    {
                        CancelAtPeriodEnd = true
                    };
                    await Subscriptions.UpdateAsync(billing.Stripe !.SubscriptionId, update, RequestOptions);
                }
                catch (StripeException e)
                {
                    logger.LogError(e, "Failed to update stripe subscription");
                    throw;
                }
            }
            else
            {
                throw new ArgumentException("StripePaymentProcessor requires a StripePlan");
            }
        }
Exemplo n.º 9
0
        public string TogglePause(string togglePause)
        {   //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
            //sk_test_51Gzaa1HAh8lBnQxza9cOAzY7LbfgQ4FWX2sYqiuHsoVWJg4mNDppueQkAVd0XIPU4GhcrNBca8aemNgr24m4jDv200ooFw0Bhz
            StripeConfiguration.ApiKey = "sk_test_51Gzaa1HAh8lBnQxza9cOAzY7LbfgQ4FWX2sYqiuHsoVWJg4mNDppueQkAVd0XIPU4GhcrNBca8aemNgr24m4jDv200ooFw0Bhz";
            var msg = "";

            if (togglePause == "pause")
            {
                var options = new SubscriptionUpdateOptions
                {
                    PauseCollection = new SubscriptionPauseCollectionOptions
                    {
                        Behavior = "mark_uncollectible",
                    },
                };
                var service = new SubscriptionService();
                service.Update("sub_HZ5QvvcLgLx8vW", options);
                msg = "Subscription paused";
            }

            else if (togglePause == "resume")
            {
                var options = new SubscriptionUpdateOptions();
                options.AddExtraParam("pause_collection", "");
                var service = new SubscriptionService();
                service.Update("sub_HZ5QvvcLgLx8vW", options);
                msg = "Subscription resumed";
            }
            //ViewBag.message = msg;
            return(msg);
        }
Exemplo n.º 10
0
        // refer: https://stripe.com/docs/api/subscriptions/update
        public async Task UpdateSubscriptionAsync(string subscriptionId, Action <SubscriptionUpdateOptions> action)
        {
            var options = new SubscriptionUpdateOptions();

            action(options);

            await _subscriptionService.UpdateAsync(subscriptionId, options);
        }
Exemplo n.º 11
0
        public Subscription Update(string customerId, string subscriptionId, SubscriptionUpdateOptions updateOptions)
        {
            if (updateOptions == null)
            {
                updateOptions = new SubscriptionUpdateOptions();
            }

            return(_stripeSubscriptionService.Update(subscriptionId, updateOptions));
        }
Exemplo n.º 12
0
        public SubscriptionServiceTest(
            StripeMockFixture stripeMockFixture,
            MockHttpClientFixture mockHttpClientFixture)
            : base(stripeMockFixture, mockHttpClientFixture)
        {
            this.service = new SubscriptionService(this.StripeClient);

            this.cancelOptions = new SubscriptionCancelOptions
            {
                InvoiceNow = true,
                Prorate    = true,
            };

            this.createOptions = new SubscriptionCreateOptions
            {
                Customer = "cus_123",
                Items    = new List <SubscriptionItemOptions>
                {
                    new SubscriptionItemOptions
                    {
                        Price    = "price_123",
                        Quantity = 2,
                    },
                    new SubscriptionItemOptions
                    {
                        PriceData = new SubscriptionItemPriceDataOptions
                        {
                            Currency  = "usd",
                            Product   = "prod_123",
                            Recurring = new SubscriptionItemPriceDataRecurringOptions
                            {
                                Interval      = "day",
                                IntervalCount = 15,
                            },
                            UnitAmountDecimal = 0.01234567890m, // Ensure decimals work
                        },
                        Quantity = 3,
                    },
                },
            };

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

            this.listOptions = new SubscriptionListOptions
            {
                Limit = 1,
            };
        }
Exemplo n.º 13
0
        public ActionResult continueSubscription()
        {
            StripeConfiguration.ApiKey = "sk_test_51GxEfiHhYK7K9XttqUpv12yjajZLs01TY95VhvzVfPEb5Ed8GaF3GFUV2iuhFZGkBgHoNib4iHBDlpALqWPplth6008EdMnnaw";

            var options = new SubscriptionUpdateOptions();

            options.AddExtraParam("pause_collection", "");
            var service = new SubscriptionService();

            service.Update("sub_HXNOGgEcJT2vvM", options);
            return(Redirect("/Home/Billing"));
        }
Exemplo n.º 14
0
        public async Task CancelSubscriptionAtPeriodEnd(Domain.Scheduling.Billing.Customer customer)
        {
            if (customer.Subscription == null)
            {
                throw new InvalidOperationException("No subscription to cancel.");
            }

            var opts = new SubscriptionUpdateOptions {
                CancelAtPeriodEnd = true
            };

            await subscriptionService.UpdateAsync(customer.Subscription.BillingReference.BillingId, opts);

            customer.Subscription.CancellingAtPeriodEnd = true;
        }
Exemplo n.º 15
0
        public ActionResult pauseSubscription()
        {
            StripeConfiguration.ApiKey = "sk_test_51GxEfiHhYK7K9XttqUpv12yjajZLs01TY95VhvzVfPEb5Ed8GaF3GFUV2iuhFZGkBgHoNib4iHBDlpALqWPplth6008EdMnnaw";

            var options = new SubscriptionUpdateOptions
            {
                PauseCollection = new SubscriptionPauseCollectionOptions
                {
                    Behavior = "void",
                },
            };
            var service = new SubscriptionService();

            service.Update("sub_HXNOGgEcJT2vvM", options);
            return(Redirect("/Home/Billing"));
        }
    public async Task CancelSubscriptionAtPeriodEnd(string customerEmail)
    {
        var spec   = new InactiveInvitationByEmailSpec(customerEmail);
        var invite = await _invitationRepository.GetBySpecAsync(spec);

        if (invite is null)
        {
            throw new InvitationNotFoundException(customerEmail);
        }
        var subscriptionId = invite.PaymentHandlerSubscriptionId;

        var subscriptionCancelOptions = new SubscriptionUpdateOptions
        {
            CancelAtPeriodEnd = true,
        };

        _subscriptionService.Update(subscriptionId, subscriptionCancelOptions);
    }
Exemplo n.º 17
0
        public SubscriptionServiceTest(
            StripeMockFixture stripeMockFixture,
            MockHttpClientFixture mockHttpClientFixture)
            : base(stripeMockFixture, mockHttpClientFixture)
        {
            this.service = new SubscriptionService(this.StripeClient);

            this.cancelOptions = new SubscriptionCancelOptions
            {
                InvoiceNow = true,
                Prorate    = true,
            };

            this.createOptions = new SubscriptionCreateOptions
            {
                Customer = "cus_123",
                Items    = new List <SubscriptionItemOption>
                {
                    new SubscriptionItemOption
                    {
                        Plan     = "plan_123",
                        Quantity = 2,
                    },
                    new SubscriptionItemOption
                    {
                        Plan     = "plan_124",
                        Quantity = 3,
                    },
                },
            };

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

            this.listOptions = new SubscriptionListOptions
            {
                Limit = 1,
            };
        }
Exemplo n.º 18
0
        public async Task <PaymentGatewayResult <IPaymentSubscription> > UpdateSubscriptionAsync(string planId, ChargeType type,
                                                                                                 string subscriptionId, string?coupon)
        {
            try
            {
                var subscription = await _subscriptionService.GetAsync(subscriptionId);

                if (subscription == null)
                {
                    throw new StripeException("Subscription Not Found")
                          {
                              HttpStatusCode = HttpStatusCode.NotFound
                          }
                }
                ;
                var opt = new SubscriptionUpdateOptions
                {
                    CancelAtPeriodEnd = false,
                    Items             = new List <SubscriptionItemUpdateOption> {
                        new SubscriptionItemUpdateOption {
                            Id     = subscription.Items.Data.FirstOrDefault()?.Id,
                            PlanId = planId
                        },
                    },
                    CouponId         = coupon,
                    Prorate          = true,
                    ProrationDate    = DateTime.UtcNow,
                    CollectionMethod = _chargeTypes[(int)type],
                };
                if (type == ChargeType.Manual)
                {
                    opt.DaysUntilDue = _appSettings.Stripe.InvoiceDueDays;
                }

                subscription = await _subscriptionService.UpdateAsync(subscription.Id, opt);

                return(PaymentGatewayResult <IPaymentSubscription> .Success(_mapper.Map <IPaymentSubscription>(subscription)));
            }
            catch (StripeException e)
            {
                return(PaymentGatewayResult <IPaymentSubscription> .Failed(e));
            }
        }
Exemplo n.º 19
0
        public async Task UndoCancellingSubscription(Domain.Scheduling.Billing.Customer customer)
        {
            if (customer.Subscription == null)
            {
                throw new InvalidOperationException("No subscription to cancel.");
            }

            if (!customer.Subscription.CancellingAtPeriodEnd)
            {
                throw new InvalidOperationException("Cannot undo what has not been done");
            }

            var opts = new SubscriptionUpdateOptions {
                CancelAtPeriodEnd = false
            };

            await subscriptionService.UpdateAsync(customer.Subscription.BillingReference.BillingId, opts);

            customer.Subscription.CancellingAtPeriodEnd = false;
        }
Exemplo n.º 20
0
        public ActionResult<Subscription> UpdateSubscription([FromBody] UpdateSubscriptionRequest req)
        {
            var service = new SubscriptionService();
            var subscription = service.Get(req.Subscription);

            var options = new SubscriptionUpdateOptions
            {
                CancelAtPeriodEnd = false,
                Items = new List<SubscriptionItemOptions>
                {
                    new SubscriptionItemOptions
                    {
                        Id = subscription.Items.Data[0].Id,
                        Price = Environment.GetEnvironmentVariable(req.NewPrice),
                    }
                }
            };
            var updatedSubscription = service.Update(req.Subscription, options);
            return updatedSubscription;
        }
        public SubscriptionServiceTest()
        {
            this.service = new SubscriptionService();

            this.cancelOptions = new SubscriptionCancelOptions
            {
                InvoiceNow = true,
                Prorate    = true,
            };

            this.createOptions = new SubscriptionCreateOptions
            {
                CustomerId = "cus_123",
                Items      = new List <SubscriptionItemOption>
                {
                    new SubscriptionItemOption
                    {
                        PlanId   = "plan_123",
                        Quantity = 2
                    },
                    new SubscriptionItemOption
                    {
                        PlanId   = "plan_124",
                        Quantity = 3
                    },
                },
            };

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

            this.listOptions = new SubscriptionListOptions
            {
                Limit = 1,
            };
        }
Exemplo n.º 22
0
        public Subscription Change(string subscriptionId, string subscriptionItemId, string overageSubscriptionItemId, string monthlyPlanId, string overagePlanId)
        {
            var subscriptionService = new Stripe.SubscriptionService();

            var items = new List <SubscriptionItemOptions> {
                new SubscriptionItemOptions {
                    Plan = monthlyPlanId,
                },
                new SubscriptionItemOptions {
                    Plan = overagePlanId,
                }
            };

            var options = new SubscriptionUpdateOptions
            {
                CancelAtPeriodEnd = false,
                Items             = items,
            };

            return(subscriptionService.Update(subscriptionId, options));
        }
Exemplo n.º 23
0
        public IActionResult Upgrade(string subKey, string plan)
        {
            // Set your secret key. Remember to switch to your live secret key in production!
            // See your keys here: https://dashboard.stripe.com/account/apikeys
            StripeConfiguration.ApiKey = _configuration["Stripe:SecretKey"];

            var          service      = new SubscriptionService();
            Subscription subscription = service.Get(subKey);

            var planId = _configuration["Stripe:Daily5"];

            if (plan == "Daily10")
            {
                planId = _configuration["Stripe:Daily10"];
            }

            var items = new List <SubscriptionItemOptions> {
                new SubscriptionItemOptions {
                    Id    = subscription.Items.Data[0].Id,
                    Price = planId,
                },
            };

            var options = new SubscriptionUpdateOptions
            {
                CancelAtPeriodEnd = false,
                ProrationBehavior = "create_prorations",
                Items             = items,
            };

            subscription = service.Update(subKey, options);

            var subUpdate = _database.Subscriptions.Where(i => i.SubID == subKey).Single();

            subUpdate.PlanID = planId;

            _database.SaveChanges();
            return(View("UpdateResult"));
        }
Exemplo n.º 24
0
        public ActionResult Resume()
        {
            try
            {
                StripeConfiguration.ApiKey            = key;
                StripeConfiguration.MaxNetworkRetries = 2;

                var options = new SubscriptionUpdateOptions();
                options.AddExtraParam("pause_collection", "");
                var service = new SubscriptionService();
                service.Update(subscriptionId, options);

                return(View("OrderStatus"));
            }
            catch (StripeException e)
            {
                var x = new
                {
                    status  = "Failed",
                    message = e.Message
                };
                return(this.Json(x));
            }
        }
        public async Task <IActionResult> Webhook()
        {
            var   json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync();
            Event stripeEvent;

            try
            {
                stripeEvent = EventUtility.ConstructEvent(
                    json,
                    Request.Headers["Stripe-Signature"],
                    this.options.Value.WebhookSecret
                    );
                Console.WriteLine($"Webhook notification with type: {stripeEvent.Type} found for {stripeEvent.Id}");
            }
            catch (Exception e)
            {
                Console.WriteLine($"Something failed {e}");
                return(BadRequest());
            }

            if (stripeEvent.Type == "invoice.payment_succeeded")
            {
                var invoice = stripeEvent.Data.Object as Invoice;

                if (invoice.BillingReason == "subscription_create")
                {
                    // The subscription automatically activates after successful payment
                    // Set the payment method used to pay the first invoice
                    // as the default payment method for that subscription

                    // Retrieve the payment intent used to pay the subscription
                    var service       = new PaymentIntentService();
                    var paymentIntent = service.Get(invoice.PaymentIntentId);

                    // Set the default payment method
                    var options = new SubscriptionUpdateOptions
                    {
                        DefaultPaymentMethod = paymentIntent.PaymentMethodId,
                    };
                    var subscriptionService = new SubscriptionService();
                    subscriptionService.Update(invoice.SubscriptionId, options);

                    Console.WriteLine($"Default payment method set for subscription: {paymentIntent.PaymentMethodId}");
                }
                Console.WriteLine($"Payment succeeded for invoice: {stripeEvent.Id}");
            }

            if (stripeEvent.Type == "invoice.paid")
            {
                // Used to provision services after the trial has ended.
                // The status of the invoice will show up as paid. Store the status in your
                // database to reference when a user accesses your service to avoid hitting rate
                // limits.
            }
            if (stripeEvent.Type == "invoice.payment_failed")
            {
                // If the payment fails or the customer does not have a valid payment method,
                // an invoice.payment_failed event is sent, the subscription becomes past_due.
                // Use this webhook to notify your user that their payment has
                // failed and to retrieve new card details.
            }
            if (stripeEvent.Type == "invoice.finalized")
            {
                // If you want to manually send out invoices to your customers
                // or store them locally to reference to avoid hitting Stripe rate limits.
            }
            if (stripeEvent.Type == "customer.subscription.deleted")
            {
                // handle subscription cancelled automatically based
                // upon your subscription settings. Or if the user cancels it.
            }
            if (stripeEvent.Type == "customer.subscription.trial_will_end")
            {
                // Send notification to your user that the trial will end
            }

            return(Ok());
        }
Exemplo n.º 26
0
        public async Task <ActionResult <ChangePlanResult> > ChangePlanAsync(string id, string planId, string stripeToken = null, string last4 = null, string couponId = null)
        {
            if (String.IsNullOrEmpty(id) || !CanAccessOrganization(id))
            {
                return(NotFound());
            }

            if (!_options.StripeOptions.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(_plans.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 client              = new StripeClient(_options.StripeOptions.StripeApiKey);
            var customerService     = new CustomerService(client);
            var subscriptionService = new SubscriptionService(client);

            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, _plans.FreePlan.Id) && String.Equals(plan.Id, _plans.FreePlan.Id))
                {
                    if (!String.IsNullOrEmpty(organization.StripeCustomerId))
                    {
                        var subs = await subscriptionService.ListAsync(new SubscriptionListOptions { Customer = organization.StripeCustomerId });

                        foreach (var sub in subs.Where(s => !s.CanceledAt.HasValue))
                        {
                            await subscriptionService.CancelAsync(sub.Id, new SubscriptionCancelOptions());
                        }
                    }

                    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 CustomerCreateOptions {
                        Source      = stripeToken,
                        Plan        = planId,
                        Description = organization.Name,
                        Email       = CurrentUser.EmailAddress
                    };

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

                    var customer = await customerService.CreateAsync(createCustomer);

                    organization.BillingStatus = BillingStatus.Active;
                    organization.RemoveSuspension();
                    organization.StripeCustomerId = customer.Id;
                    if (customer.Sources.Data.Count > 0)
                    {
                        organization.CardLast4 = (customer.Sources.Data.First() as Card)?.Last4;
                    }
                }
                else
                {
                    var update = new SubscriptionUpdateOptions {
                        Items = new List <SubscriptionItemOptions>()
                    };
                    var create = new SubscriptionCreateOptions {
                        Customer = organization.StripeCustomerId, Items = new List <SubscriptionItemOptions>()
                    };
                    bool cardUpdated = false;

                    var customerUpdateOptions = new CustomerUpdateOptions {
                        Description = organization.Name, Email = CurrentUser.EmailAddress
                    };
                    if (!String.IsNullOrEmpty(stripeToken))
                    {
                        customerUpdateOptions.Source = stripeToken;
                        cardUpdated = true;
                    }

                    await customerService.UpdateAsync(organization.StripeCustomerId, customerUpdateOptions);

                    var subscriptionList = await subscriptionService.ListAsync(new SubscriptionListOptions { Customer = organization.StripeCustomerId });

                    var subscription = subscriptionList.FirstOrDefault(s => !s.CanceledAt.HasValue);
                    if (subscription != null)
                    {
                        update.Items.Add(new SubscriptionItemOptions {
                            Id = subscription.Items.Data[0].Id, Plan = planId
                        });
                        await subscriptionService.UpdateAsync(subscription.Id, update);
                    }
                    else
                    {
                        create.Items.Add(new SubscriptionItemOptions {
                            Plan = planId
                        });
                        await subscriptionService.CreateAsync(create);
                    }

                    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 ex) {
                using (_logger.BeginScope(new ExceptionlessState().Tag("Change Plan").Identity(CurrentUser.EmailAddress).Property("User", CurrentUser).SetHttpContext(HttpContext)))
                    _logger.LogCritical(ex, "An error occurred while trying to update your billing plan: {Message}", ex.Message);

                return(Ok(ChangePlanResult.FailWithMessage(ex.Message)));
            }

            return(Ok(new ChangePlanResult {
                Success = true
            }));
        }
Exemplo n.º 27
0
        public async Task <PaymentGatewayResult <IPaymentSubscription> > UpdateSubscriptionAsync(string id, SubscriptionUpdateOptions options)
        {
            try
            {
                var subscription = await _subscriptionService.GetAsync(id);

                subscription = await _subscriptionService.UpdateAsync(subscription.Id, options);

                return(PaymentGatewayResult <IPaymentSubscription> .Success(_mapper.Map <IPaymentSubscription>(subscription)));
            }
            catch (StripeException e)
            {
                return(PaymentGatewayResult <IPaymentSubscription> .Failed(e));
            }
        }
Exemplo n.º 28
0
 public UpdateSubscriptionCommand(SubscriptionUpdateOptions options)
 {
     _options = options;
 }
Exemplo n.º 29
0
        public virtual async Task <Subscription> Update(string customerId, string subscriptionId, SubscriptionUpdateOptions updateOptions)
        {
            var url = string.Format(Urls.Subscriptions + "/{1}", customerId, subscriptionId);

            url = this.ApplyAllParameters(updateOptions, url, false);

            var response = await Requestor.Post(url);

            return(Mapper <Subscription> .MapFromJson(response));
        }
        public ActionResult <UpdateSubscriptionResponse> UpdateSubscription([FromBody] UpdateSubscriptionRequest req)
        {
            if (!ModelState.IsValid)
            {
                return(this.FailWithMessage("invalid params"));
            }
            var newPrice = Environment.GetEnvironmentVariable(req.NewPrice);

            if (newPrice is null || newPrice == "")
            {
                return(this.FailWithMessage($"No price with the new price ID ({req.NewPrice}) found in .env"));
            }

            var          service = new SubscriptionService();
            Subscription subscription;

            try
            {
                subscription = service.Get(req.Subscription);
            }
            catch (StripeException e)
            {
                return(this.FailWithMessage($"Failed to retrieve subscription: {e}"));
            }
            var currentPrice = subscription.Items.Data[0].Price.Id;

            List <SubscriptionItemOptions> items;

            if (currentPrice == newPrice)
            {
                items = new List <SubscriptionItemOptions>
                {
                    new SubscriptionItemOptions
                    {
                        Id       = subscription.Items.Data[0].Id,
                        Quantity = req.Quantity,
                    },
                };
            }
            else
            {
                items = new List <SubscriptionItemOptions>
                {
                    new SubscriptionItemOptions
                    {
                        Id      = subscription.Items.Data[0].Id,
                        Deleted = true,
                    },
                    new SubscriptionItemOptions
                    {
                        Price    = newPrice,
                        Quantity = req.Quantity,
                    },
                };
            }

            var options = new SubscriptionUpdateOptions
            {
                CancelAtPeriodEnd = false,
                Items             = items,
                ProrationBehavior = "always_invoice",
            };
            var updatedSubscription = service.Update(req.Subscription, options);

            return(new UpdateSubscriptionResponse
            {
                Subscription = updatedSubscription,
            });
        }