Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support updating payment method in CustomerSheet. #7644

Merged
merged 3 commits into from
Nov 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -554,7 +554,7 @@ class StripeApiRepository @JvmOverloads internal constructor(
apiRequest = apiRequestFactory.createPost(
url = getPaymentMethodUrl(paymentMethodId),
options = options,
params = paymentMethodUpdateParams.toParamMap() + fraudDetectionData?.params.orEmpty(),
params = paymentMethodUpdateParams.toParamMap(),
),
jsonParser = PaymentMethodJsonParser()
)
Expand Down
1 change: 1 addition & 0 deletions paymentsheet/api/paymentsheet.api
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ public abstract interface class com/stripe/android/customersheet/CustomerAdapter
public abstract fun retrieveSelectedPaymentOption (Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
public abstract fun setSelectedPaymentOption (Lcom/stripe/android/customersheet/CustomerAdapter$PaymentOption;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
public abstract fun setupIntentClientSecretForCustomerAttach (Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
public abstract fun updatePaymentMethod (Ljava/lang/String;Lcom/stripe/android/model/PaymentMethodUpdateParams;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
}

public final class com/stripe/android/customersheet/CustomerAdapter$Companion {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package com.stripe.android.customersheet
import android.content.Context
import com.stripe.android.customersheet.injection.DaggerStripeCustomerAdapterComponent
import com.stripe.android.model.PaymentMethod
import com.stripe.android.model.PaymentMethodUpdateParams
import com.stripe.android.paymentsheet.model.PaymentSelection
import com.stripe.android.paymentsheet.model.SavedSelection

Expand Down Expand Up @@ -49,6 +50,15 @@ interface CustomerAdapter {
*/
suspend fun detachPaymentMethod(paymentMethodId: String): Result<PaymentMethod>

/**
* Updates a payment method with the provided [PaymentMethodUpdateParams].
*
* @param paymentMethodId The payment method to update
* @param paymentMethodUpdateParams The [PaymentMethodUpdateParams]
* @return The updated [PaymentMethod]
*/
suspend fun updatePaymentMethod(paymentMethodId: String, params: PaymentMethodUpdateParams): Result<PaymentMethod>

/**
* Saves the payment option to a data store.
* @param paymentOption the [PaymentOption] to save to the data store. If null, the selected
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,13 @@ import com.stripe.android.customersheet.CustomerAdapter.PaymentOption.Companion.
import com.stripe.android.customersheet.analytics.CustomerSheetEventReporter
import com.stripe.android.customersheet.injection.CustomerSheetViewModelScope
import com.stripe.android.customersheet.util.isUnverifiedUSBankAccount
import com.stripe.android.model.CardBrand
import com.stripe.android.model.ConfirmSetupIntentParams
import com.stripe.android.model.ConfirmStripeIntentParams
import com.stripe.android.model.PaymentMethod
import com.stripe.android.model.PaymentMethodCode
import com.stripe.android.model.PaymentMethodCreateParams
import com.stripe.android.model.PaymentMethodUpdateParams
import com.stripe.android.model.SetupIntent
import com.stripe.android.model.StripeIntent
import com.stripe.android.networking.StripeRepository
Expand Down Expand Up @@ -67,8 +69,6 @@ import javax.inject.Provider
import kotlin.coroutines.CoroutineContext
import com.stripe.android.ui.core.R as UiCoreR

private const val TempDelay = 2000L

@OptIn(ExperimentalCustomerSheetApi::class)
@CustomerSheetViewModelScope
internal class CustomerSheetViewModel @Inject constructor(
Expand Down Expand Up @@ -429,6 +429,23 @@ internal class CustomerSheetViewModel @Inject constructor(
}
}

private suspend fun modifyCardPaymentMethod(
paymentMethod: PaymentMethod,
brand: CardBrand
): CustomerAdapter.Result<PaymentMethod> {
return customerAdapter.updatePaymentMethod(
paymentMethodId = paymentMethod.id!!,
params = PaymentMethodUpdateParams.createCard(
networks = PaymentMethodUpdateParams.Card.Networks(
preferred = brand.code
)
)
).onSuccess { updatedMethod ->
onBackPressed()
updatePaymentMethodInState(updatedMethod)
}
}

private fun handlePaymentMethodRemoved(paymentMethod: PaymentMethod) {
val currentViewState = viewState.value
val newSavedPaymentMethods = currentViewState.savedPaymentMethods.filter { it.id != paymentMethod.id!! }
Expand Down Expand Up @@ -484,10 +501,11 @@ internal class CustomerSheetViewModel @Inject constructor(
}
result is CustomerAdapter.Result.Success
},
updateExecutor = { _, _ ->
// TODO(tillh-stripe): Replace with update operation
delay(TempDelay)
Result.success(paymentMethod)
updateExecutor = { method, brand ->
when (val result = modifyCardPaymentMethod(method, brand)) {
is CustomerAdapter.Result.Success -> Result.success(result.value)
is CustomerAdapter.Result.Failure -> Result.failure(result.cause)
}
},
),
isLiveMode = currentViewState.isLiveMode,
Expand All @@ -513,6 +531,25 @@ internal class CustomerSheetViewModel @Inject constructor(
}
}

private fun updatePaymentMethodInState(updatedMethod: PaymentMethod) {
viewModelScope.launch {
val newSavedPaymentMethods = viewState.value.savedPaymentMethods.map { savedMethod ->
val savedId = savedMethod.id
val updatedId = updatedMethod.id

if (updatedId != null && savedId != null && updatedId == savedId) {
updatedMethod
} else {
savedMethod
}
}

updateViewState<CustomerSheetViewState.SelectPaymentMethod> {
it.copy(savedPaymentMethods = newSavedPaymentMethods)
}
}
}

private fun onItemSelected(paymentSelection: PaymentSelection?) {
// TODO (jameswoo) consider clearing the error message onItemSelected, currently the only
// error source is when the payment methods cannot be loaded
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import com.stripe.android.common.exception.stripeErrorMessage
import com.stripe.android.core.injection.IOContext
import com.stripe.android.customersheet.CustomerAdapter.PaymentOption.Companion.toPaymentOption
import com.stripe.android.model.PaymentMethod
import com.stripe.android.model.PaymentMethodUpdateParams
import com.stripe.android.paymentsheet.PaymentSheet
import com.stripe.android.paymentsheet.PrefsRepository
import com.stripe.android.paymentsheet.R
Expand Down Expand Up @@ -101,6 +102,27 @@ internal class StripeCustomerAdapter @Inject constructor(
}
}

override suspend fun updatePaymentMethod(
paymentMethodId: String,
params: PaymentMethodUpdateParams
): CustomerAdapter.Result<PaymentMethod> {
return getCustomerEphemeralKey().mapCatching { customerEphemeralKey ->
customerRepository.updatePaymentMethod(
customerConfig = PaymentSheet.CustomerConfiguration(
id = customerEphemeralKey.customerId,
ephemeralKeySecret = customerEphemeralKey.ephemeralKey
),
paymentMethodId = paymentMethodId,
params = params
).getOrElse {
return CustomerAdapter.Result.failure(
cause = it,
displayMessage = it.stripeErrorMessage(context),
)
}
}
}

override suspend fun setSelectedPaymentOption(
paymentOption: CustomerAdapter.PaymentOption?
): CustomerAdapter.Result<Unit> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import com.stripe.android.customersheet.CustomerAdapter.PaymentOption.Companion.
import com.stripe.android.customersheet.StripeCustomerAdapter.Companion.CACHED_CUSTOMER_MAX_AGE_MILLIS
import com.stripe.android.model.PaymentMethod
import com.stripe.android.model.PaymentMethodFixtures
import com.stripe.android.model.PaymentMethodUpdateParams
import com.stripe.android.paymentsheet.DefaultPrefsRepository
import com.stripe.android.paymentsheet.FakePrefsRepository
import com.stripe.android.paymentsheet.PrefsRepository
Expand Down Expand Up @@ -288,6 +289,67 @@ class CustomerAdapterTest {
.isEqualTo("Unable to detach payment method")
}

@Test
fun `updatePaymentMethod succeeds when the payment method is update`() = runTest {
val adapter = createAdapter(
customerRepository = FakeCustomerRepository(
onUpdatePaymentMethod = {
Result.success(PaymentMethodFixtures.CARD_PAYMENT_METHOD)
}
)
)
val result = adapter.updatePaymentMethod(
paymentMethodId = "pm_1234",
params = PaymentMethodUpdateParams.createCard()
)
assertThat(result.getOrNull()).isEqualTo(
PaymentMethodFixtures.CARD_PAYMENT_METHOD
)
}

@Test
fun `updatePaymentMethod fails with default message when the payment method couldn't be updated`() = runTest {
val adapter = createAdapter(
customerRepository = FakeCustomerRepository(
onUpdatePaymentMethod = {
Result.failure(
APIException(
message = "could not update payment method",
)
)
}
)
)
val result = adapter.updatePaymentMethod(
paymentMethodId = "pm_1234",
params = PaymentMethodUpdateParams.createCard()
)
assertThat(result.failureOrNull()?.displayMessage)
.isEqualTo("Something went wrong")
}

@Test
fun `updatePaymentMethod fails with Stripe message when the payment method couldn't be updated`() = runTest {
val adapter = createAdapter(
customerRepository = FakeCustomerRepository(
onUpdatePaymentMethod = {
Result.failure(
APIException(
message = "could not update payment method",
stripeError = StripeError(message = "Unable to update payment method")
)
)
}
)
)
val result = adapter.updatePaymentMethod(
paymentMethodId = "pm_1234",
params = PaymentMethodUpdateParams.createCard()
)
assertThat(result.failureOrNull()?.displayMessage)
.isEqualTo("Unable to update payment method")
}

@Test
fun `setSelectedPaymentMethodOption saves the selected payment method`() = runTest {
val adapter = createAdapter(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import com.stripe.android.customersheet.utils.FakeCustomerSheetLoader
import com.stripe.android.financialconnections.model.FinancialConnectionsAccount
import com.stripe.android.financialconnections.model.FinancialConnectionsSession
import com.stripe.android.financialconnections.model.PaymentAccount
import com.stripe.android.model.CardBrand
import com.stripe.android.model.PaymentMethod
import com.stripe.android.model.PaymentMethodFixtures.CARD_PAYMENT_METHOD
import com.stripe.android.model.PaymentMethodFixtures.US_BANK_ACCOUNT
Expand All @@ -31,7 +32,10 @@ import com.stripe.android.paymentsheet.forms.FormFieldValues
import com.stripe.android.paymentsheet.forms.FormViewModel
import com.stripe.android.paymentsheet.model.PaymentSelection
import com.stripe.android.paymentsheet.paymentdatacollection.ach.USBankAccountFormScreenState
import com.stripe.android.paymentsheet.ui.EditPaymentMethodViewAction.OnBrandChoiceChanged
import com.stripe.android.paymentsheet.ui.EditPaymentMethodViewAction.OnRemovePressed
import com.stripe.android.paymentsheet.ui.EditPaymentMethodViewAction.OnUpdatePressed
import com.stripe.android.paymentsheet.ui.EditPaymentMethodViewState
import com.stripe.android.paymentsheet.ui.PrimaryButton
import com.stripe.android.testing.CoroutineTestRule
import com.stripe.android.testing.FeatureFlagTestRule
Expand Down Expand Up @@ -2483,6 +2487,66 @@ class CustomerSheetViewModelTest {
}
}

@Test
fun `Updating payment method in edit screen goes through expected states`() = runTest(testDispatcher) {
val paymentMethods = PaymentMethodFactory.cards(size = 1)

val firstMethod = paymentMethods.single()

val updatedMethod = firstMethod.copy(
card = firstMethod.card?.copy(
networks = PaymentMethod.Card.Networks(
available = setOf("visa", "cartes_bancaires"),
preferred = "visa"
)
)
)

val customerAdapter = FakeCustomerAdapter(
paymentMethods = CustomerAdapter.Result.Success(paymentMethods),
onUpdatePaymentMethod = { _, _ ->
CustomerAdapter.Result.Success(updatedMethod)
}
)

val viewModel = createViewModel(
workContext = testDispatcher,
initialBackStack = listOf(
selectPaymentMethodViewState.copy(
savedPaymentMethods = paymentMethods,
)
),
customerPaymentMethods = paymentMethods,
customerAdapter = customerAdapter,
)

viewModel.viewState.test {
assertThat(awaitItem()).isInstanceOf(SelectPaymentMethod::class.java)
viewModel.handleViewAction(CustomerSheetViewAction.OnModifyItem(firstMethod))

val editViewState = awaitViewState<CustomerSheetViewState.EditPaymentMethod>()
editViewState.editPaymentMethodInteractor.handleViewAction(
OnBrandChoiceChanged(
EditPaymentMethodViewState.CardBrandChoice(
brand = CardBrand.Visa
)
)
)
editViewState.editPaymentMethodInteractor.handleViewAction(OnUpdatePressed)

// Confirm that nothing has changed yet. We're waiting to update the payment method
// once we return to the SPM screen.
val updatedViewState = awaitViewState<SelectPaymentMethod>()
assertThat(updatedViewState.savedPaymentMethods).containsExactlyElementsIn(paymentMethods)

// Simulate the delay
testDispatcher.scheduler.advanceUntilIdle()

val finalViewState = awaitViewState<SelectPaymentMethod>()
assertThat(finalViewState.savedPaymentMethods).containsExactlyElementsIn(listOf(updatedMethod))
}
}

private fun mockUSBankAccountResult(
isVerified: Boolean
): CollectBankAccountResultInternal.Completed {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package com.stripe.android.customersheet

import com.stripe.android.model.PaymentMethod
import com.stripe.android.model.PaymentMethodFixtures.CARD_PAYMENT_METHOD
import com.stripe.android.model.PaymentMethodUpdateParams

@OptIn(ExperimentalCustomerSheetApi::class)
internal class FakeCustomerAdapter(
Expand All @@ -14,6 +15,8 @@ internal class FakeCustomerAdapter(
((paymentOption: CustomerAdapter.PaymentOption?) -> CustomerAdapter.Result<Unit>)? = null,
private val onAttachPaymentMethod: ((paymentMethodId: String) -> CustomerAdapter.Result<PaymentMethod>)? = null,
private val onDetachPaymentMethod: ((paymentMethodId: String) -> CustomerAdapter.Result<PaymentMethod>)? = null,
private val onUpdatePaymentMethod:
((paymentMethodId: String, params: PaymentMethodUpdateParams) -> CustomerAdapter.Result<PaymentMethod>)? = null,
private val onSetupIntentClientSecretForCustomerAttach: (() -> CustomerAdapter.Result<String>)? = null
) : CustomerAdapter {

Expand All @@ -31,6 +34,18 @@ internal class FakeCustomerAdapter(
?: CustomerAdapter.Result.success(paymentMethods.getOrNull()?.find { it.id!! == paymentMethodId }!!)
}

override suspend fun updatePaymentMethod(
paymentMethodId: String,
params: PaymentMethodUpdateParams
): CustomerAdapter.Result<PaymentMethod> {
return onUpdatePaymentMethod?.invoke(paymentMethodId, params)
?: CustomerAdapter.Result.success(
paymentMethods.getOrNull()?.find {
it.id!! == paymentMethodId
}!!
)
}

override suspend fun setSelectedPaymentOption(
paymentOption: CustomerAdapter.PaymentOption?
): CustomerAdapter.Result<Unit> {
Expand Down
Loading