示例#1
0
        public async Task CancelAndRecoverChargesAsync(ISubscriber subscriber)
        {
            if (!string.IsNullOrWhiteSpace(subscriber.GatewaySubscriptionId))
            {
                var subscriptionService = new StripeSubscriptionService();
                await subscriptionService.CancelAsync(subscriber.GatewaySubscriptionId, false);
            }

            if (string.IsNullOrWhiteSpace(subscriber.GatewayCustomerId))
            {
                return;
            }

            var chargeService = new StripeChargeService();
            var charges       = await chargeService.ListAsync(new StripeChargeListOptions
            {
                CustomerId = subscriber.GatewayCustomerId
            });

            if (charges?.Data != null)
            {
                var refundService = new StripeRefundService();
                foreach (var charge in charges.Data.Where(c => !c.Refunded))
                {
                    await refundService.CreateAsync(charge.Id);
                }
            }

            var customerService = new StripeCustomerService();
            await customerService.DeleteAsync(subscriber.GatewayCustomerId);
        }
示例#2
0
        public static async Task <List <StripeTransaction> > GetStripeChargeTransactionsAsync(IMyConfiguration configuration, DateTime from, DateTime to)
        {
            // get stripe configuration parameters
            string stripeApiKey = configuration.GetValue("StripeApiKey");

            StripeConfiguration.SetApiKey(stripeApiKey);

            var chargeService = new StripeChargeService();

            chargeService.ExpandBalanceTransaction = true;
            chargeService.ExpandCustomer           = true;
            chargeService.ExpandInvoice            = true;

            var allCharges = new List <StripeCharge>();
            var lastId     = String.Empty;

            int MAX_PAGINATION = 100;
            int itemsExpected  = MAX_PAGINATION;

            while (itemsExpected == MAX_PAGINATION)
            {
                IEnumerable <StripeCharge> charges = null;
                if (String.IsNullOrEmpty(lastId))
                {
                    charges = await chargeService.ListAsync(
                        new StripeChargeListOptions()
                    {
                        Limit   = MAX_PAGINATION,
                        Created = new StripeDateFilter
                        {
                            GreaterThanOrEqual = from,
                            LessThanOrEqual    = to
                        }
                    });

                    itemsExpected = charges.Count();
                }
                else
                {
                    charges = await chargeService.ListAsync(
                        new StripeChargeListOptions()
                    {
                        Limit         = MAX_PAGINATION,
                        StartingAfter = lastId,
                        Created       = new StripeDateFilter
                        {
                            GreaterThanOrEqual = from,
                            LessThanOrEqual    = to
                        }
                    });

                    itemsExpected = charges.Count();
                }

                allCharges.AddRange(charges);
                if (allCharges.Count() > 0)
                {
                    lastId = charges.LastOrDefault().Id;
                }
            }

            var stripeTransactions = new List <StripeTransaction>();

            foreach (var charge in allCharges)
            {
                // only process the charges that were successfull, aka Paid
                if (charge.Paid)
                {
                    var stripeTransaction = new StripeTransaction();
                    stripeTransaction.TransactionID = charge.Id;
                    stripeTransaction.Created       = charge.Created;
                    stripeTransaction.Paid          = charge.Paid;
                    stripeTransaction.CustomerEmail = charge.Metadata["email"];
                    stripeTransaction.OrderID       = charge.Metadata["order_id"];
                    stripeTransaction.Amount        = (decimal)charge.Amount / 100;
                    stripeTransaction.Net           = (decimal)charge.BalanceTransaction.Net / 100;
                    stripeTransaction.Fee           = (decimal)charge.BalanceTransaction.Fee / 100;
                    stripeTransaction.Currency      = charge.Currency;
                    stripeTransaction.Description   = charge.Description;
                    stripeTransaction.Status        = charge.Status;
                    decimal amountRefunded = (decimal)charge.AmountRefunded / 100;
                    if (amountRefunded > 0)
                    {
                        // if anything has been refunded
                        // don't add if amount refunded and amount is the same (full refund)
                        if (stripeTransaction.Amount - amountRefunded == 0)
                        {
                            continue;
                        }
                        else
                        {
                            stripeTransaction.Amount = stripeTransaction.Amount - amountRefunded;
                            stripeTransaction.Net    = stripeTransaction.Net - amountRefunded;
                        }
                    }
                    stripeTransactions.Add(stripeTransaction);
                }
            }
            return(stripeTransactions);
        }
