1
0
mirror of https://github.com/bitwarden/server.git synced 2025-04-18 03:28:15 -05:00

use existing stripe customer for premium signup

This commit is contained in:
Kyle Spearrin 2019-02-18 16:08:58 -05:00
parent b036657d78
commit ad577bafcc

View File

@ -164,13 +164,32 @@ namespace Bit.Core.Services
var invoiceService = new InvoiceService();
var customerService = new CustomerService();
var createdStripeCustomer = false;
string stripeCustomerId = null;
Braintree.Transaction braintreeTransaction = null;
Braintree.Customer braintreeCustomer = null;
string stipeCustomerSourceToken = null;
var stripeCustomerMetadata = new Dictionary<string, string>();
var stripePaymentMethod = paymentMethodType == PaymentMethodType.Card ||
paymentMethodType == PaymentMethodType.BankAccount;
if(user.Gateway == GatewayType.Stripe && !string.IsNullOrWhiteSpace(user.GatewayCustomerId))
{
try
{
await UpdatePaymentMethodAsync(user, paymentMethodType, paymentToken);
stripeCustomerId = user.GatewayCustomerId;
createdStripeCustomer = false;
}
catch(Exception)
{
stripeCustomerId = null;
}
}
if(string.IsNullOrWhiteSpace(stripeCustomerId))
{
string stipeCustomerSourceToken = null;
var stripeCustomerMetadata = new Dictionary<string, string>();
if(stripePaymentMethod)
{
stipeCustomerSourceToken = paymentToken;
@ -209,10 +228,13 @@ namespace Bit.Core.Services
SourceToken = stipeCustomerSourceToken,
Metadata = stripeCustomerMetadata
});
stripeCustomerId = customer.Id;
createdStripeCustomer = true;
}
var subCreateOptions = new SubscriptionCreateOptions
{
CustomerId = customer.Id,
CustomerId = stripeCustomerId,
Items = new List<SubscriptionItemOption>(),
Metadata = new Dictionary<string, string>
{
@ -243,11 +265,11 @@ namespace Bit.Core.Services
{
var previewInvoice = await invoiceService.UpcomingAsync(new UpcomingInvoiceOptions
{
CustomerId = customer.Id,
CustomerId = stripeCustomerId,
SubscriptionItems = ToInvoiceSubscriptionItemOptions(subCreateOptions.Items)
});
await customerService.UpdateAsync(customer.Id, new CustomerUpdateOptions
await customerService.UpdateAsync(stripeCustomerId, new CustomerUpdateOptions
{
AccountBalance = -1 * previewInvoice.AmountDue
});
@ -314,7 +336,10 @@ namespace Bit.Core.Services
}
catch(Exception e)
{
await customerService.DeleteAsync(customer.Id);
if(createdStripeCustomer && !string.IsNullOrWhiteSpace(stripeCustomerId))
{
await customerService.DeleteAsync(stripeCustomerId);
}
if(braintreeTransaction != null)
{
await _btGateway.Transaction.RefundAsync(braintreeTransaction.Id);
@ -327,7 +352,7 @@ namespace Bit.Core.Services
}
user.Gateway = GatewayType.Stripe;
user.GatewayCustomerId = customer.Id;
user.GatewayCustomerId = stripeCustomerId;
user.GatewaySubscriptionId = subscription.Id;
user.Premium = true;
user.PremiumExpirationDate = subscription.CurrentPeriodEnd;