1
0
mirror of https://github.com/bitwarden/server.git synced 2025-07-03 17:12:49 -05:00

[AC-1938] Update provider payment method (#4140)

* Refactored GET provider subscription

Refactoring this endpoint and its associated tests in preparation for the addition of more endpoints that share similar patterns

* Replaced StripePaymentService call in AccountsController, OrganizationsController

This was made in error during a previous PR. Since this is not related to Consolidated Billing, we want to try not to include it in these changes.

* Removing GetPaymentInformation call from ProviderBillingService

This method is a good call for the SubscriberService as we'll want to extend the functionality to all subscriber types

* Refactored GetTaxInformation to use Billing owned DTO

* Add UpdateTaxInformation to SubscriberService

* Added GetTaxInformation and UpdateTaxInformation endpoints to ProviderBillingController

* Added controller to manage creation of Stripe SetupIntents

With the deprecation of the Sources API, we need to move the bank account creation process to using SetupIntents. This controller brings both the creation of "card" and "us_bank_account" SetupIntents
under billing management.

* Added UpdatePaymentMethod method to SubscriberService

This method utilizes the SetupIntents created by the StripeController from the previous commit when a customer adds a card or us_bank_account payment method (Stripe). We need to cache the most recent SetupIntent for the subscriber so that we know which PaymentMethod is their most recent even when it hasn't been confirmed yet.

* Refactored GetPaymentMethod to use billing owned DTO and check setup intents

* Added GetPaymentMethod and UpdatePaymentMethod endpoints to ProviderBillingController

* Re-added GetPaymentInformation endpoint to consolidate API calls on the payment method page

* Added VerifyBankAccount endpoint to ProviderBillingController in order to finalize bank account payment methods

* Updated BitPayInvoiceRequestModel to support providers

* run dotnet format

* Conner's feedback

* Run dotnet format'
This commit is contained in:
Alex Morask
2024-06-03 11:00:52 -04:00
committed by GitHub
parent b42ebe6f1b
commit 2b43cde99b
34 changed files with 2478 additions and 540 deletions

View File

@ -1,7 +1,10 @@
using Bit.Core.Billing.Models;
using Bit.Core.Billing.Caches;
using Bit.Core.Billing.Models;
using Bit.Core.Entities;
using Bit.Core.Models.Business;
using Bit.Core.Enums;
using Bit.Core.Services;
using Bit.Core.Settings;
using Bit.Core.Utilities;
using Braintree;
using Microsoft.Extensions.Logging;
using Stripe;
@ -14,7 +17,9 @@ namespace Bit.Core.Billing.Services.Implementations;
public class SubscriberService(
IBraintreeGateway braintreeGateway,
IGlobalSettings globalSettings,
ILogger<SubscriberService> logger,
ISetupIntentCache setupIntentCache,
IStripeAdapter stripeAdapter) : ISubscriberService
{
public async Task CancelSubscription(
@ -132,6 +137,46 @@ public class SubscriberService(
}
}
public async Task<PaymentInformationDTO> GetPaymentInformation(
ISubscriber subscriber)
{
ArgumentNullException.ThrowIfNull(subscriber);
var customer = await GetCustomer(subscriber, new CustomerGetOptions
{
Expand = ["default_source", "invoice_settings.default_payment_method", "tax_ids"]
});
if (customer == null)
{
return null;
}
var accountCredit = customer.Balance * -1 / 100;
var paymentMethod = await GetMaskedPaymentMethodDTOAsync(subscriber.Id, customer);
var taxInformation = GetTaxInformationDTOFrom(customer);
return new PaymentInformationDTO(
accountCredit,
paymentMethod,
taxInformation);
}
public async Task<MaskedPaymentMethodDTO> GetPaymentMethod(
ISubscriber subscriber)
{
ArgumentNullException.ThrowIfNull(subscriber);
var customer = await GetCustomerOrThrow(subscriber, new CustomerGetOptions
{
Expand = ["default_source", "invoice_settings.default_payment_method"]
});
return await GetMaskedPaymentMethodDTOAsync(subscriber.Id, customer);
}
public async Task<Customer> GetCustomerOrThrow(
ISubscriber subscriber,
CustomerGetOptions customerGetOptions = null)
@ -240,6 +285,16 @@ public class SubscriberService(
}
}
public async Task<TaxInformationDTO> GetTaxInformation(
ISubscriber subscriber)
{
ArgumentNullException.ThrowIfNull(subscriber);
var customer = await GetCustomerOrThrow(subscriber, new CustomerGetOptions { Expand = ["tax_ids"] });
return GetTaxInformationDTOFrom(customer);
}
public async Task RemovePaymentMethod(
ISubscriber subscriber)
{
@ -332,113 +387,438 @@ public class SubscriberService(
}
}
public async Task<TaxInfo> GetTaxInformationAsync(ISubscriber subscriber)
public async Task UpdatePaymentMethod(
ISubscriber subscriber,
TokenizedPaymentMethodDTO tokenizedPaymentMethod)
{
ArgumentNullException.ThrowIfNull(subscriber);
ArgumentNullException.ThrowIfNull(tokenizedPaymentMethod);
if (string.IsNullOrWhiteSpace(subscriber.GatewayCustomerId))
var customer = await GetCustomerOrThrow(subscriber);
var (type, token) = tokenizedPaymentMethod;
if (string.IsNullOrEmpty(token))
{
logger.LogError("Cannot retrieve GatewayCustomerId for subscriber ({SubscriberID}) with no {FieldName}", subscriber.Id, nameof(subscriber.GatewaySubscriptionId));
logger.LogError("Updated payment method for ({SubscriberID}) must contain a token", subscriber.Id);
return null;
throw ContactSupport();
}
var customer = await GetCustomerOrThrow(subscriber, new CustomerGetOptions { Expand = ["tax_ids"] });
if (customer is null)
// ReSharper disable once SwitchStatementHandlesSomeKnownEnumValuesWithDefault
switch (type)
{
logger.LogError("Could not find Stripe customer ({CustomerID}) for subscriber ({SubscriberID})",
subscriber.GatewayCustomerId, subscriber.Id);
case PaymentMethodType.BankAccount:
{
var getSetupIntentsForUpdatedPaymentMethod = stripeAdapter.SetupIntentList(new SetupIntentListOptions
{
PaymentMethod = token
});
return null;
var getExistingSetupIntentsForCustomer = stripeAdapter.SetupIntentList(new SetupIntentListOptions
{
Customer = subscriber.GatewayCustomerId
});
// Find the setup intent for the incoming payment method token.
var setupIntentsForUpdatedPaymentMethod = await getSetupIntentsForUpdatedPaymentMethod;
if (setupIntentsForUpdatedPaymentMethod.Count != 1)
{
logger.LogError("There were more than 1 setup intents for subscriber's ({SubscriberID}) updated payment method", subscriber.Id);
throw ContactSupport();
}
var matchingSetupIntent = setupIntentsForUpdatedPaymentMethod.First();
// Find the customer's existing setup intents that should be cancelled.
var existingSetupIntentsForCustomer = (await getExistingSetupIntentsForCustomer)
.Where(si =>
si.Status is "requires_payment_method" or "requires_confirmation" or "requires_action");
// Store the incoming payment method's setup intent ID in the cache for the subscriber so it can be verified later.
await setupIntentCache.Set(subscriber.Id, matchingSetupIntent.Id);
// Cancel the customer's other open setup intents.
var postProcessing = existingSetupIntentsForCustomer.Select(si =>
stripeAdapter.SetupIntentCancel(si.Id,
new SetupIntentCancelOptions { CancellationReason = "abandoned" })).ToList();
// Remove the customer's other attached Stripe payment methods.
postProcessing.Add(RemoveStripePaymentMethodsAsync(customer));
// Remove the customer's Braintree customer ID.
postProcessing.Add(RemoveBraintreeCustomerIdAsync(customer));
await Task.WhenAll(postProcessing);
break;
}
case PaymentMethodType.Card:
{
var getExistingSetupIntentsForCustomer = stripeAdapter.SetupIntentList(new SetupIntentListOptions
{
Customer = subscriber.GatewayCustomerId
});
// Remove the customer's other attached Stripe payment methods.
await RemoveStripePaymentMethodsAsync(customer);
// Attach the incoming payment method.
await stripeAdapter.PaymentMethodAttachAsync(token,
new PaymentMethodAttachOptions { Customer = subscriber.GatewayCustomerId });
// Find the customer's existing setup intents that should be cancelled.
var existingSetupIntentsForCustomer = (await getExistingSetupIntentsForCustomer)
.Where(si =>
si.Status is "requires_payment_method" or "requires_confirmation" or "requires_action");
// Cancel the customer's other open setup intents.
var postProcessing = existingSetupIntentsForCustomer.Select(si =>
stripeAdapter.SetupIntentCancel(si.Id,
new SetupIntentCancelOptions { CancellationReason = "abandoned" })).ToList();
var metadata = customer.Metadata;
if (metadata.ContainsKey(BraintreeCustomerIdKey))
{
metadata[BraintreeCustomerIdKey] = null;
}
// Set the customer's default payment method in Stripe and remove their Braintree customer ID.
postProcessing.Add(stripeAdapter.CustomerUpdateAsync(subscriber.GatewayCustomerId, new CustomerUpdateOptions
{
InvoiceSettings = new CustomerInvoiceSettingsOptions
{
DefaultPaymentMethod = token
},
Metadata = metadata
}));
await Task.WhenAll(postProcessing);
break;
}
case PaymentMethodType.PayPal:
{
string braintreeCustomerId;
if (customer.Metadata != null)
{
var hasBraintreeCustomerId = customer.Metadata.TryGetValue(BraintreeCustomerIdKey, out braintreeCustomerId);
if (hasBraintreeCustomerId)
{
var braintreeCustomer = await braintreeGateway.Customer.FindAsync(braintreeCustomerId);
if (braintreeCustomer == null)
{
logger.LogError("Failed to retrieve Braintree customer ({BraintreeCustomerId}) when updating payment method for subscriber ({SubscriberID})", braintreeCustomerId, subscriber.Id);
throw ContactSupport();
}
await ReplaceBraintreePaymentMethodAsync(braintreeCustomer, token);
return;
}
}
braintreeCustomerId = await CreateBraintreeCustomerAsync(subscriber, token);
await AddBraintreeCustomerIdAsync(customer, braintreeCustomerId);
break;
}
default:
{
logger.LogError("Cannot update subscriber's ({SubscriberID}) payment method to type ({PaymentMethodType}) as it is not supported", subscriber.Id, type.ToString());
throw ContactSupport();
}
}
var address = customer.Address;
// Line1 is required, so if missing we're using the subscriber name
// see: https://stripe.com/docs/api/customers/create#create_customer-address-line1
if (address is not null && string.IsNullOrWhiteSpace(address.Line1))
{
address.Line1 = null;
}
return MapToTaxInfo(customer);
}
public async Task<BillingInfo.BillingSource> GetPaymentMethodAsync(ISubscriber subscriber)
public async Task UpdateTaxInformation(
ISubscriber subscriber,
TaxInformationDTO taxInformation)
{
ArgumentNullException.ThrowIfNull(subscriber);
var customer = await GetCustomerOrThrow(subscriber, GetCustomerPaymentOptions());
if (customer == null)
ArgumentNullException.ThrowIfNull(taxInformation);
var customer = await GetCustomerOrThrow(subscriber, new CustomerGetOptions
{
Expand = ["tax_ids"]
});
await stripeAdapter.CustomerUpdateAsync(customer.Id, new CustomerUpdateOptions
{
Address = new AddressOptions
{
Country = taxInformation.Country,
PostalCode = taxInformation.PostalCode,
Line1 = taxInformation.Line1 ?? string.Empty,
Line2 = taxInformation.Line2,
City = taxInformation.City,
State = taxInformation.State
}
});
if (!subscriber.IsUser())
{
var taxId = customer.TaxIds?.FirstOrDefault();
if (taxId != null)
{
await stripeAdapter.TaxIdDeleteAsync(customer.Id, taxId.Id);
}
var taxIdType = taxInformation.GetTaxIdType();
if (!string.IsNullOrWhiteSpace(taxInformation.TaxId) &&
!string.IsNullOrWhiteSpace(taxIdType))
{
await stripeAdapter.TaxIdCreateAsync(customer.Id, new TaxIdCreateOptions
{
Type = taxIdType,
Value = taxInformation.TaxId,
});
}
}
}
public async Task VerifyBankAccount(
ISubscriber subscriber,
(long, long) microdeposits)
{
ArgumentNullException.ThrowIfNull(subscriber);
var setupIntentId = await setupIntentCache.Get(subscriber.Id);
if (string.IsNullOrEmpty(setupIntentId))
{
logger.LogError("No setup intent ID exists to verify for subscriber with ID ({SubscriberID})", subscriber.Id);
throw ContactSupport();
}
var (amount1, amount2) = microdeposits;
await stripeAdapter.SetupIntentVerifyMicroDeposit(setupIntentId, new SetupIntentVerifyMicrodepositsOptions
{
Amounts = [amount1, amount2]
});
var setupIntent = await stripeAdapter.SetupIntentGet(setupIntentId);
await stripeAdapter.PaymentMethodAttachAsync(setupIntent.PaymentMethodId, new PaymentMethodAttachOptions
{
Customer = subscriber.GatewayCustomerId
});
await stripeAdapter.CustomerUpdateAsync(subscriber.GatewayCustomerId,
new CustomerUpdateOptions
{
InvoiceSettings = new CustomerInvoiceSettingsOptions
{
DefaultPaymentMethod = setupIntent.PaymentMethodId
}
});
}
#region Shared Utilities
private async Task AddBraintreeCustomerIdAsync(
Customer customer,
string braintreeCustomerId)
{
var metadata = customer.Metadata ?? new Dictionary<string, string>();
metadata[BraintreeCustomerIdKey] = braintreeCustomerId;
await stripeAdapter.CustomerUpdateAsync(customer.Id, new CustomerUpdateOptions
{
Metadata = metadata
});
}
private async Task<string> CreateBraintreeCustomerAsync(
ISubscriber subscriber,
string paymentMethodNonce)
{
var braintreeCustomerId =
subscriber.BraintreeCustomerIdPrefix() +
subscriber.Id.ToString("N").ToLower() +
CoreHelpers.RandomString(3, upper: false, numeric: false);
var customerResult = await braintreeGateway.Customer.CreateAsync(new CustomerRequest
{
Id = braintreeCustomerId,
CustomFields = new Dictionary<string, string>
{
[subscriber.BraintreeIdField()] = subscriber.Id.ToString(),
[subscriber.BraintreeCloudRegionField()] = globalSettings.BaseServiceUri.CloudRegion
},
Email = subscriber.BillingEmailAddress(),
PaymentMethodNonce = paymentMethodNonce,
});
if (customerResult.IsSuccess())
{
return customerResult.Target.Id;
}
logger.LogError("Failed to create Braintree customer for subscriber ({ID})", subscriber.Id);
throw ContactSupport();
}
private async Task<MaskedPaymentMethodDTO> GetMaskedPaymentMethodDTOAsync(
Guid subscriberId,
Customer customer)
{
if (customer.Metadata != null)
{
var hasBraintreeCustomerId = customer.Metadata.TryGetValue(BraintreeCustomerIdKey, out var braintreeCustomerId);
if (hasBraintreeCustomerId)
{
var braintreeCustomer = await braintreeGateway.Customer.FindAsync(braintreeCustomerId);
return MaskedPaymentMethodDTO.From(braintreeCustomer);
}
}
var attachedPaymentMethodDTO = MaskedPaymentMethodDTO.From(customer);
if (attachedPaymentMethodDTO != null)
{
return attachedPaymentMethodDTO;
}
/*
* attachedPaymentMethodDTO being null represents a case where we could be looking for the SetupIntent for an unverified "us_bank_account".
* We store the ID of this SetupIntent in the cache when we originally update the payment method.
*/
var setupIntentId = await setupIntentCache.Get(subscriberId);
if (string.IsNullOrEmpty(setupIntentId))
{
logger.LogError("Could not find Stripe customer ({CustomerID}) for subscriber ({SubscriberID})",
subscriber.GatewayCustomerId, subscriber.Id);
return null;
}
if (customer.Metadata?.ContainsKey("btCustomerId") ?? false)
var setupIntent = await stripeAdapter.SetupIntentGet(setupIntentId, new SetupIntentGetOptions
{
try
Expand = ["payment_method"]
});
return MaskedPaymentMethodDTO.From(setupIntent);
}
private static TaxInformationDTO GetTaxInformationDTOFrom(
Customer customer)
{
if (customer.Address == null)
{
return null;
}
return new TaxInformationDTO(
customer.Address.Country,
customer.Address.PostalCode,
customer.TaxIds?.FirstOrDefault()?.Value,
customer.Address.Line1,
customer.Address.Line2,
customer.Address.City,
customer.Address.State);
}
private async Task RemoveBraintreeCustomerIdAsync(
Customer customer)
{
var metadata = customer.Metadata ?? new Dictionary<string, string>();
if (metadata.ContainsKey(BraintreeCustomerIdKey))
{
metadata[BraintreeCustomerIdKey] = null;
await stripeAdapter.CustomerUpdateAsync(customer.Id, new CustomerUpdateOptions
{
var braintreeCustomer = await braintreeGateway.Customer.FindAsync(
customer.Metadata["btCustomerId"]);
if (braintreeCustomer?.DefaultPaymentMethod != null)
Metadata = metadata
});
}
}
private async Task RemoveStripePaymentMethodsAsync(
Customer customer)
{
if (customer.Sources != null && customer.Sources.Any())
{
foreach (var source in customer.Sources)
{
switch (source)
{
return new BillingInfo.BillingSource(
braintreeCustomer.DefaultPaymentMethod);
case BankAccount:
await stripeAdapter.BankAccountDeleteAsync(customer.Id, source.Id);
break;
case Card:
await stripeAdapter.CardDeleteAsync(customer.Id, source.Id);
break;
}
}
catch (Braintree.Exceptions.NotFoundException ex)
}
var paymentMethods = await stripeAdapter.CustomerListPaymentMethods(customer.Id);
await Task.WhenAll(paymentMethods.Select(pm => stripeAdapter.PaymentMethodDetachAsync(pm.Id)));
}
private async Task ReplaceBraintreePaymentMethodAsync(
Braintree.Customer customer,
string defaultPaymentMethodToken)
{
var existingDefaultPaymentMethod = customer.DefaultPaymentMethod;
var createPaymentMethodResult = await braintreeGateway.PaymentMethod.CreateAsync(new PaymentMethodRequest
{
CustomerId = customer.Id,
PaymentMethodNonce = defaultPaymentMethodToken
});
if (!createPaymentMethodResult.IsSuccess())
{
logger.LogError("Failed to replace payment method for Braintree customer ({ID}) - Creation of new payment method failed | Error: {Error}", customer.Id, createPaymentMethodResult.Message);
throw ContactSupport();
}
var updateCustomerResult = await braintreeGateway.Customer.UpdateAsync(
customer.Id,
new CustomerRequest { DefaultPaymentMethodToken = createPaymentMethodResult.Target.Token });
if (!updateCustomerResult.IsSuccess())
{
logger.LogError("Failed to replace payment method for Braintree customer ({ID}) - Customer update failed | Error: {Error}",
customer.Id, updateCustomerResult.Message);
await braintreeGateway.PaymentMethod.DeleteAsync(createPaymentMethodResult.Target.Token);
throw ContactSupport();
}
if (existingDefaultPaymentMethod != null)
{
var deletePaymentMethodResult = await braintreeGateway.PaymentMethod.DeleteAsync(existingDefaultPaymentMethod.Token);
if (!deletePaymentMethodResult.IsSuccess())
{
logger.LogError("An error occurred while trying to retrieve braintree customer ({SubscriberID}): {Error}", subscriber.Id, ex.Message);
logger.LogWarning(
"Failed to delete replaced payment method for Braintree customer ({ID}) - outdated payment method still exists | Error: {Error}",
customer.Id, deletePaymentMethodResult.Message);
}
}
if (customer.InvoiceSettings?.DefaultPaymentMethod?.Type == "card")
{
return new BillingInfo.BillingSource(
customer.InvoiceSettings.DefaultPaymentMethod);
}
if (customer.DefaultSource != null &&
(customer.DefaultSource is Card || customer.DefaultSource is BankAccount))
{
return new BillingInfo.BillingSource(customer.DefaultSource);
}
var paymentMethod = GetLatestCardPaymentMethod(customer.Id);
return paymentMethod != null ? new BillingInfo.BillingSource(paymentMethod) : null;
}
private static CustomerGetOptions GetCustomerPaymentOptions()
{
var customerOptions = new CustomerGetOptions();
customerOptions.AddExpand("default_source");
customerOptions.AddExpand("invoice_settings.default_payment_method");
return customerOptions;
}
private Stripe.PaymentMethod GetLatestCardPaymentMethod(string customerId)
{
var cardPaymentMethods = stripeAdapter.PaymentMethodListAutoPaging(
new PaymentMethodListOptions { Customer = customerId, Type = "card" });
return cardPaymentMethods.MaxBy(m => m.Created);
}
private TaxInfo MapToTaxInfo(Customer customer)
{
var address = customer.Address;
var taxId = customer.TaxIds?.FirstOrDefault();
return new TaxInfo
{
TaxIdNumber = taxId?.Value,
BillingAddressLine1 = address?.Line1,
BillingAddressLine2 = address?.Line2,
BillingAddressCity = address?.City,
BillingAddressState = address?.State,
BillingAddressPostalCode = address?.PostalCode,
BillingAddressCountry = address?.Country,
};
}
#endregion
}