示例#3
0
        public async Task <Tuple <Organization, OrganizationUser> > SignUpAsync(OrganizationSignup signup)
        {
            var plan = StaticStore.Plans.FirstOrDefault(p => p.Type == signup.Plan && !p.Disabled);

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

            var                customerService     = new StripeCustomerService();
            var                subscriptionService = new StripeSubscriptionService();
            StripeCustomer     customer            = null;
            StripeSubscription subscription        = null;

            if (!plan.CanBuyAdditionalSeats && signup.AdditionalSeats > 0)
            {
                throw new BadRequestException("Plan does not allow additional users.");
            }

            if (plan.CanBuyAdditionalSeats && plan.MaxAdditionalSeats.HasValue &&
                signup.AdditionalSeats > plan.MaxAdditionalSeats.Value)
            {
                throw new BadRequestException($"Selected plan allows a maximum of " +
                                              $"{plan.MaxAdditionalSeats.GetValueOrDefault(0)} additional users.");
            }

            if (plan.Type == PlanType.Free)
            {
                var ownerExistingOrgCount =
                    await _organizationUserRepository.GetCountByFreeOrganizationAdminUserAsync(signup.Owner.Id);

                if (ownerExistingOrgCount > 0)
                {
                    throw new BadRequestException("You can only be an admin of one free organization.");
                }
            }
            else
            {
                customer = await customerService.CreateAsync(new StripeCustomerCreateOptions
                {
                    Description = signup.BusinessName,
                    Email       = signup.BillingEmail,
                    SourceToken = signup.PaymentToken
                });

                var subCreateOptions = new StripeSubscriptionCreateOptions
                {
                    Items = new List <StripeSubscriptionItemOption>
                    {
                        new StripeSubscriptionItemOption
                        {
                            PlanId   = plan.StripePlanId,
                            Quantity = 1
                        }
                    }
                };

                if (signup.AdditionalSeats > 0)
                {
                    subCreateOptions.Items.Add(new StripeSubscriptionItemOption
                    {
                        PlanId   = plan.StripeSeatPlanId,
                        Quantity = signup.AdditionalSeats
                    });
                }

                try
                {
                    subscription = await subscriptionService.CreateAsync(customer.Id, subCreateOptions);
                }
                catch (StripeException)
                {
                    if (customer != null)
                    {
                        await customerService.DeleteAsync(customer.Id);
                    }

                    throw;
                }
            }

            var organization = new Organization
            {
                Name                 = signup.Name,
                BillingEmail         = signup.BillingEmail,
                BusinessName         = signup.BusinessName,
                PlanType             = plan.Type,
                Seats                = (short)(plan.BaseSeats + signup.AdditionalSeats),
                MaxSubvaults         = plan.MaxSubvaults,
                Plan                 = plan.Name,
                StripeCustomerId     = customer?.Id,
                StripeSubscriptionId = subscription?.Id,
                CreationDate         = DateTime.UtcNow,
                RevisionDate         = DateTime.UtcNow
            };

            try
            {
                await _organizationRepository.CreateAsync(organization);

                var orgUser = new OrganizationUser
                {
                    OrganizationId     = organization.Id,
                    UserId             = signup.Owner.Id,
                    Key                = signup.OwnerKey,
                    Type               = OrganizationUserType.Owner,
                    Status             = OrganizationUserStatusType.Confirmed,
                    AccessAllSubvaults = true,
                    CreationDate       = DateTime.UtcNow,
                    RevisionDate       = DateTime.UtcNow
                };

                await _organizationUserRepository.CreateAsync(orgUser);

                // push
                await _pushService.PushSyncOrgKeysAsync(signup.Owner.Id);

                return(new Tuple <Organization, OrganizationUser>(organization, orgUser));
            }
            catch
            {
                if (subscription != null)
                {
                    await subscriptionService.CancelAsync(subscription.Id, false);
                }

                if (customer != null)
                {
                    var chargeService = new StripeChargeService();
                    var charges       = await chargeService.ListAsync(new StripeChargeListOptions { CustomerId = customer.Id });

                    if (charges?.Data != null)
                    {
                        var refundService = new StripeRefundService();
                        foreach (var charge in charges.Data.Where(c => !c.Refunded))
                        {
                            await refundService.CreateAsync(charge.Id);
                        }
                    }

                    await customerService.DeleteAsync(customer.Id);
                }

                if (organization.Id != default(Guid))
                {
                    await _organizationRepository.DeleteAsync(organization);
                }

                throw;
            }
        }
