public async Task ReplacePaymentMethodAsync(Guid organizationId, string paymentToken) { var organization = await _organizationRepository.GetByIdAsync(organizationId); if (organization == null) { throw new NotFoundException(); } var cardService = new StripeCardService(); var customerService = new StripeCustomerService(); StripeCustomer customer = null; if (!string.IsNullOrWhiteSpace(organization.StripeCustomerId)) { customer = await customerService.GetAsync(organization.StripeCustomerId); } if (customer == null) { customer = await customerService.CreateAsync(new StripeCustomerCreateOptions { Description = organization.BusinessName, Email = organization.BillingEmail, SourceToken = paymentToken }); organization.StripeCustomerId = customer.Id; await _organizationRepository.ReplaceAsync(organization); } await cardService.CreateAsync(customer.Id, new StripeCardCreateOptions { SourceToken = paymentToken }); if (!string.IsNullOrWhiteSpace(customer.DefaultSourceId)) { await cardService.DeleteAsync(customer.Id, customer.DefaultSourceId); } }
public async Task <bool> UpdatePaymentMethodAsync(ISubscriber subscriber, string paymentToken) { if (subscriber == null) { throw new ArgumentNullException(nameof(subscriber)); } if (subscriber.Gateway.HasValue && subscriber.Gateway.Value != Enums.GatewayType.Stripe) { throw new GatewayException("Switching from one payment type to another is not supported. " + "Contact us for assistance."); } var updatedSubscriber = false; var cardService = new StripeCardService(); var bankSerice = new BankAccountService(); var customerService = new StripeCustomerService(); StripeCustomer customer = null; if (!string.IsNullOrWhiteSpace(subscriber.GatewayCustomerId)) { customer = await customerService.GetAsync(subscriber.GatewayCustomerId); } if (customer == null) { customer = await customerService.CreateAsync(new StripeCustomerCreateOptions { Description = subscriber.BillingName(), Email = subscriber.BillingEmailAddress(), SourceToken = paymentToken }); subscriber.Gateway = Enums.GatewayType.Stripe; subscriber.GatewayCustomerId = customer.Id; updatedSubscriber = true; } else { if (paymentToken.StartsWith("btok_")) { await bankSerice.CreateAsync(customer.Id, new BankAccountCreateOptions { SourceToken = paymentToken }); } else { await cardService.CreateAsync(customer.Id, new StripeCardCreateOptions { SourceToken = paymentToken }); } if (!string.IsNullOrWhiteSpace(customer.DefaultSourceId)) { var source = customer.Sources.FirstOrDefault(s => s.Id == customer.DefaultSourceId); if (source.BankAccount != null) { await bankSerice.DeleteAsync(customer.Id, customer.DefaultSourceId); } else if (source.Card != null) { await cardService.DeleteAsync(customer.Id, customer.DefaultSourceId); } } } return(updatedSubscriber); }