示例#1
0
        public async Task UpdateSubscription(string subscriptionId, string newPlanId, decimal newAmount, string interval)
        {
            var subscriptionService = new SubscriptionService();
            var subscription        = await subscriptionService.GetAsync(subscriptionId);

            if (!await DoesPlanExistAsync(newPlanId))
            {
                await CreatePlanAsync(newPlanId, newAmount, interval, ProductName);
            }

            var oldPlanId = subscription.Items.Data[0].Plan.Id;

            await subscriptionService.UpdateAsync(subscriptionId, new SubscriptionUpdateOptions
            {
                CancelAtPeriodEnd = false,
                Items             = new List <SubscriptionItemUpdateOption> {
                    new SubscriptionItemUpdateOption {
                        Id     = subscription.Items.Data[0].Id,
                        PlanId = newPlanId
                    }
                }
            });

            var invoiceService = new InvoiceService();
            var invoice        = await invoiceService.CreateAsync(new InvoiceCreateOptions
            {
                SubscriptionId = subscription.Id,
                CustomerId     = subscription.CustomerId
            });

            if (!invoice.Paid)
            {
                invoice = await invoiceService.PayAsync(invoice.Id, null);

                if (!invoice.Paid)
                {
                    await subscriptionService.UpdateAsync(subscriptionId, new SubscriptionUpdateOptions
                    {
                        CancelAtPeriodEnd = false,
                        Items             = new List <SubscriptionItemUpdateOption> {
                            new SubscriptionItemUpdateOption {
                                Id     = subscription.Items.Data[0].Id,
                                PlanId = oldPlanId
                            }
                        }
                    });

                    throw new UserFriendlyException(L("PaymentCouldNotCompleted"));
                }
            }

            var lastRecurringPayment = await _subscriptionPaymentRepository.GetByGatewayAndPaymentIdAsync(SubscriptionPaymentGatewayType.Stripe, subscriptionId);

            var payment = await _subscriptionPaymentRepository.GetLastPaymentOrDefaultAsync(
                tenantId : lastRecurringPayment.TenantId,
                SubscriptionPaymentGatewayType.Stripe,
                isRecurring : true);

            payment.Amount            = ConvertFromStripePrice(invoice.Total);
            payment.IsRecurring       = false;
            payment.ExternalPaymentId = invoice.ChargeId;
            payment.SetAsPaid();
        }