示例#4
0
        public async Task <OrganizationBilling> GetBillingAsync(Organization organization)
        {
            var orgBilling          = new OrganizationBilling();
            var customerService     = new StripeCustomerService();
            var subscriptionService = new StripeSubscriptionService();
            var chargeService       = new StripeChargeService();
            var invoiceService      = new StripeInvoiceService();

            if (!string.IsNullOrWhiteSpace(organization.StripeCustomerId))
            {
                var customer = await customerService.GetAsync(organization.StripeCustomerId);

                if (customer != null)
                {
                    if (!string.IsNullOrWhiteSpace(customer.DefaultSourceId) && customer.Sources?.Data != null)
                    {
                        if (customer.DefaultSourceId.StartsWith("card_"))
                        {
                            orgBilling.PaymentSource =
                                customer.Sources.Data.FirstOrDefault(s => s.Card?.Id == customer.DefaultSourceId);
                        }
                        else if (customer.DefaultSourceId.StartsWith("ba_"))
                        {
                            orgBilling.PaymentSource =
                                customer.Sources.Data.FirstOrDefault(s => s.BankAccount?.Id == customer.DefaultSourceId);
                        }
                    }

                    var charges = await chargeService.ListAsync(new StripeChargeListOptions
                    {
                        CustomerId = customer.Id,
                        Limit      = 20
                    });

                    orgBilling.Charges = charges?.Data?.OrderByDescending(c => c.Created);
                }
            }

            if (!string.IsNullOrWhiteSpace(organization.StripeSubscriptionId))
            {
                var sub = await subscriptionService.GetAsync(organization.StripeSubscriptionId);

                if (sub != null)
                {
                    orgBilling.Subscription = sub;
                }

                if (!sub.CanceledAt.HasValue && !string.IsNullOrWhiteSpace(organization.StripeCustomerId))
                {
                    try
                    {
                        var upcomingInvoice = await invoiceService.UpcomingAsync(organization.StripeCustomerId);

                        if (upcomingInvoice != null)
                        {
                            orgBilling.UpcomingInvoice = upcomingInvoice;
                        }
                    }
                    catch (StripeException) { }
                }
            }

            return(orgBilling);
        }
示例#5
0
        public async Task <BillingInfo> GetBillingAsync(ISubscriber subscriber)
        {
            var billingInfo         = new BillingInfo();
            var customerService     = new StripeCustomerService();
            var subscriptionService = new StripeSubscriptionService();
            var chargeService       = new StripeChargeService();
            var invoiceService      = new StripeInvoiceService();

            if (!string.IsNullOrWhiteSpace(subscriber.GatewayCustomerId))
            {
                var customer = await customerService.GetAsync(subscriber.GatewayCustomerId);

                if (customer != null)
                {
                    if (!string.IsNullOrWhiteSpace(customer.DefaultSourceId) && customer.Sources?.Data != null)
                    {
                        if (customer.DefaultSourceId.StartsWith("card_"))
                        {
                            var source = customer.Sources.Data.FirstOrDefault(s => s.Card?.Id == customer.DefaultSourceId);
                            if (source != null)
                            {
                                billingInfo.PaymentSource = new BillingInfo.BillingSource(source);
                            }
                        }
                        else if (customer.DefaultSourceId.StartsWith("ba_"))
                        {
                            var source = customer.Sources.Data
                                         .FirstOrDefault(s => s.BankAccount?.Id == customer.DefaultSourceId);
                            if (source != null)
                            {
                                billingInfo.PaymentSource = new BillingInfo.BillingSource(source);
                            }
                        }
                    }

                    var charges = await chargeService.ListAsync(new StripeChargeListOptions
                    {
                        CustomerId = customer.Id,
                        Limit      = 20
                    });

                    billingInfo.Charges = charges?.Data?.OrderByDescending(c => c.Created)
                                          .Select(c => new BillingInfo.BillingCharge(c));
                }
            }

            if (!string.IsNullOrWhiteSpace(subscriber.GatewaySubscriptionId))
            {
                var sub = await subscriptionService.GetAsync(subscriber.GatewaySubscriptionId);

                if (sub != null)
                {
                    billingInfo.Subscription = new BillingInfo.BillingSubscription(sub);
                }

                if (!sub.CanceledAt.HasValue && !string.IsNullOrWhiteSpace(subscriber.GatewayCustomerId))
                {
                    try
                    {
                        var upcomingInvoice = await invoiceService.UpcomingAsync(subscriber.GatewayCustomerId);

                        if (upcomingInvoice != null)
                        {
                            billingInfo.UpcomingInvoice = new BillingInfo.BillingInvoice(upcomingInvoice);
                        }
                    }
                    catch (StripeException) { }
                }
            }

            return(billingInfo);
        }