From ed091367fb2a417423e3ee683b2635d983c00ee7 Mon Sep 17 00:00:00 2001 From: Tim Chow Date: Tue, 5 Nov 2024 12:49:15 -0600 Subject: [PATCH] Add MerchantRepository for holding BraintreeClient properties (#1202) * Move properties from BraintreeClient to MerchantRepository * Add kdocs for MerchantRepository --- .../api/core/BraintreeClient.kt | 71 ++- .../api/core/MerchantRepository.kt | 26 + .../api/core/BraintreeClientUnitTest.kt | 47 +- .../api/googlepay/GooglePayClient.kt | 14 +- .../googlepay/GooglePayClientUnitTest.java | 281 +++++++-- .../api/localpayment/LocalPaymentApi.kt | 6 +- .../localpayment/LocalPaymentApiUnitTest.java | 142 ++--- .../LocalPaymentClientUnitTest.java | 5 - .../api/paypal/PayPalClient.kt | 4 +- .../api/paypal/PayPalInternalClient.kt | 14 +- .../api/paypal/PayPalClientUnitTest.java | 117 ++-- .../paypal/PayPalInternalClientUnitTest.java | 540 ++++++++++++------ .../shopperinsights/ShopperInsightsClient.kt | 4 +- .../ShopperInsightsClientUnitTest.kt | 21 +- .../testutils/MockBraintreeClientBuilder.java | 22 - .../api/threedsecure/ThreeDSecureClient.kt | 6 +- .../ThreeDSecureClientUnitTest.java | 236 +++++--- .../braintreepayments/api/venmo/VenmoApi.kt | 6 +- .../api/venmo/VenmoClient.kt | 14 +- .../api/venmo/VenmoApiUnitTest.java | 30 +- .../api/venmo/VenmoClientUnitTest.java | 307 +++++++--- 21 files changed, 1241 insertions(+), 672 deletions(-) create mode 100644 BraintreeCore/src/main/java/com/braintreepayments/api/core/MerchantRepository.kt diff --git a/BraintreeCore/src/main/java/com/braintreepayments/api/core/BraintreeClient.kt b/BraintreeCore/src/main/java/com/braintreepayments/api/core/BraintreeClient.kt index 6582383a53..cb3a5529a8 100644 --- a/BraintreeCore/src/main/java/com/braintreepayments/api/core/BraintreeClient.kt +++ b/BraintreeCore/src/main/java/com/braintreepayments/api/core/BraintreeClient.kt @@ -17,35 +17,18 @@ import org.json.JSONObject @Suppress("LargeClass", "LongParameterList", "TooManyFunctions") @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) class BraintreeClient internal constructor( - - /** - * @suppress - */ - val applicationContext: Context, - - /** - * @suppress - */ - val integrationType: IntegrationType, - - /** - * @suppress - */ - val authorization: Authorization, - - private val returnUrlScheme: String, - - /** - * @suppress - */ - val appLinkReturnUri: Uri?, - + applicationContext: Context, + integrationType: IntegrationType, + authorization: Authorization, + returnUrlScheme: String, + appLinkReturnUri: Uri?, private val analyticsClient: AnalyticsClient = AnalyticsClient(applicationContext), private val httpClient: BraintreeHttpClient = BraintreeHttpClient(), private val graphQLClient: BraintreeGraphQLClient = BraintreeGraphQLClient(), private val configurationLoader: ConfigurationLoader = ConfigurationLoader(applicationContext, httpClient), private val manifestValidator: ManifestValidator = ManifestValidator(), private val time: Time = Time(), + private val merchantRepository: MerchantRepository = MerchantRepository.instance ) { private val crashReporter: CrashReporter @@ -80,6 +63,16 @@ class BraintreeClient internal constructor( // statistics access via the sdk console crashReporter = CrashReporter(this) crashReporter.start() + + merchantRepository.let { + it.applicationContext = applicationContext + it.integrationType = integrationType + it.authorization = authorization + it.returnUrlScheme = returnUrlScheme + if (appLinkReturnUri != null) { + it.appLinkReturnUri = appLinkReturnUri + } + } } /** @@ -88,11 +81,11 @@ class BraintreeClient internal constructor( * @param callback [ConfigurationCallback] */ fun getConfiguration(callback: ConfigurationCallback) { - if (authorization is InvalidAuthorization) { + if (merchantRepository.authorization is InvalidAuthorization) { callback.onResult(null, createAuthError()) return } - configurationLoader.loadConfiguration(authorization) { configuration, configError, timing -> + configurationLoader.loadConfiguration(merchantRepository.authorization) { configuration, configError, timing -> if (configuration != null) { callback.onResult(configuration, null) } else { @@ -123,7 +116,7 @@ class BraintreeClient internal constructor( experiment = params.experiment, paymentMethodsDisplayed = params.paymentMethodsDisplayed ) - sendAnalyticsEvent(event, configuration, authorization) + sendAnalyticsEvent(event, configuration, merchantRepository.authorization) } } @@ -136,7 +129,7 @@ class BraintreeClient internal constructor( analyticsClient.sendEvent( it, event, - integrationType, + merchantRepository.integrationType, authorization ) } @@ -146,13 +139,13 @@ class BraintreeClient internal constructor( * @suppress */ fun sendGET(url: String, responseCallback: HttpResponseCallback) { - if (authorization is InvalidAuthorization) { + if (merchantRepository.authorization is InvalidAuthorization) { responseCallback.onResult(null, createAuthError()) return } getConfiguration { configuration, configError -> if (configuration != null) { - httpClient.get(url, configuration, authorization) { response, httpError -> + httpClient.get(url, configuration, merchantRepository.authorization) { response, httpError -> response?.let { try { sendAnalyticsTimingEvent(url, response.timing) @@ -180,7 +173,7 @@ class BraintreeClient internal constructor( additionalHeaders: Map = emptyMap(), responseCallback: HttpResponseCallback, ) { - if (authorization is InvalidAuthorization) { + if (merchantRepository.authorization is InvalidAuthorization) { responseCallback.onResult(null, createAuthError()) return } @@ -190,7 +183,7 @@ class BraintreeClient internal constructor( path = url, data = data, configuration = configuration, - authorization = authorization, + authorization = merchantRepository.authorization, additionalHeaders = additionalHeaders ) { response, httpError -> response?.let { @@ -214,7 +207,7 @@ class BraintreeClient internal constructor( * @suppress */ fun sendGraphQLPOST(json: JSONObject?, responseCallback: HttpResponseCallback) { - if (authorization is InvalidAuthorization) { + if (merchantRepository.authorization is InvalidAuthorization) { responseCallback.onResult(null, createAuthError()) return } @@ -223,7 +216,7 @@ class BraintreeClient internal constructor( graphQLClient.post( json?.toString(), configuration, - authorization + merchantRepository.authorization ) { response, httpError -> response?.let { try { @@ -262,7 +255,7 @@ class BraintreeClient internal constructor( return if (launchesBrowserSwitchAsNewTask) { braintreeDeepLinkReturnUrlScheme } else { - returnUrlScheme + merchantRepository.returnUrlScheme } } @@ -271,7 +264,7 @@ class BraintreeClient internal constructor( */ fun isUrlSchemeDeclaredInAndroidManifest(urlScheme: String?, klass: Class?): Boolean { return manifestValidator.isUrlSchemeDeclaredInAndroidManifest( - applicationContext, + merchantRepository.applicationContext, urlScheme, klass ) @@ -281,7 +274,7 @@ class BraintreeClient internal constructor( * @suppress */ fun getManifestActivityInfo(klass: Class?): ActivityInfo? { - return manifestValidator.getActivityInfo(applicationContext, klass) + return manifestValidator.getActivityInfo(merchantRepository.applicationContext, klass) } /** @@ -290,10 +283,10 @@ class BraintreeClient internal constructor( internal fun reportCrash() = getConfiguration { configuration, _ -> analyticsClient.reportCrash( - applicationContext, + merchantRepository.applicationContext, configuration, - integrationType, - authorization + merchantRepository.integrationType, + merchantRepository.authorization ) } diff --git a/BraintreeCore/src/main/java/com/braintreepayments/api/core/MerchantRepository.kt b/BraintreeCore/src/main/java/com/braintreepayments/api/core/MerchantRepository.kt new file mode 100644 index 0000000000..d8ad972c5c --- /dev/null +++ b/BraintreeCore/src/main/java/com/braintreepayments/api/core/MerchantRepository.kt @@ -0,0 +1,26 @@ +package com.braintreepayments.api.core + +import android.content.Context +import android.net.Uri +import androidx.annotation.RestrictTo + +/** + * An internal repository that holds properties set by the integrating merchant. + */ +@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) +class MerchantRepository { + + lateinit var applicationContext: Context + lateinit var integrationType: IntegrationType + lateinit var authorization: Authorization + lateinit var returnUrlScheme: String + var appLinkReturnUri: Uri? = null + + companion object { + + /** + * Singleton instance of the MerchantRepository. + */ + val instance: MerchantRepository by lazy { MerchantRepository() } + } +} diff --git a/BraintreeCore/src/test/java/com/braintreepayments/api/core/BraintreeClientUnitTest.kt b/BraintreeCore/src/test/java/com/braintreepayments/api/core/BraintreeClientUnitTest.kt index f906d88533..e8709acd07 100644 --- a/BraintreeCore/src/test/java/com/braintreepayments/api/core/BraintreeClientUnitTest.kt +++ b/BraintreeCore/src/test/java/com/braintreepayments/api/core/BraintreeClientUnitTest.kt @@ -34,6 +34,7 @@ class BraintreeClientUnitTest { private lateinit var manifestValidator: ManifestValidator private lateinit var browserSwitchClient: BrowserSwitchClient private lateinit var expectedAuthException: BraintreeException + private lateinit var merchantRepository: MerchantRepository @Before fun beforeEach() { @@ -48,6 +49,7 @@ class BraintreeClientUnitTest { analyticsClient = mockk(relaxed = true) manifestValidator = mockk(relaxed = true) browserSwitchClient = mockk(relaxed = true) + merchantRepository = mockk(relaxed = true) val clientSDKSetupURL = "https://developer.paypal.com/braintree/docs/guides/client-sdk/setup/android/v4#initialization" @@ -402,24 +404,6 @@ class BraintreeClientUnitTest { ) } - @Test - fun integrationType_returnsCustomByDefault() { - val context = ApplicationProvider.getApplicationContext() - val sut = BraintreeClient(context, authorization.toString()) - assertEquals("custom", sut.integrationType.stringValue) - } - - @Test - fun integrationType_returnsIntegrationTypeDefinedInConstructor() { - val context = ApplicationProvider.getApplicationContext() - val sut = BraintreeClient( - context = context, - authorization = authorization.toString(), - integrationType = IntegrationType.DROP_IN - ) - assertEquals("dropin", sut.integrationType.stringValue) - } - @Test @Throws(JSONException::class) fun reportCrash_reportsCrashViaAnalyticsClient() { @@ -447,20 +431,39 @@ class BraintreeClientUnitTest { } } + @Test + fun `when BraintreeClient is initialized, merchantRepository properties are set`() { + createBraintreeClient(merchantRepository = merchantRepository) + verify { merchantRepository.returnUrlScheme = "sample-return-url-scheme" } + verify { merchantRepository.applicationContext = applicationContext } + verify { merchantRepository.authorization = authorization } + verify { merchantRepository.appLinkReturnUri = Uri.parse("https://example.com") } + verify { merchantRepository.integrationType = IntegrationType.CUSTOM } + } + + @Test + fun `when BraintreeClient is initialized and appLinkReturnUri is null, it is not set on the MerchantRepository`() { + createBraintreeClient(appLinkReturnUri = null, merchantRepository = merchantRepository) + verify(exactly = 0) { merchantRepository.appLinkReturnUri = null } + } + private fun createBraintreeClient( - configurationLoader: ConfigurationLoader, - time: Time = Time() + configurationLoader: ConfigurationLoader = mockk(), + time: Time = Time(), + appLinkReturnUri: Uri? = Uri.parse("https://example.com"), + merchantRepository: MerchantRepository = MerchantRepository.instance ) = BraintreeClient( applicationContext = applicationContext, integrationType = IntegrationType.CUSTOM, authorization = authorization, returnUrlScheme = "sample-return-url-scheme", - appLinkReturnUri = Uri.parse("https://example.com"), + appLinkReturnUri = appLinkReturnUri, httpClient = braintreeHttpClient, graphQLClient = braintreeGraphQLClient, analyticsClient = analyticsClient, manifestValidator = manifestValidator, configurationLoader = configurationLoader, - time = time + time = time, + merchantRepository = merchantRepository, ) } diff --git a/GooglePay/src/main/java/com/braintreepayments/api/googlepay/GooglePayClient.kt b/GooglePay/src/main/java/com/braintreepayments/api/googlepay/GooglePayClient.kt index 7d36e53d10..ec99a7f1b0 100644 --- a/GooglePay/src/main/java/com/braintreepayments/api/googlepay/GooglePayClient.kt +++ b/GooglePay/src/main/java/com/braintreepayments/api/googlepay/GooglePayClient.kt @@ -9,6 +9,7 @@ import com.braintreepayments.api.core.BraintreeClient import com.braintreepayments.api.core.BraintreeException import com.braintreepayments.api.core.Configuration import com.braintreepayments.api.core.ErrorWithResponse.Companion.fromJson +import com.braintreepayments.api.core.MerchantRepository import com.braintreepayments.api.core.MetadataBuilder import com.braintreepayments.api.core.TokenizationKey import com.braintreepayments.api.core.UserCanceledException @@ -31,7 +32,8 @@ import org.json.JSONObject class GooglePayClient internal constructor( private val braintreeClient: BraintreeClient, private val internalGooglePayClient: GooglePayInternalClient = GooglePayInternalClient(), - private val analyticsParamRepository: AnalyticsParamRepository = AnalyticsParamRepository.instance + private val analyticsParamRepository: AnalyticsParamRepository = AnalyticsParamRepository.instance, + private val merchantRepository: MerchantRepository = MerchantRepository.instance, ) { /** * Initializes a new [GooglePayClient] instance @@ -154,7 +156,7 @@ class GooglePayClient internal constructor( if (configuration != null) { callback.onTokenizationParametersResult( GooglePayTokenizationParameters.Success( - getTokenizationParameters(configuration, braintreeClient.authorization), + getTokenizationParameters(configuration, merchantRepository.authorization), getAllowedCardNetworks(configuration) ) ) @@ -201,7 +203,7 @@ class GooglePayClient internal constructor( braintreeClient.getConfiguration { configuration: Configuration?, configError: Exception? -> if (configuration?.isGooglePayEnabled == true) { - setGooglePayRequestDefaults(configuration, braintreeClient.authorization, request) + setGooglePayRequestDefaults(configuration, merchantRepository.authorization, request) val paymentDataRequest = PaymentDataRequest.fromJson(request.toJson()) @@ -315,7 +317,7 @@ class GooglePayClient internal constructor( ): PaymentMethodTokenizationParameters { val metadata = - MetadataBuilder().integration(braintreeClient.integrationType) + MetadataBuilder().integration(merchantRepository.integrationType) .sessionId(analyticsParamRepository.sessionId).version().build() val version = try { @@ -467,7 +469,7 @@ class GooglePayClient internal constructor( .put("braintree:merchantId", configuration.merchantId) .put( "braintree:metadata", JSONObject().put("source", "client") - .put("integration", braintreeClient.integrationType) + .put("integration", merchantRepository.integrationType) .put("sessionId", analyticsParamRepository.sessionId) .put("version", googlePayVersion) .put("platform", "android").toString() @@ -507,7 +509,7 @@ class GooglePayClient internal constructor( ) .put( "braintree:metadata", JSONObject().put("source", "client") - .put("integration", braintreeClient.integrationType) + .put("integration", merchantRepository.integrationType) .put("sessionId", analyticsParamRepository.sessionId) .put("version", googlePayVersion) .put("platform", "android").toString() diff --git a/GooglePay/src/test/java/com/braintreepayments/api/googlepay/GooglePayClientUnitTest.java b/GooglePay/src/test/java/com/braintreepayments/api/googlepay/GooglePayClientUnitTest.java index 5be5268685..23dd571dd3 100644 --- a/GooglePay/src/test/java/com/braintreepayments/api/googlepay/GooglePayClientUnitTest.java +++ b/GooglePay/src/test/java/com/braintreepayments/api/googlepay/GooglePayClientUnitTest.java @@ -23,6 +23,7 @@ import com.braintreepayments.api.core.BraintreeClient; import com.braintreepayments.api.core.BraintreeException; import com.braintreepayments.api.core.Configuration; +import com.braintreepayments.api.core.MerchantRepository; import com.braintreepayments.api.testutils.Fixtures; import com.braintreepayments.api.testutils.MockBraintreeClientBuilder; import com.braintreepayments.api.paypal.PayPalAccountNonce; @@ -63,6 +64,8 @@ public class GooglePayClientUnitTest { private AnalyticsParamRepository analyticsParamRepository; + private MerchantRepository merchantRepository = mock(MerchantRepository.class); + @Before public void beforeEach() { activity = mock(FragmentActivity.class); @@ -93,7 +96,12 @@ public void isReadyToPay_sendsReadyToPayRequest() throws JSONException { GooglePayInternalClient internalGooglePayClient = new MockGooglePayInternalClientBuilder().build(); - GooglePayClient sut = new GooglePayClient(braintreeClient, internalGooglePayClient, analyticsParamRepository); + GooglePayClient sut = new GooglePayClient( + braintreeClient, + internalGooglePayClient, + analyticsParamRepository, + merchantRepository + ); sut.isReadyToPay(activity, null, readyToPayCallback); ArgumentCaptor captor = @@ -125,7 +133,12 @@ public void isReadyToPay_whenExistingPaymentMethodRequired_sendsIsReadyToPayRequ GooglePayInternalClient internalGooglePayClient = new MockGooglePayInternalClientBuilder().build(); - GooglePayClient sut = new GooglePayClient(braintreeClient, internalGooglePayClient, analyticsParamRepository); + GooglePayClient sut = new GooglePayClient( + braintreeClient, + internalGooglePayClient, + analyticsParamRepository, + merchantRepository + ); sut.isReadyToPay(activity, readyForGooglePayRequest, readyToPayCallback); ArgumentCaptor captor = @@ -147,15 +160,21 @@ public void isReadyToPay_returnsFalseWhenGooglePayIsNotEnabled() { BraintreeClient braintreeClient = new MockBraintreeClientBuilder() .configuration(configuration) - .authorizationSuccess(Authorization.fromString(Fixtures.TOKENIZATION_KEY)) .activityInfo(activityInfo) .build(); + + when(merchantRepository.getAuthorization()).thenReturn(Authorization.fromString(Fixtures.TOKENIZATION_KEY)); GooglePayInternalClient internalGooglePayClient = new MockGooglePayInternalClientBuilder() .isReadyToPay(true) .build(); - GooglePayClient sut = new GooglePayClient(braintreeClient, internalGooglePayClient, analyticsParamRepository); + GooglePayClient sut = new GooglePayClient( + braintreeClient, + internalGooglePayClient, + analyticsParamRepository, + merchantRepository + ); sut.isReadyToPay(activity, null, readyToPayCallback); verify(readyToPayCallback).onGooglePayReadinessResult(any(GooglePayReadinessResult.NotReadyToPay.class)); @@ -174,15 +193,21 @@ public void createPaymentAuthRequest_resetsSessionId() { BraintreeClient braintreeClient = new MockBraintreeClientBuilder() .configuration(configuration) - .authorizationSuccess(Authorization.fromString(Fixtures.TOKENIZATION_KEY)) .activityInfo(activityInfo) .build(); + when(merchantRepository.getAuthorization()).thenReturn(Authorization.fromString(Fixtures.TOKENIZATION_KEY)); + GooglePayInternalClient internalGooglePayClient = new MockGooglePayInternalClientBuilder() .isReadyToPay(true) .build(); - GooglePayClient sut = new GooglePayClient(braintreeClient, internalGooglePayClient, analyticsParamRepository); + GooglePayClient sut = new GooglePayClient( + braintreeClient, + internalGooglePayClient, + analyticsParamRepository, + merchantRepository + ); sut.createPaymentAuthRequest(mock(), mock()); @@ -203,10 +228,11 @@ public void createPaymentAuthRequest_callsBackIntentData() throws JSONException BraintreeClient braintreeClient = new MockBraintreeClientBuilder() .configuration(configuration) - .authorizationSuccess(Authorization.fromString("sandbox_tokenization_string")) .activityInfo(activityInfo) .build(); + when(merchantRepository.getAuthorization()).thenReturn(Authorization.fromString("sandbox_tokenization_string")); + GooglePayRequest googlePayRequest = new GooglePayRequest("USD", "1.00", GooglePayTotalPriceStatus.TOTAL_PRICE_STATUS_FINAL); googlePayRequest.setAllowPrepaidCards(true); googlePayRequest.setBillingAddressFormat(GooglePayBillingAddressFormat.FULL); @@ -219,7 +245,12 @@ public void createPaymentAuthRequest_callsBackIntentData() throws JSONException GooglePayInternalClient internalGooglePayClient = new MockGooglePayInternalClientBuilder().build(); - GooglePayClient sut = new GooglePayClient(braintreeClient, internalGooglePayClient, analyticsParamRepository); + GooglePayClient sut = new GooglePayClient( + braintreeClient, + internalGooglePayClient, + analyticsParamRepository, + merchantRepository + ); sut.createPaymentAuthRequest(googlePayRequest, intentDataCallback); ArgumentCaptor captor = ArgumentCaptor.forClass( @@ -329,16 +360,22 @@ public void createPaymentAuthRequest_includesATokenizationKeyWhenPresent() throw BraintreeClient braintreeClient = new MockBraintreeClientBuilder() .configuration(configuration) - .authorizationSuccess(Authorization.fromString(Fixtures.TOKENIZATION_KEY)) .activityInfo(activityInfo) .build(); + when(merchantRepository.getAuthorization()).thenReturn(Authorization.fromString(Fixtures.TOKENIZATION_KEY)); + GooglePayRequest googlePayRequest = new GooglePayRequest("USD", "1.00", GooglePayTotalPriceStatus.TOTAL_PRICE_STATUS_FINAL); GooglePayInternalClient internalGooglePayClient = new MockGooglePayInternalClientBuilder().build(); - GooglePayClient sut = new GooglePayClient(braintreeClient, internalGooglePayClient, analyticsParamRepository); + GooglePayClient sut = new GooglePayClient( + braintreeClient, + internalGooglePayClient, + analyticsParamRepository, + merchantRepository + ); sut.createPaymentAuthRequest(googlePayRequest, intentDataCallback); ArgumentCaptor captor = ArgumentCaptor.forClass( @@ -375,16 +412,22 @@ public void createPaymentAuthRequest_doesNotIncludeATokenizationKeyWhenNotPresen BraintreeClient braintreeClient = new MockBraintreeClientBuilder() .configuration(configuration) - .authorizationSuccess(Authorization.fromString(Fixtures.BASE64_CLIENT_TOKEN)) .activityInfo(activityInfo) .build(); + when(merchantRepository.getAuthorization()).thenReturn(Authorization.fromString(Fixtures.BASE64_CLIENT_TOKEN)); + GooglePayRequest googlePayRequest = new GooglePayRequest("USD", "1.00", GooglePayTotalPriceStatus.TOTAL_PRICE_STATUS_FINAL); GooglePayInternalClient internalGooglePayClient = new MockGooglePayInternalClientBuilder().build(); - GooglePayClient sut = new GooglePayClient(braintreeClient, internalGooglePayClient, analyticsParamRepository); + GooglePayClient sut = new GooglePayClient( + braintreeClient, + internalGooglePayClient, + analyticsParamRepository, + merchantRepository + ); sut.createPaymentAuthRequest(googlePayRequest, intentDataCallback); ArgumentCaptor captor = ArgumentCaptor.forClass( @@ -421,16 +464,22 @@ public void createPaymentAuthRequest_sendsAnalyticsEvent() { BraintreeClient braintreeClient = new MockBraintreeClientBuilder() .configuration(configuration) - .authorizationSuccess(Authorization.fromString("sandbox_tokenization_string")) .activityInfo(activityInfo) .build(); + when(merchantRepository.getAuthorization()).thenReturn(Authorization.fromString("sandbox_tokenization_string")); + GooglePayRequest googlePayRequest = new GooglePayRequest("USD", "1.00", GooglePayTotalPriceStatus.TOTAL_PRICE_STATUS_FINAL); GooglePayInternalClient internalGooglePayClient = new MockGooglePayInternalClientBuilder().build(); - GooglePayClient sut = new GooglePayClient(braintreeClient, internalGooglePayClient, analyticsParamRepository); + GooglePayClient sut = new GooglePayClient( + braintreeClient, + internalGooglePayClient, + analyticsParamRepository, + merchantRepository + ); sut.createPaymentAuthRequest(googlePayRequest, intentDataCallback); InOrder order = inOrder(braintreeClient); @@ -443,15 +492,21 @@ public void createPaymentAuthRequest_whenMerchantNotConfigured_returnsExceptionT Configuration configuration = new TestConfigurationBuilder().buildConfiguration(); BraintreeClient braintreeClient = new MockBraintreeClientBuilder() - .authorizationSuccess(Authorization.fromString(Fixtures.BASE64_CLIENT_TOKEN)) .configuration(configuration) .activityInfo(activityInfo) .build(); + when(merchantRepository.getAuthorization()).thenReturn(Authorization.fromString(Fixtures.BASE64_CLIENT_TOKEN)); + GooglePayInternalClient internalGooglePayClient = new MockGooglePayInternalClientBuilder().build(); - GooglePayClient sut = new GooglePayClient(braintreeClient, internalGooglePayClient, analyticsParamRepository); + GooglePayClient sut = new GooglePayClient( + braintreeClient, + internalGooglePayClient, + analyticsParamRepository, + merchantRepository + ); sut.createPaymentAuthRequest(baseRequest, intentDataCallback); ArgumentCaptor captor = ArgumentCaptor.forClass( @@ -483,14 +538,20 @@ public void createPaymentAuthRequest_whenSandbox_setsTestEnvironment() throws JS BraintreeClient braintreeClient = new MockBraintreeClientBuilder() .configuration(configuration) - .authorizationSuccess(Authorization.fromString("sandbox_tokenization_string")) .activityInfo(activityInfo) .build(); + when(merchantRepository.getAuthorization()).thenReturn(Authorization.fromString("sandbox_tokenization_string")); + GooglePayInternalClient internalGooglePayClient = new MockGooglePayInternalClientBuilder().build(); - GooglePayClient sut = new GooglePayClient(braintreeClient, internalGooglePayClient, analyticsParamRepository); + GooglePayClient sut = new GooglePayClient( + braintreeClient, + internalGooglePayClient, + analyticsParamRepository, + merchantRepository + ); sut.createPaymentAuthRequest(baseRequest, intentDataCallback); ArgumentCaptor captor = ArgumentCaptor.forClass( @@ -522,14 +583,20 @@ public void createPaymentAuthRequest_whenProduction_setsProductionEnvironment() BraintreeClient braintreeClient = new MockBraintreeClientBuilder() .configuration(configuration) - .authorizationSuccess(Authorization.fromString("sandbox_tokenization_string")) .activityInfo(activityInfo) .build(); + when(merchantRepository.getAuthorization()).thenReturn(Authorization.fromString("sandbox_tokenization_string")); + GooglePayInternalClient internalGooglePayClient = new MockGooglePayInternalClientBuilder().build(); - GooglePayClient sut = new GooglePayClient(braintreeClient, internalGooglePayClient, analyticsParamRepository); + GooglePayClient sut = new GooglePayClient( + braintreeClient, + internalGooglePayClient, + analyticsParamRepository, + merchantRepository + ); sut.createPaymentAuthRequest(baseRequest, intentDataCallback); ArgumentCaptor captor = ArgumentCaptor.forClass( @@ -562,16 +629,22 @@ public void createPaymentAuthRequest_withGoogleMerchantName_sendGoogleMerchantNa BraintreeClient braintreeClient = new MockBraintreeClientBuilder() .configuration(configuration) - .authorizationSuccess(Authorization.fromString("sandbox_tokenization_string")) .activityInfo(activityInfo) .build(); + when(merchantRepository.getAuthorization()).thenReturn(Authorization.fromString("sandbox_tokenization_string")); + baseRequest.setGoogleMerchantName("google-merchant-name-override"); GooglePayInternalClient internalGooglePayClient = new MockGooglePayInternalClientBuilder().build(); - GooglePayClient sut = new GooglePayClient(braintreeClient, internalGooglePayClient, analyticsParamRepository); + GooglePayClient sut = new GooglePayClient( + braintreeClient, + internalGooglePayClient, + analyticsParamRepository, + merchantRepository + ); sut.createPaymentAuthRequest(baseRequest, intentDataCallback); ArgumentCaptor captor = ArgumentCaptor.forClass( @@ -605,17 +678,23 @@ public void createPaymentAuthRequest_whenGooglePayCanProcessPayPal_tokenizationP BraintreeClient braintreeClient = new MockBraintreeClientBuilder() .configuration(configuration) - .authorizationSuccess(Authorization.fromString("sandbox_tokenization_string")) .activityInfo(activityInfo) .build(); + when(merchantRepository.getAuthorization()).thenReturn(Authorization.fromString("sandbox_tokenization_string")); + GooglePayRequest googlePayRequest = baseRequest; googlePayRequest.setGoogleMerchantName("google-merchant-name-override"); GooglePayInternalClient internalGooglePayClient = new MockGooglePayInternalClientBuilder().build(); - GooglePayClient sut = new GooglePayClient(braintreeClient, internalGooglePayClient, analyticsParamRepository); + GooglePayClient sut = new GooglePayClient( + braintreeClient, + internalGooglePayClient, + analyticsParamRepository, + merchantRepository + ); sut.createPaymentAuthRequest(baseRequest, intentDataCallback); ArgumentCaptor captor = ArgumentCaptor.forClass( @@ -653,10 +732,11 @@ public void createPaymentAuthRequest_whenPayPalDisabledByRequest_tokenizationPro BraintreeClient braintreeClient = new MockBraintreeClientBuilder() .configuration(configuration) - .authorizationSuccess(Authorization.fromString("sandbox_tokenization_string")) .activityInfo(activityInfo) .build(); + when(merchantRepository.getAuthorization()).thenReturn(Authorization.fromString("sandbox_tokenization_string")); + GooglePayRequest googlePayRequest = baseRequest; googlePayRequest.setGoogleMerchantName("google-merchant-name-override"); googlePayRequest.setPayPalEnabled(false); @@ -664,7 +744,12 @@ public void createPaymentAuthRequest_whenPayPalDisabledByRequest_tokenizationPro GooglePayInternalClient internalGooglePayClient = new MockGooglePayInternalClientBuilder().build(); - GooglePayClient sut = new GooglePayClient(braintreeClient, internalGooglePayClient, analyticsParamRepository); + GooglePayClient sut = new GooglePayClient( + braintreeClient, + internalGooglePayClient, + analyticsParamRepository, + merchantRepository + ); sut.createPaymentAuthRequest(baseRequest, intentDataCallback); ArgumentCaptor captor = ArgumentCaptor.forClass( @@ -703,17 +788,23 @@ public void createPaymentAuthRequest_whenPayPalDisabledInConfigurationAndGoogleP BraintreeClient braintreeClient = new MockBraintreeClientBuilder() .configuration(configuration) - .authorizationSuccess(Authorization.fromString("sandbox_tokenization_string")) .activityInfo(activityInfo) .build(); + when(merchantRepository.getAuthorization()).thenReturn(Authorization.fromString("sandbox_tokenization_string")); + GooglePayRequest googlePayRequest = baseRequest; googlePayRequest.setGoogleMerchantName("google-merchant-name-override"); GooglePayInternalClient internalGooglePayClient = new MockGooglePayInternalClientBuilder().build(); - GooglePayClient sut = new GooglePayClient(braintreeClient, internalGooglePayClient, analyticsParamRepository); + GooglePayClient sut = new GooglePayClient( + braintreeClient, + internalGooglePayClient, + analyticsParamRepository, + merchantRepository + ); sut.createPaymentAuthRequest(baseRequest, intentDataCallback); ArgumentCaptor captor = ArgumentCaptor.forClass( @@ -753,17 +844,23 @@ public void createPaymentAuthRequest_usesGooglePayConfigurationClientId() throws BraintreeClient braintreeClient = new MockBraintreeClientBuilder() .configuration(configuration) - .authorizationSuccess(Authorization.fromString("sandbox_tokenization_string")) .activityInfo(activityInfo) .build(); + when(merchantRepository.getAuthorization()).thenReturn(Authorization.fromString("sandbox_tokenization_string")); + GooglePayRequest googlePayRequest = baseRequest; googlePayRequest.setGoogleMerchantName("google-merchant-name-override"); GooglePayInternalClient internalGooglePayClient = new MockGooglePayInternalClientBuilder().build(); - GooglePayClient sut = new GooglePayClient(braintreeClient, internalGooglePayClient, analyticsParamRepository); + GooglePayClient sut = new GooglePayClient( + braintreeClient, + internalGooglePayClient, + analyticsParamRepository, + merchantRepository + ); sut.createPaymentAuthRequest(baseRequest, intentDataCallback); ArgumentCaptor captor = ArgumentCaptor.forClass( @@ -810,17 +907,23 @@ public void createPaymentAuthRequest_whenGooglePayConfigurationLacksClientId_tok BraintreeClient braintreeClient = new MockBraintreeClientBuilder() .configuration(configuration) - .authorizationSuccess(Authorization.fromString("sandbox_tokenization_string")) .activityInfo(activityInfo) .build(); + when(merchantRepository.getAuthorization()).thenReturn(Authorization.fromString("sandbox_tokenization_string")); + GooglePayRequest googlePayRequest = baseRequest; googlePayRequest.setGoogleMerchantName("google-merchant-name-override"); GooglePayInternalClient internalGooglePayClient = new MockGooglePayInternalClientBuilder().build(); - GooglePayClient sut = new GooglePayClient(braintreeClient, internalGooglePayClient, analyticsParamRepository); + GooglePayClient sut = new GooglePayClient( + braintreeClient, + internalGooglePayClient, + analyticsParamRepository, + merchantRepository + ); sut.createPaymentAuthRequest(baseRequest, intentDataCallback); ArgumentCaptor captor = ArgumentCaptor.forClass( @@ -859,17 +962,23 @@ public void createPaymentAuthRequest_whenConfigurationContainsElo_addsEloAndEloD BraintreeClient braintreeClient = new MockBraintreeClientBuilder() .configuration(configuration) - .authorizationSuccess(Authorization.fromString("sandbox_tokenization_string")) .activityInfo(activityInfo) .build(); + when(merchantRepository.getAuthorization()).thenReturn(Authorization.fromString("sandbox_tokenization_string")); + GooglePayRequest googlePayRequest = baseRequest; googlePayRequest.setGoogleMerchantName("google-merchant-name-override"); GooglePayInternalClient internalGooglePayClient = new MockGooglePayInternalClientBuilder().build(); - GooglePayClient sut = new GooglePayClient(braintreeClient, internalGooglePayClient, analyticsParamRepository); + GooglePayClient sut = new GooglePayClient( + braintreeClient, + internalGooglePayClient, + analyticsParamRepository, + merchantRepository + ); sut.createPaymentAuthRequest(baseRequest, intentDataCallback); ArgumentCaptor captor = ArgumentCaptor.forClass( @@ -908,14 +1017,20 @@ public void createPaymentAuthRequest_whenManifestInvalid_forwardsExceptionToList BraintreeClient braintreeClient = new MockBraintreeClientBuilder() .configuration(configuration) - .authorizationSuccess(Authorization.fromString("sandbox_tokenization_string")) .activityInfo(null) .build(); + when(merchantRepository.getAuthorization()).thenReturn(Authorization.fromString("sandbox_tokenization_string")); + GooglePayInternalClient internalGooglePayClient = new MockGooglePayInternalClientBuilder().build(); - GooglePayClient sut = new GooglePayClient(braintreeClient, internalGooglePayClient, analyticsParamRepository); + GooglePayClient sut = new GooglePayClient( + braintreeClient, + internalGooglePayClient, + analyticsParamRepository, + merchantRepository + ); sut.createPaymentAuthRequest(baseRequest, intentDataCallback); ArgumentCaptor captor = ArgumentCaptor.forClass( @@ -952,16 +1067,22 @@ public void tokenize_withCardToken_returnsGooglePayNonce() { BraintreeClient braintreeClient = new MockBraintreeClientBuilder() .configuration(configuration) - .authorizationSuccess(Authorization.fromString("sandbox_tokenization_string")) .activityInfo(activityInfo) .build(); + when(merchantRepository.getAuthorization()).thenReturn(Authorization.fromString("sandbox_tokenization_string")); + PaymentData pd = PaymentData.fromJson(paymentDataJson); GooglePayInternalClient internalGooglePayClient = new MockGooglePayInternalClientBuilder().build(); - GooglePayClient sut = new GooglePayClient(braintreeClient, internalGooglePayClient, analyticsParamRepository); + GooglePayClient sut = new GooglePayClient( + braintreeClient, + internalGooglePayClient, + analyticsParamRepository, + merchantRepository + ); sut.tokenize(pd, activityResultCallback); ArgumentCaptor captor = @@ -990,16 +1111,22 @@ public void tokenize_withPayPalToken_returnsPayPalAccountNonce() { BraintreeClient braintreeClient = new MockBraintreeClientBuilder() .configuration(configuration) - .authorizationSuccess(Authorization.fromString("sandbox_tokenization_string")) .activityInfo(activityInfo) .build(); + when(merchantRepository.getAuthorization()).thenReturn(Authorization.fromString("sandbox_tokenization_string")); + PaymentData pd = PaymentData.fromJson(paymentDataJson); GooglePayInternalClient internalGooglePayClient = new MockGooglePayInternalClientBuilder().build(); - GooglePayClient sut = new GooglePayClient(braintreeClient, internalGooglePayClient, analyticsParamRepository); + GooglePayClient sut = new GooglePayClient( + braintreeClient, + internalGooglePayClient, + analyticsParamRepository, + merchantRepository + ); sut.tokenize(pd, activityResultCallback); ArgumentCaptor captor = @@ -1022,7 +1149,12 @@ public void tokenize_whenPaymentDataExists_returnsResultToListener_andSendsAnaly GooglePayInternalClient internalGooglePayClient = new MockGooglePayInternalClientBuilder().build(); - GooglePayClient sut = new GooglePayClient(braintreeClient, internalGooglePayClient, analyticsParamRepository); + GooglePayClient sut = new GooglePayClient( + braintreeClient, + internalGooglePayClient, + analyticsParamRepository, + merchantRepository + ); String paymentDataJson = Fixtures.RESPONSE_GOOGLE_PAY_CARD; PaymentData paymentData = PaymentData.fromJson(paymentDataJson); @@ -1049,7 +1181,12 @@ public void tokenize_whenErrorExists_returnsErrorToListener_andSendsAnalytics() GooglePayInternalClient internalGooglePayClient = new MockGooglePayInternalClientBuilder().build(); - GooglePayClient sut = new GooglePayClient(braintreeClient, internalGooglePayClient, analyticsParamRepository); + GooglePayClient sut = new GooglePayClient( + braintreeClient, + internalGooglePayClient, + analyticsParamRepository, + merchantRepository + ); Exception error = new Exception("Error"); GooglePayPaymentAuthResult @@ -1072,7 +1209,12 @@ public void tokenize_whenUserCanceledErrorExists_returnsErrorToListener_andSends GooglePayInternalClient internalGooglePayClient = new MockGooglePayInternalClientBuilder().build(); - GooglePayClient sut = new GooglePayClient(braintreeClient, internalGooglePayClient, analyticsParamRepository); + GooglePayClient sut = new GooglePayClient( + braintreeClient, + internalGooglePayClient, + analyticsParamRepository, + merchantRepository + ); UserCanceledException userCanceledError = new UserCanceledException("User canceled Google Pay."); @@ -1102,14 +1244,20 @@ public void getAllowedCardNetworks_returnsSupportedNetworks() { BraintreeClient braintreeClient = new MockBraintreeClientBuilder() .configuration(configuration) - .authorizationSuccess(Authorization.fromString("sandbox_tokenization_string")) .activityInfo(activityInfo) .build(); + when(merchantRepository.getAuthorization()).thenReturn(Authorization.fromString("sandbox_tokenization_string")); + GooglePayInternalClient internalGooglePayClient = new MockGooglePayInternalClientBuilder().build(); - GooglePayClient sut = new GooglePayClient(braintreeClient, internalGooglePayClient, analyticsParamRepository); + GooglePayClient sut = new GooglePayClient( + braintreeClient, + internalGooglePayClient, + analyticsParamRepository, + merchantRepository + ); Collection allowedCardNetworks = sut.getAllowedCardNetworks(configuration); @@ -1136,13 +1284,19 @@ public void getTokenizationParameters_returnsCorrectParameters() { Authorization authorization = Authorization.fromString(Fixtures.TOKENIZATION_KEY); BraintreeClient braintreeClient = new MockBraintreeClientBuilder() .configuration(configuration) - .authorizationSuccess(authorization) .activityInfo(activityInfo) .build(); + when(merchantRepository.getAuthorization()).thenReturn(authorization); + GooglePayInternalClient internalGooglePayClient = new MockGooglePayInternalClientBuilder().build(); - GooglePayClient sut = new GooglePayClient(braintreeClient, internalGooglePayClient, analyticsParamRepository); + GooglePayClient sut = new GooglePayClient( + braintreeClient, + internalGooglePayClient, + analyticsParamRepository, + merchantRepository + ); Bundle tokenizationParameters = sut.getTokenizationParameters(configuration, authorization).getParameters(); @@ -1169,13 +1323,19 @@ public void getTokenizationParameters_doesNotIncludeATokenizationKeyWhenNotPrese Authorization authorization = Authorization.fromString(Fixtures.BASE64_CLIENT_TOKEN); BraintreeClient braintreeClient = new MockBraintreeClientBuilder() .configuration(configuration) - .authorizationSuccess(authorization) .activityInfo(activityInfo) .build(); + when(merchantRepository.getAuthorization()).thenReturn(authorization); + GooglePayInternalClient internalGooglePayClient = new MockGooglePayInternalClientBuilder().build(); - GooglePayClient sut = new GooglePayClient(braintreeClient, internalGooglePayClient, analyticsParamRepository); + GooglePayClient sut = new GooglePayClient( + braintreeClient, + internalGooglePayClient, + analyticsParamRepository, + merchantRepository + ); Bundle tokenizationParameters = sut.getTokenizationParameters(configuration, authorization).getParameters(); @@ -1194,13 +1354,18 @@ public void getTokenizationParameters_includesATokenizationKeyWhenPresent() { Authorization authorization = Authorization.fromString(Fixtures.TOKENIZATION_KEY); BraintreeClient braintreeClient = new MockBraintreeClientBuilder() .configuration(configuration) - .authorizationSuccess(authorization) .activityInfo(activityInfo) .build(); - GooglePayInternalClient internalGooglePayClient = - new MockGooglePayInternalClientBuilder().build(); - GooglePayClient sut = new GooglePayClient(braintreeClient, internalGooglePayClient, analyticsParamRepository); + when(merchantRepository.getAuthorization()).thenReturn(authorization); + + GooglePayInternalClient internalGooglePayClient = new MockGooglePayInternalClientBuilder().build(); + GooglePayClient sut = new GooglePayClient( + braintreeClient, + internalGooglePayClient, + analyticsParamRepository, + merchantRepository + ); Bundle tokenizationParameters = sut.getTokenizationParameters(configuration, authorization).getParameters(); @@ -1219,13 +1384,19 @@ public void getTokenizationParameters_forwardsParametersAndAllowedCardsToCallbac BraintreeClient braintreeClient = new MockBraintreeClientBuilder() .configuration(configuration) - .authorizationSuccess(Authorization.fromString(Fixtures.TOKENIZATION_KEY)) .activityInfo(activityInfo) .build(); + when(merchantRepository.getAuthorization()).thenReturn(Authorization.fromString(Fixtures.TOKENIZATION_KEY)); + GooglePayInternalClient internalGooglePayClient = new MockGooglePayInternalClientBuilder().build(); - GooglePayClient sut = new GooglePayClient(braintreeClient, internalGooglePayClient, analyticsParamRepository); + GooglePayClient sut = new GooglePayClient( + braintreeClient, + internalGooglePayClient, + analyticsParamRepository, + merchantRepository + ); sut.getTokenizationParameters(tokenizationParameters -> { assertTrue(tokenizationParameters instanceof GooglePayTokenizationParameters.Success); diff --git a/LocalPayment/src/main/java/com/braintreepayments/api/localpayment/LocalPaymentApi.kt b/LocalPayment/src/main/java/com/braintreepayments/api/localpayment/LocalPaymentApi.kt index 6ceb0f2198..e3444afa46 100644 --- a/LocalPayment/src/main/java/com/braintreepayments/api/localpayment/LocalPaymentApi.kt +++ b/LocalPayment/src/main/java/com/braintreepayments/api/localpayment/LocalPaymentApi.kt @@ -2,13 +2,15 @@ package com.braintreepayments.api.localpayment import com.braintreepayments.api.core.AnalyticsParamRepository import com.braintreepayments.api.core.BraintreeClient +import com.braintreepayments.api.core.MerchantRepository import com.braintreepayments.api.localpayment.LocalPaymentNonce.Companion.fromJSON import org.json.JSONException import org.json.JSONObject internal class LocalPaymentApi( private val braintreeClient: BraintreeClient, - private val analyticsParamRepository: AnalyticsParamRepository = AnalyticsParamRepository.instance + private val analyticsParamRepository: AnalyticsParamRepository = AnalyticsParamRepository.instance, + private val merchantRepository: MerchantRepository = MerchantRepository.instance, ) { fun createPaymentMethod( @@ -66,7 +68,7 @@ internal class LocalPaymentApi( val metaData = JSONObject() .put("source", "client") - .put("integration", braintreeClient.integrationType.stringValue) + .put("integration", merchantRepository.integrationType.stringValue) .put("sessionId", analyticsParamRepository.sessionId) payload.put("_meta", metaData) diff --git a/LocalPayment/src/test/java/com/braintreepayments/api/localpayment/LocalPaymentApiUnitTest.java b/LocalPayment/src/test/java/com/braintreepayments/api/localpayment/LocalPaymentApiUnitTest.java index 297f3e631a..e076511105 100644 --- a/LocalPayment/src/test/java/com/braintreepayments/api/localpayment/LocalPaymentApiUnitTest.java +++ b/LocalPayment/src/test/java/com/braintreepayments/api/localpayment/LocalPaymentApiUnitTest.java @@ -18,6 +18,7 @@ import com.braintreepayments.api.core.AnalyticsParamRepository; import com.braintreepayments.api.core.BraintreeClient; import com.braintreepayments.api.core.IntegrationType; +import com.braintreepayments.api.core.MerchantRepository; import com.braintreepayments.api.core.PostalAddress; import com.braintreepayments.api.sharedutils.HttpResponseCallback; import com.braintreepayments.api.testutils.Fixtures; @@ -39,35 +40,37 @@ public class LocalPaymentApiUnitTest { private LocalPaymentInternalTokenizeCallback localPaymentInternalTokenizeCallback; private AnalyticsParamRepository analyticsParamRepository; + private MerchantRepository merchantRepository = mock(MerchantRepository.class); @Before public void beforeEach() { analyticsParamRepository = mock(AnalyticsParamRepository.class); localPaymentInternalAuthRequestCallback = - mock(LocalPaymentInternalAuthRequestCallback.class); + mock(LocalPaymentInternalAuthRequestCallback.class); localPaymentInternalTokenizeCallback = - mock(LocalPaymentInternalTokenizeCallback.class); + mock(LocalPaymentInternalTokenizeCallback.class); when(analyticsParamRepository.getSessionId()).thenReturn("sample-session-id"); + when(merchantRepository.getIntegrationType()).thenReturn(IntegrationType.CUSTOM); } @Test public void createPaymentMethod_sendsCorrectPostParams() throws JSONException { BraintreeClient braintreeClient = new MockBraintreeClientBuilder() - .returnUrlScheme("sample-scheme") - .build(); + .returnUrlScheme("sample-scheme") + .build(); - LocalPaymentApi sut = new LocalPaymentApi(braintreeClient, analyticsParamRepository); + LocalPaymentApi sut = new LocalPaymentApi(braintreeClient, analyticsParamRepository, merchantRepository); sut.createPaymentMethod( - getIdealLocalPaymentRequest(), - localPaymentInternalAuthRequestCallback + getIdealLocalPaymentRequest(), + localPaymentInternalAuthRequestCallback ); String expectedPath = "/v1/local_payments/create"; ArgumentCaptor bodyCaptor = ArgumentCaptor.forClass(String.class); verify(braintreeClient).sendPOST( - eq(expectedPath), bodyCaptor.capture(), anyMap(), - any(HttpResponseCallback.class)); + eq(expectedPath), bodyCaptor.capture(), anyMap(), + any(HttpResponseCallback.class)); String requestBody = bodyCaptor.getValue(); JSONObject json = new JSONObject(requestBody); @@ -88,8 +91,8 @@ public void createPaymentMethod_sendsCorrectPostParams() throws JSONException { assertEquals("local-merchant-account-id", json.getString("merchantAccountId")); assertTrue(json.getJSONObject("experienceProfile").getBoolean("noShipping")); assertEquals( - "My Brand!", - json.getJSONObject("experienceProfile").getString("brandName") + "My Brand!", + json.getJSONObject("experienceProfile").getString("brandName") ); String expectedCancelUrl = Uri.parse("sample-scheme://local-payment-cancel").toString(); String expectedReturnUrl = Uri.parse("sample-scheme://local-payment-success").toString(); @@ -101,18 +104,19 @@ public void createPaymentMethod_sendsCorrectPostParams() throws JSONException { public void createPaymentMethod_onPOSTError_forwardsErrorToCallback() { Exception error = new Exception("error"); BraintreeClient braintreeClient = new MockBraintreeClientBuilder() - .sendPOSTErrorResponse(error) - .build(); + .sendPOSTErrorResponse(error) + .build(); + + LocalPaymentApi sut = new LocalPaymentApi(braintreeClient, analyticsParamRepository, merchantRepository); - LocalPaymentApi sut = new LocalPaymentApi(braintreeClient, analyticsParamRepository); sut.createPaymentMethod( - getIdealLocalPaymentRequest(), - localPaymentInternalAuthRequestCallback + getIdealLocalPaymentRequest(), + localPaymentInternalAuthRequestCallback ); verify(localPaymentInternalAuthRequestCallback).onLocalPaymentInternalAuthResult( - isNull(), - same(error) + isNull(), + same(error) ); } @@ -120,19 +124,20 @@ public void createPaymentMethod_onPOSTError_forwardsErrorToCallback() { @Test public void createPaymentMethod_onJSONError_forwardsJSONErrorToCallback() { BraintreeClient braintreeClient = new MockBraintreeClientBuilder() - .sendPOSTSuccessfulResponse(Fixtures.ERROR_RESPONSE) - .build(); + .sendPOSTSuccessfulResponse(Fixtures.ERROR_RESPONSE) + .build(); + + LocalPaymentApi sut = new LocalPaymentApi(braintreeClient, analyticsParamRepository, merchantRepository); - LocalPaymentApi sut = new LocalPaymentApi(braintreeClient, analyticsParamRepository); sut.createPaymentMethod( - getIdealLocalPaymentRequest(), - localPaymentInternalAuthRequestCallback + getIdealLocalPaymentRequest(), + localPaymentInternalAuthRequestCallback ); ArgumentCaptor captor = ArgumentCaptor.forClass(Exception.class); verify(localPaymentInternalAuthRequestCallback).onLocalPaymentInternalAuthResult( - isNull(), - captor.capture() + isNull(), + captor.capture() ); assertTrue(captor.getValue() instanceof JSONException); @@ -141,26 +146,27 @@ public void createPaymentMethod_onJSONError_forwardsJSONErrorToCallback() { @Test public void createPaymentMethod_onPOSTSuccess_returnsResultWithOriginalRequestToCallback() { BraintreeClient braintreeClient = new MockBraintreeClientBuilder() - .sendPOSTSuccessfulResponse(Fixtures.PAYMENT_METHODS_LOCAL_PAYMENT_CREATE_RESPONSE) - .build(); + .sendPOSTSuccessfulResponse(Fixtures.PAYMENT_METHODS_LOCAL_PAYMENT_CREATE_RESPONSE) + .build(); + + LocalPaymentApi sut = new LocalPaymentApi(braintreeClient, analyticsParamRepository, merchantRepository); - LocalPaymentApi sut = new LocalPaymentApi(braintreeClient, analyticsParamRepository); LocalPaymentRequest request = getIdealLocalPaymentRequest(); sut.createPaymentMethod(request, localPaymentInternalAuthRequestCallback); ArgumentCaptor captor = - ArgumentCaptor.forClass(LocalPaymentAuthRequestParams.class); + ArgumentCaptor.forClass(LocalPaymentAuthRequestParams.class); verify(localPaymentInternalAuthRequestCallback).onLocalPaymentInternalAuthResult( - captor.capture(), - isNull() + captor.capture(), + isNull() ); LocalPaymentAuthRequestParams result = captor.getValue(); assertNotNull(result); assertSame(request, result.getRequest()); assertEquals( - "https://checkout.paypal.com/latinum?token=payment-token", - result.getApprovalUrl() + "https://checkout.paypal.com/latinum?token=payment-token", + result.getApprovalUrl() ); assertEquals("local-payment-id-123", result.getPaymentId()); } @@ -168,39 +174,39 @@ public void createPaymentMethod_onPOSTSuccess_returnsResultWithOriginalRequestTo @Test public void tokenize_sendsCorrectPostParams() throws JSONException { BraintreeClient braintreeClient = new MockBraintreeClientBuilder() - .integration(IntegrationType.CUSTOM) - .build(); + .build(); + + LocalPaymentApi sut = new LocalPaymentApi(braintreeClient, analyticsParamRepository, merchantRepository); - LocalPaymentApi sut = new LocalPaymentApi(braintreeClient, analyticsParamRepository); String webUrl = "sample-scheme://local-payment-success?paymentToken=successTokenId"; sut.tokenize( - "local-merchant-account-id", webUrl, "sample-correlation-id", - localPaymentInternalTokenizeCallback + "local-merchant-account-id", webUrl, "sample-correlation-id", + localPaymentInternalTokenizeCallback ); ArgumentCaptor bodyCaptor = ArgumentCaptor.forClass(String.class); String expectedUrl = "/v1/payment_methods/paypal_accounts"; verify(braintreeClient).sendPOST( - eq(expectedUrl), bodyCaptor.capture(),anyMap(), - any(HttpResponseCallback.class)); + eq(expectedUrl), bodyCaptor.capture(), anyMap(), + any(HttpResponseCallback.class)); String requestBody = bodyCaptor.getValue(); JSONObject expectedJSON = new JSONObject(); expectedJSON.put("merchant_account_id", "local-merchant-account-id"); JSONObject paypalAccount = new JSONObject() - .put("intent", "sale") - .put("response", new JSONObject().put("webURL", webUrl)) - .put("options", new JSONObject().put("validate", false)) - .put("response_type", "web") - .put("correlation_id", "sample-correlation-id"); + .put("intent", "sale") + .put("response", new JSONObject().put("webURL", webUrl)) + .put("options", new JSONObject().put("validate", false)) + .put("response_type", "web") + .put("correlation_id", "sample-correlation-id"); expectedJSON.put("paypal_account", paypalAccount); JSONObject metaData = new JSONObject() - .put("source", "client") - .put("integration", "custom") - .put("sessionId", "sample-session-id"); + .put("source", "client") + .put("integration", "custom") + .put("sessionId", "sample-session-id"); expectedJSON.put("_meta", metaData); JSONAssert.assertEquals(expectedJSON, new JSONObject(requestBody), true); @@ -210,15 +216,15 @@ public void tokenize_sendsCorrectPostParams() throws JSONException { public void tokenize_onPOSTError_forwardsErrorToCallback() { Exception error = new Exception("error"); BraintreeClient braintreeClient = new MockBraintreeClientBuilder() - .integration(IntegrationType.CUSTOM) - .sendPOSTErrorResponse(error) - .build(); + .sendPOSTErrorResponse(error) + .build(); + + LocalPaymentApi sut = new LocalPaymentApi(braintreeClient, analyticsParamRepository, merchantRepository); - LocalPaymentApi sut = new LocalPaymentApi(braintreeClient, analyticsParamRepository); String webUrl = "sample-scheme://local-payment-success?paymentToken=successTokenId"; sut.tokenize( - "local-merchant-account-id", webUrl, "sample-correlation-id", - localPaymentInternalTokenizeCallback + "local-merchant-account-id", webUrl, "sample-correlation-id", + localPaymentInternalTokenizeCallback ); verify(localPaymentInternalTokenizeCallback).onResult(isNull(), same(error)); @@ -227,15 +233,15 @@ public void tokenize_onPOSTError_forwardsErrorToCallback() { @Test public void tokenize_onJSONError_forwardsErrorToCallback() { BraintreeClient braintreeClient = new MockBraintreeClientBuilder() - .integration(IntegrationType.CUSTOM) - .sendPOSTSuccessfulResponse("not-json") - .build(); + .sendPOSTSuccessfulResponse("not-json") + .build(); + + LocalPaymentApi sut = new LocalPaymentApi(braintreeClient, analyticsParamRepository, merchantRepository); - LocalPaymentApi sut = new LocalPaymentApi(braintreeClient, analyticsParamRepository); String webUrl = "sample-scheme://local-payment-success?paymentToken=successTokenId"; sut.tokenize( - "local-merchant-account-id", webUrl, "sample-correlation-id", - localPaymentInternalTokenizeCallback + "local-merchant-account-id", webUrl, "sample-correlation-id", + localPaymentInternalTokenizeCallback ); ArgumentCaptor captor = ArgumentCaptor.forClass(Exception.class); @@ -247,21 +253,21 @@ public void tokenize_onJSONError_forwardsErrorToCallback() { @Test public void tokenize_onPOSTSuccess_returnsResultToCallback() { BraintreeClient braintreeClient = new MockBraintreeClientBuilder() - .integration(IntegrationType.CUSTOM) - .sendPOSTSuccessfulResponse(Fixtures.PAYMENT_METHODS_LOCAL_PAYMENT_RESPONSE) - .build(); + .sendPOSTSuccessfulResponse(Fixtures.PAYMENT_METHODS_LOCAL_PAYMENT_RESPONSE) + .build(); + + LocalPaymentApi sut = new LocalPaymentApi(braintreeClient, analyticsParamRepository, merchantRepository); - LocalPaymentApi sut = new LocalPaymentApi(braintreeClient, analyticsParamRepository); String webUrl = "sample-scheme://local-payment-success?paymentToken=successTokenId"; sut.tokenize( - "local-merchant-account-id", webUrl, "sample-correlation-id", - localPaymentInternalTokenizeCallback + "local-merchant-account-id", webUrl, "sample-correlation-id", + localPaymentInternalTokenizeCallback ); ArgumentCaptor captor = ArgumentCaptor.forClass(LocalPaymentNonce.class); verify(localPaymentInternalTokenizeCallback).onResult( - captor.capture(), - (Exception) isNull() + captor.capture(), + (Exception) isNull() ); LocalPaymentNonce result = captor.getValue(); diff --git a/LocalPayment/src/test/java/com/braintreepayments/api/localpayment/LocalPaymentClientUnitTest.java b/LocalPayment/src/test/java/com/braintreepayments/api/localpayment/LocalPaymentClientUnitTest.java index 8ca95359fd..22f8b84217 100644 --- a/LocalPayment/src/test/java/com/braintreepayments/api/localpayment/LocalPaymentClientUnitTest.java +++ b/LocalPayment/src/test/java/com/braintreepayments/api/localpayment/LocalPaymentClientUnitTest.java @@ -476,7 +476,6 @@ public void tokenize_whenPostFailure_notifiesCallbackOfErrorAlongWithAnalyticsEv BraintreeClient braintreeClient = new MockBraintreeClientBuilder() .configuration(payPalEnabledConfig) .sendPOSTErrorResponse(postError) - .integration(IntegrationType.CUSTOM) .build(); LocalPaymentApi localPaymentApi = new MockLocalPaymentApiBuilder() @@ -522,7 +521,6 @@ public void tokenize_whenResultOKAndSuccessful_tokenizesWithLocalPaymentApi() BraintreeClient braintreeClient = new MockBraintreeClientBuilder() .configuration(payPalEnabledConfig) - .integration(IntegrationType.CUSTOM) .build(); when(dataCollector.getClientMetadataId(activity, payPalEnabledConfig, false)).thenReturn( "sample-correlation-id"); @@ -553,7 +551,6 @@ public void tokenize_whenResultOKAndTokenizationSucceeds_sendsResultToCallback() BraintreeClient braintreeClient = new MockBraintreeClientBuilder() .configuration(payPalEnabledConfig) - .integration(IntegrationType.CUSTOM) .build(); when(dataCollector.getClientMetadataId(any(Context.class), same(payPalEnabledConfig), eq(false))).thenReturn("client-metadata-id"); @@ -635,7 +632,6 @@ public void tokenize_whenResultOK_onConfigurationError_returnsError() Exception configError = new Exception("config error"); BraintreeClient braintreeClient = new MockBraintreeClientBuilder() .configurationError(configError) - .integration(IntegrationType.CUSTOM) .build(); when(dataCollector.getClientMetadataId(activity, payPalEnabledConfig, true)).thenReturn( "sample-correlation-id"); @@ -702,7 +698,6 @@ public void onBrowserSwitchResult_sends_the_correct_value_of_hasUserLocationCons when(browserSwitchResult.getReturnUrl()).thenReturn(Uri.parse(webUrl)); BraintreeClient braintreeClient = new MockBraintreeClientBuilder() .configuration(payPalEnabledConfig) - .integration(IntegrationType.CUSTOM) .build(); when(dataCollector.getClientMetadataId(any(Context.class), same(payPalEnabledConfig), anyBoolean())).thenReturn("client-metadata-id"); diff --git a/PayPal/src/main/java/com/braintreepayments/api/paypal/PayPalClient.kt b/PayPal/src/main/java/com/braintreepayments/api/paypal/PayPalClient.kt index 21181f35fa..ccdfbd46ad 100644 --- a/PayPal/src/main/java/com/braintreepayments/api/paypal/PayPalClient.kt +++ b/PayPal/src/main/java/com/braintreepayments/api/paypal/PayPalClient.kt @@ -10,6 +10,7 @@ import com.braintreepayments.api.core.BraintreeException import com.braintreepayments.api.core.BraintreeRequestCodes import com.braintreepayments.api.core.Configuration import com.braintreepayments.api.core.LinkType +import com.braintreepayments.api.core.MerchantRepository import com.braintreepayments.api.core.UserCanceledException import com.braintreepayments.api.paypal.PayPalPaymentIntent.Companion.fromString import com.braintreepayments.api.sharedutils.Json @@ -22,6 +23,7 @@ import org.json.JSONObject class PayPalClient internal constructor( private val braintreeClient: BraintreeClient, private val internalPayPalClient: PayPalInternalClient = PayPalInternalClient(braintreeClient), + private val merchantRepository: MerchantRepository = MerchantRepository.instance, ) { /** @@ -150,7 +152,7 @@ class PayPalClient internal constructor( return BrowserSwitchOptions() .requestCode(BraintreeRequestCodes.PAYPAL.code) - .appLinkUri(braintreeClient.appLinkReturnUri) + .appLinkUri(merchantRepository.appLinkReturnUri) .url(Uri.parse(paymentAuthRequest.approvalUrl)) .launchAsNewTask(braintreeClient.launchesBrowserSwitchAsNewTask()) .metadata(metadata) diff --git a/PayPal/src/main/java/com/braintreepayments/api/paypal/PayPalInternalClient.kt b/PayPal/src/main/java/com/braintreepayments/api/paypal/PayPalInternalClient.kt index 55601fceff..cfb9427d40 100644 --- a/PayPal/src/main/java/com/braintreepayments/api/paypal/PayPalInternalClient.kt +++ b/PayPal/src/main/java/com/braintreepayments/api/paypal/PayPalInternalClient.kt @@ -7,6 +7,7 @@ import com.braintreepayments.api.core.BraintreeClient import com.braintreepayments.api.core.BraintreeException import com.braintreepayments.api.core.Configuration import com.braintreepayments.api.core.DeviceInspector +import com.braintreepayments.api.core.MerchantRepository import com.braintreepayments.api.datacollector.DataCollector import com.braintreepayments.api.datacollector.DataCollectorInternalRequest import com.braintreepayments.api.paypal.PayPalPaymentResource.Companion.fromJson @@ -17,11 +18,12 @@ internal class PayPalInternalClient( private val braintreeClient: BraintreeClient, private val dataCollector: DataCollector = DataCollector(braintreeClient), private val apiClient: ApiClient = ApiClient(braintreeClient), - private val deviceInspector: DeviceInspector = DeviceInspector() + private val deviceInspector: DeviceInspector = DeviceInspector(), + private val merchantRepository: MerchantRepository = MerchantRepository.instance, ) { - private val cancelUrl = "${braintreeClient.appLinkReturnUri}://onetouch/v1/cancel" - private val successUrl = "${braintreeClient.appLinkReturnUri}://onetouch/v1/success" - private val appLink = braintreeClient.appLinkReturnUri?.toString() + private val cancelUrl = "${merchantRepository.appLinkReturnUri}://onetouch/v1/cancel" + private val successUrl = "${merchantRepository.appLinkReturnUri}://onetouch/v1/success" + private val appLink = merchantRepository.appLinkReturnUri?.toString() fun sendRequest( context: Context, @@ -50,7 +52,7 @@ internal class PayPalInternalClient( val requestBody = payPalRequest.createRequestBody( configuration = configuration, - authorization = braintreeClient.authorization, + authorization = merchantRepository.authorization, successUrl = successUrl, cancelUrl = cancelUrl, appLink = appLinkReturn @@ -155,7 +157,7 @@ internal class PayPalInternalClient( fun isAppSwitchEnabled(payPalRequest: PayPalRequest): Boolean { return (payPalRequest is PayPalVaultRequest) && - payPalRequest.enablePayPalAppSwitch + payPalRequest.enablePayPalAppSwitch } fun isPayPalInstalled(context: Context): Boolean { diff --git a/PayPal/src/test/java/com/braintreepayments/api/paypal/PayPalClientUnitTest.java b/PayPal/src/test/java/com/braintreepayments/api/paypal/PayPalClientUnitTest.java index de3084e69b..ea68b5b6ed 100644 --- a/PayPal/src/test/java/com/braintreepayments/api/paypal/PayPalClientUnitTest.java +++ b/PayPal/src/test/java/com/braintreepayments/api/paypal/PayPalClientUnitTest.java @@ -19,6 +19,7 @@ import com.braintreepayments.api.core.BraintreeClient; import com.braintreepayments.api.core.BraintreeRequestCodes; import com.braintreepayments.api.core.Configuration; +import com.braintreepayments.api.core.MerchantRepository; import com.braintreepayments.api.testutils.Fixtures; import com.braintreepayments.api.testutils.MockBraintreeClientBuilder; @@ -41,6 +42,8 @@ public class PayPalClientUnitTest { private PayPalTokenizeCallback payPalTokenizeCallback; private PayPalPaymentAuthCallback paymentAuthCallback; + private MerchantRepository merchantRepository; + @Before public void beforeEach() throws JSONException { activity = mock(FragmentActivity.class); @@ -50,6 +53,8 @@ public void beforeEach() throws JSONException { payPalTokenizeCallback = mock(PayPalTokenizeCallback.class); paymentAuthCallback = mock(PayPalPaymentAuthCallback.class); + + merchantRepository = mock(MerchantRepository.class); } @Test @@ -72,7 +77,7 @@ public void createPaymentAuthRequest_callsBackPayPalResponse_sendsStartedAnalyti BraintreeClient braintreeClient = new MockBraintreeClientBuilder().configuration(payPalEnabledConfig).build(); - PayPalClient sut = new PayPalClient(braintreeClient, payPalInternalClient); + PayPalClient sut = new PayPalClient(braintreeClient, payPalInternalClient, merchantRepository); sut.createPaymentAuthRequest(activity, payPalVaultRequest, paymentAuthCallback); ArgumentCaptor captor = @@ -126,7 +131,7 @@ public void createPaymentAuthRequest_whenLaunchesBrowserSwitchAsNewTaskEnabled_s new MockBraintreeClientBuilder().configuration(payPalEnabledConfig) .launchesBrowserSwitchAsNewTask(true).build(); - PayPalClient sut = new PayPalClient(braintreeClient, payPalInternalClient); + PayPalClient sut = new PayPalClient(braintreeClient, payPalInternalClient, merchantRepository); sut.createPaymentAuthRequest(activity, payPalVaultRequest, paymentAuthCallback); ArgumentCaptor captor = @@ -156,12 +161,12 @@ public void createPaymentAuthRequest_setsAppLinkReturnUrl() { new MockPayPalInternalClientBuilder().sendRequestSuccess(paymentAuthRequest) .build(); - BraintreeClient braintreeClient = - new MockBraintreeClientBuilder().configuration(payPalEnabledConfig) - .appLinkReturnUri(Uri.parse("www.example.com")) - .build(); + when(merchantRepository.getAppLinkReturnUri()).thenReturn(Uri.parse("www.example.com")); - PayPalClient sut = new PayPalClient(braintreeClient, payPalInternalClient); + BraintreeClient braintreeClient = new MockBraintreeClientBuilder().configuration(payPalEnabledConfig) + .build(); + + PayPalClient sut = new PayPalClient(braintreeClient, payPalInternalClient, merchantRepository); sut.createPaymentAuthRequest(activity, payPalVaultRequest, paymentAuthCallback); ArgumentCaptor captor = @@ -170,7 +175,7 @@ public void createPaymentAuthRequest_setsAppLinkReturnUrl() { PayPalPaymentAuthRequest request = captor.getValue(); assertTrue(request instanceof PayPalPaymentAuthRequest.ReadyToLaunch); - assertEquals(braintreeClient.getAppLinkReturnUri(), + assertEquals(merchantRepository.getAppLinkReturnUri(), ((PayPalPaymentAuthRequest.ReadyToLaunch) request).getRequestParams().getBrowserSwitchOptions().getAppLinkUri()); } @@ -181,7 +186,7 @@ public void createPaymentAuthRequest_whenPayPalNotEnabled_returnsError() { BraintreeClient braintreeClient = new MockBraintreeClientBuilder().configuration(payPalDisabledConfig).build(); - PayPalClient sut = new PayPalClient(braintreeClient, payPalInternalClient); + PayPalClient sut = new PayPalClient(braintreeClient, payPalInternalClient, merchantRepository); sut.createPaymentAuthRequest(activity, new PayPalCheckoutRequest("1.00", true), paymentAuthCallback); @@ -210,7 +215,7 @@ public void createPaymentAuthRequest_whenCheckoutRequest_whenConfigError_forward .configurationError(authError) .build(); - PayPalClient sut = new PayPalClient(braintreeClient, payPalInternalClient); + PayPalClient sut = new PayPalClient(braintreeClient, payPalInternalClient, merchantRepository); sut.createPaymentAuthRequest(activity, new PayPalCheckoutRequest("1.00", true), paymentAuthCallback); ArgumentCaptor captor = @@ -235,7 +240,7 @@ public void requestBillingAgreement_whenConfigError_forwardsErrorToListener() { .configurationError(authError) .build(); - PayPalClient sut = new PayPalClient(braintreeClient, payPalInternalClient); + PayPalClient sut = new PayPalClient(braintreeClient, payPalInternalClient, merchantRepository); sut.createPaymentAuthRequest(activity, new PayPalVaultRequest(true), paymentAuthCallback); ArgumentCaptor captor = @@ -261,7 +266,7 @@ public void createPaymentAuthRequest_whenVaultRequest_sendsPayPalRequestViaInter PayPalVaultRequest payPalRequest = new PayPalVaultRequest(true); - PayPalClient sut = new PayPalClient(braintreeClient, payPalInternalClient); + PayPalClient sut = new PayPalClient(braintreeClient, payPalInternalClient, merchantRepository); sut.createPaymentAuthRequest(activity, payPalRequest, paymentAuthCallback); verify(payPalInternalClient).sendRequest(same(activity), same(payPalRequest), @@ -277,7 +282,7 @@ public void createPaymentAuthRequest_whenCheckoutRequest_sendsPayPalRequestViaIn PayPalCheckoutRequest payPalRequest = new PayPalCheckoutRequest("1.00", true); - PayPalClient sut = new PayPalClient(braintreeClient, payPalInternalClient); + PayPalClient sut = new PayPalClient(braintreeClient, payPalInternalClient, merchantRepository); sut.createPaymentAuthRequest(activity, payPalRequest, paymentAuthCallback); verify(payPalInternalClient).sendRequest(same(activity), same(payPalRequest), @@ -292,34 +297,34 @@ public void createPaymentAuthRequest_whenVaultRequest_sendsAppSwitchStartedEvent payPalVaultRequest.setMerchantAccountId("sample-merchant-account-id"); PayPalPaymentAuthRequestParams paymentAuthRequest = new PayPalPaymentAuthRequestParams( - payPalVaultRequest, - null, - "https://example.com/approval/url", - "sample-client-metadata-id", - null, - "https://example.com/success/url" + payPalVaultRequest, + null, + "https://example.com/approval/url", + "sample-client-metadata-id", + null, + "https://example.com/success/url" ); PayPalInternalClient payPalInternalClient = - new MockPayPalInternalClientBuilder().sendRequestSuccess(paymentAuthRequest) - .build(); + new MockPayPalInternalClientBuilder().sendRequestSuccess(paymentAuthRequest) + .build(); when(payPalInternalClient.isPayPalInstalled(activity)).thenReturn(true); when(payPalInternalClient.isAppSwitchEnabled(payPalVaultRequest)).thenReturn(true); BraintreeClient braintreeClient = - new MockBraintreeClientBuilder().configuration(payPalEnabledConfig).build(); + new MockBraintreeClientBuilder().configuration(payPalEnabledConfig).build(); - PayPalClient sut = new PayPalClient(braintreeClient, payPalInternalClient); + PayPalClient sut = new PayPalClient(braintreeClient, payPalInternalClient, merchantRepository); sut.createPaymentAuthRequest(activity, payPalVaultRequest, paymentAuthCallback); ArgumentCaptor captor = - ArgumentCaptor.forClass(PayPalPaymentAuthRequest.class); + ArgumentCaptor.forClass(PayPalPaymentAuthRequest.class); verify(paymentAuthCallback).onPayPalPaymentAuthRequest(captor.capture()); PayPalPaymentAuthRequest request = captor.getValue(); assertTrue(request instanceof PayPalPaymentAuthRequest.ReadyToLaunch); PayPalPaymentAuthRequestParams paymentAuthRequestCaptured = - ((PayPalPaymentAuthRequest.ReadyToLaunch) request).getRequestParams(); + ((PayPalPaymentAuthRequest.ReadyToLaunch) request).getRequestParams(); BrowserSwitchOptions browserSwitchOptions = paymentAuthRequestCaptured.getBrowserSwitchOptions(); assertEquals(BraintreeRequestCodes.PAYPAL.getCode(), browserSwitchOptions.getRequestCode()); @@ -354,7 +359,7 @@ public void tokenize_withBillingAgreement_tokenizesResponseOnSuccess() throws JS PayPalPaymentAuthResult.Success payPalPaymentAuthResult = new PayPalPaymentAuthResult.Success( browserSwitchResult); BraintreeClient braintreeClient = new MockBraintreeClientBuilder().build(); - PayPalClient sut = new PayPalClient(braintreeClient, payPalInternalClient); + PayPalClient sut = new PayPalClient(braintreeClient, payPalInternalClient, merchantRepository); sut.tokenize(payPalPaymentAuthResult, payPalTokenizeCallback); @@ -396,9 +401,9 @@ public void tokenize_withOneTimePayment_tokenizesResponseOnSuccess() throws JSON when(browserSwitchResult.getReturnUrl()).thenReturn(uri); PayPalPaymentAuthResult.Success payPalPaymentAuthResult = new PayPalPaymentAuthResult.Success( - browserSwitchResult); + browserSwitchResult); BraintreeClient braintreeClient = new MockBraintreeClientBuilder().build(); - PayPalClient sut = new PayPalClient(braintreeClient, payPalInternalClient); + PayPalClient sut = new PayPalClient(braintreeClient, payPalInternalClient, merchantRepository); sut.tokenize(payPalPaymentAuthResult, payPalTokenizeCallback); @@ -443,7 +448,7 @@ public void tokenize_whenCancelUriReceived_notifiesCancellationAndSendsAnalytics PayPalPaymentAuthResult.Success payPalPaymentAuthResult = new PayPalPaymentAuthResult.Success( browserSwitchResult); BraintreeClient braintreeClient = new MockBraintreeClientBuilder().build(); - PayPalClient sut = new PayPalClient(braintreeClient, payPalInternalClient); + PayPalClient sut = new PayPalClient(braintreeClient, payPalInternalClient, merchantRepository); sut.tokenize(payPalPaymentAuthResult, payPalTokenizeCallback); @@ -481,9 +486,9 @@ public void tokenize_whenPayPalInternalClientTokenizeResult_callsBackResult() when(browserSwitchResult.getReturnUrl()).thenReturn(uri); PayPalPaymentAuthResult.Success payPalPaymentAuthResult = new PayPalPaymentAuthResult.Success( - browserSwitchResult); + browserSwitchResult); BraintreeClient braintreeClient = new MockBraintreeClientBuilder().build(); - PayPalClient sut = new PayPalClient(braintreeClient, payPalInternalClient); + PayPalClient sut = new PayPalClient(braintreeClient, payPalInternalClient, merchantRepository); sut.tokenize(payPalPaymentAuthResult, payPalTokenizeCallback); @@ -502,30 +507,30 @@ public void tokenize_whenPayPalInternalClientTokenizeResult_callsBackResult() @Test public void tokenize_whenPayPalInternalClientTokenizeResult_sendsAppSwitchSucceededEvents() - throws JSONException { + throws JSONException { PayPalAccountNonce payPalAccountNonce = mock(PayPalAccountNonce.class); PayPalInternalClient payPalInternalClient = - new MockPayPalInternalClientBuilder().tokenizeSuccess(payPalAccountNonce).build(); + new MockPayPalInternalClientBuilder().tokenizeSuccess(payPalAccountNonce).build(); String approvalUrl = - "sample-scheme://onetouch/v1/success?PayerID=HERMES-SANDBOX-PAYER-ID&paymentId=HERMES-SANDBOX-PAYMENT-ID&token=EC-HERMES-SANDBOX-EC-TOKEN&switch_initiated_time=17166111926211"; + "sample-scheme://onetouch/v1/success?PayerID=HERMES-SANDBOX-PAYER-ID&paymentId=HERMES-SANDBOX-PAYMENT-ID&token=EC-HERMES-SANDBOX-EC-TOKEN&switch_initiated_time=17166111926211"; BrowserSwitchFinalResult.Success browserSwitchResult = mock(BrowserSwitchFinalResult.Success.class); when(browserSwitchResult.getRequestMetadata()).thenReturn( - new JSONObject().put("client-metadata-id", "sample-client-metadata-id") - .put("merchant-account-id", "sample-merchant-account-id") - .put("intent", "authorize").put("approval-url", approvalUrl) - .put("success-url", "https://example.com/success") - .put("payment-type", "single-payment")); + new JSONObject().put("client-metadata-id", "sample-client-metadata-id") + .put("merchant-account-id", "sample-merchant-account-id") + .put("intent", "authorize").put("approval-url", approvalUrl) + .put("success-url", "https://example.com/success") + .put("payment-type", "single-payment")); Uri uri = Uri.parse(approvalUrl); when(browserSwitchResult.getReturnUrl()).thenReturn(uri); PayPalPaymentAuthResult.Success payPalPaymentAuthResult = new PayPalPaymentAuthResult.Success( - browserSwitchResult); + browserSwitchResult); BraintreeClient braintreeClient = new MockBraintreeClientBuilder().build(); - PayPalClient sut = new PayPalClient(braintreeClient, payPalInternalClient); + PayPalClient sut = new PayPalClient(braintreeClient, payPalInternalClient, merchantRepository); sut.tokenize(payPalPaymentAuthResult, payPalTokenizeCallback); @@ -552,19 +557,19 @@ public void tokenize_whenPayPalNotEnabled_sendsAppSwitchFailedEvents() throws JS BrowserSwitchFinalResult.Success browserSwitchResult = mock(BrowserSwitchFinalResult.Success.class); when(browserSwitchResult.getRequestMetadata()).thenReturn( - new JSONObject().put("client-metadata-id", "sample-client-metadata-id") - .put("merchant-account-id", "sample-merchant-account-id") - .put("intent", "authorize").put("approval-url", "https://some-scheme/onetouch/v1/cancel?token=SOME-BA&switch_initiated_time=17166111926211") - .put("success-url", "https://example.com/cancel") - .put("payment-type", "single-payment")); + new JSONObject().put("client-metadata-id", "sample-client-metadata-id") + .put("merchant-account-id", "sample-merchant-account-id") + .put("intent", "authorize").put("approval-url", "https://some-scheme/onetouch/v1/cancel?token=SOME-BA&switch_initiated_time=17166111926211") + .put("success-url", "https://example.com/cancel") + .put("payment-type", "single-payment")); Uri uri = Uri.parse(approvalUrl); when(browserSwitchResult.getReturnUrl()).thenReturn(uri); PayPalPaymentAuthResult.Success payPalPaymentAuthResult = new PayPalPaymentAuthResult.Success( - browserSwitchResult); + browserSwitchResult); BraintreeClient braintreeClient = new MockBraintreeClientBuilder().build(); - PayPalClient sut = new PayPalClient(braintreeClient, payPalInternalClient); + PayPalClient sut = new PayPalClient(braintreeClient, payPalInternalClient, merchantRepository); sut.tokenize(payPalPaymentAuthResult, payPalTokenizeCallback); @@ -576,7 +581,7 @@ public void tokenize_whenPayPalNotEnabled_sendsAppSwitchFailedEvents() throws JS @Test public void tokenize_whenCancelUriReceived_sendsAppSwitchCanceledEvents() - throws JSONException { + throws JSONException { PayPalInternalClient payPalInternalClient = new MockPayPalInternalClientBuilder().build(); String approvalUrl = "https://some-scheme/onetouch/v1/cancel?switch_initiated_time=17166111926211"; @@ -584,19 +589,19 @@ public void tokenize_whenCancelUriReceived_sendsAppSwitchCanceledEvents() BrowserSwitchFinalResult.Success browserSwitchResult = mock(BrowserSwitchFinalResult.Success.class); when(browserSwitchResult.getRequestMetadata()).thenReturn( - new JSONObject().put("client-metadata-id", "sample-client-metadata-id") - .put("merchant-account-id", "sample-merchant-account-id") - .put("intent", "authorize").put("approval-url", approvalUrl) - .put("success-url", "https://example.com/success") - .put("payment-type", "single-payment")); + new JSONObject().put("client-metadata-id", "sample-client-metadata-id") + .put("merchant-account-id", "sample-merchant-account-id") + .put("intent", "authorize").put("approval-url", approvalUrl) + .put("success-url", "https://example.com/success") + .put("payment-type", "single-payment")); Uri uri = Uri.parse(approvalUrl); when(browserSwitchResult.getReturnUrl()).thenReturn(uri); PayPalPaymentAuthResult.Success payPalPaymentAuthResult = new PayPalPaymentAuthResult.Success( - browserSwitchResult); + browserSwitchResult); BraintreeClient braintreeClient = new MockBraintreeClientBuilder().build(); - PayPalClient sut = new PayPalClient(braintreeClient, payPalInternalClient); + PayPalClient sut = new PayPalClient(braintreeClient, payPalInternalClient, merchantRepository); sut.tokenize(payPalPaymentAuthResult, payPalTokenizeCallback); diff --git a/PayPal/src/test/java/com/braintreepayments/api/paypal/PayPalInternalClientUnitTest.java b/PayPal/src/test/java/com/braintreepayments/api/paypal/PayPalInternalClientUnitTest.java index 8a4214ced1..d743584131 100644 --- a/PayPal/src/test/java/com/braintreepayments/api/paypal/PayPalInternalClientUnitTest.java +++ b/PayPal/src/test/java/com/braintreepayments/api/paypal/PayPalInternalClientUnitTest.java @@ -23,6 +23,7 @@ import com.braintreepayments.api.core.ClientToken; import com.braintreepayments.api.core.Configuration; import com.braintreepayments.api.core.DeviceInspector; +import com.braintreepayments.api.core.MerchantRepository; import com.braintreepayments.api.core.PostalAddress; import com.braintreepayments.api.core.TokenizationKey; import com.braintreepayments.api.core.TokenizeCallback; @@ -61,6 +62,8 @@ public class PayPalInternalClientUnitTest { PayPalInternalClientCallback payPalInternalClientCallback; + private MerchantRepository merchantRepository = mock(MerchantRepository.class); + @Before public void beforeEach() throws JSONException { context = mock(Context.class); @@ -77,13 +80,20 @@ public void beforeEach() throws JSONException { @Test public void sendRequest_withPayPalVaultRequest_sendsAllParameters() throws JSONException { BraintreeClient braintreeClient = new MockBraintreeClientBuilder() - .configuration(configuration) - .authorizationSuccess(clientToken) - .appLinkReturnUri(Uri.parse("https://example.com")) - .build(); + .configuration(configuration) + .build(); when(clientToken.getBearer()).thenReturn("client-token-bearer"); - PayPalInternalClient sut = new PayPalInternalClient(braintreeClient, dataCollector, apiClient, deviceInspector); + when(merchantRepository.getAuthorization()).thenReturn(clientToken); + when(merchantRepository.getAppLinkReturnUri()).thenReturn(Uri.parse("https://example.com")); + + PayPalInternalClient sut = new PayPalInternalClient( + braintreeClient, + dataCollector, + apiClient, + deviceInspector, + merchantRepository + ); PostalAddress shippingAddressOverride = new PostalAddress(); shippingAddressOverride.setRecipientName("Brianna Tree"); @@ -119,26 +129,26 @@ public void sendRequest_withPayPalVaultRequest_sendsAllParameters() throws JSONE JSONObject actual = new JSONObject(result); JSONObject expected = new JSONObject() - .put("authorization_fingerprint", "client-token-bearer") - .put("return_url", "https://example.com://onetouch/v1/success") - .put("cancel_url", "https://example.com://onetouch/v1/cancel") - .put("offer_paypal_credit", true) - .put("description", "Billing Agreement Description") - .put("experience_profile", new JSONObject() - .put("no_shipping", false) - .put("landing_page_type", "billing") - .put("brand_name", "sample-display-name") - .put("locale_code", "US") - .put("address_override", false)) - .put("shipping_address", new JSONObject() - .put("line1", "123 Fake St.") - .put("line2", "Apt. v.0") - .put("city", "Oakland") - .put("state", "CA") - .put("postal_code", "12345") - .put("country_code", "US") - .put("recipient_name", "Brianna Tree")) - .put("merchant_account_id", "sample-merchant-account-id"); + .put("authorization_fingerprint", "client-token-bearer") + .put("return_url", "https://example.com://onetouch/v1/success") + .put("cancel_url", "https://example.com://onetouch/v1/cancel") + .put("offer_paypal_credit", true) + .put("description", "Billing Agreement Description") + .put("experience_profile", new JSONObject() + .put("no_shipping", false) + .put("landing_page_type", "billing") + .put("brand_name", "sample-display-name") + .put("locale_code", "US") + .put("address_override", false)) + .put("shipping_address", new JSONObject() + .put("line1", "123 Fake St.") + .put("line2", "Apt. v.0") + .put("city", "Oakland") + .put("state", "CA") + .put("postal_code", "12345") + .put("country_code", "US") + .put("recipient_name", "Brianna Tree")) + .put("merchant_account_id", "sample-merchant-account-id"); JSONAssert.assertEquals(expected, actual, true); } @@ -146,14 +156,20 @@ public void sendRequest_withPayPalVaultRequest_sendsAllParameters() throws JSONE @Test public void sendRequest_withPayPalCheckoutRequest_sendsAllParameters() throws JSONException { BraintreeClient braintreeClient = new MockBraintreeClientBuilder() - .configuration(configuration) - .authorizationSuccess(clientToken) - .appLinkReturnUri(Uri.parse("https://example.com")) - .build(); + .configuration(configuration) + .build(); when(clientToken.getBearer()).thenReturn("client-token-bearer"); - PayPalInternalClient sut = new PayPalInternalClient(braintreeClient, dataCollector, apiClient, deviceInspector); + when(merchantRepository.getAuthorization()).thenReturn(clientToken); + when(merchantRepository.getAppLinkReturnUri()).thenReturn(Uri.parse("https://example.com")); + PayPalInternalClient sut = new PayPalInternalClient( + braintreeClient, + dataCollector, + apiClient, + deviceInspector, + merchantRepository + ); PostalAddress shippingAddressOverride = new PostalAddress(); shippingAddressOverride.setRecipientName("Brianna Tree"); shippingAddressOverride.setStreetAddress("123 Fake St."); @@ -202,40 +218,40 @@ public void sendRequest_withPayPalCheckoutRequest_sendsAllParameters() throws JS JSONObject actual = new JSONObject(result); JSONObject expected = new JSONObject() - .put("amount", "1.00") - .put("currency_iso_code", "USD") - .put("intent", "authorize") - .put("authorization_fingerprint", "client-token-bearer") - .put("return_url", "https://example.com://onetouch/v1/success") - .put("cancel_url", "https://example.com://onetouch/v1/cancel") - .put("offer_pay_later", true) - .put("request_billing_agreement", true) - .put("billing_agreement_details", new JSONObject() - .put("description", "Billing Agreement Description")) - .put("line_items", new JSONArray() - .put(new JSONObject() - .put("kind", "debit") - .put("name", "Item 0") - .put("quantity", "1") - .put("unit_amount", "2") - .put("description", "A new item") - .put("product_code", "abc-123") - .put("unit_tax_amount", "1.50") - .put("url", "http://example.com"))) - .put("experience_profile", new JSONObject() - .put("no_shipping", false) - .put("landing_page_type", "login") - .put("brand_name", "sample-display-name") - .put("locale_code", "US") - .put("address_override", false)) - .put("line1", "123 Fake St.") - .put("line2", "Apt. v.0") - .put("city", "Oakland") - .put("state", "CA") - .put("postal_code", "12345") - .put("country_code", "US") - .put("recipient_name", "Brianna Tree") - .put("merchant_account_id", "sample-merchant-account-id"); + .put("amount", "1.00") + .put("currency_iso_code", "USD") + .put("intent", "authorize") + .put("authorization_fingerprint", "client-token-bearer") + .put("return_url", "https://example.com://onetouch/v1/success") + .put("cancel_url", "https://example.com://onetouch/v1/cancel") + .put("offer_pay_later", true) + .put("request_billing_agreement", true) + .put("billing_agreement_details", new JSONObject() + .put("description", "Billing Agreement Description")) + .put("line_items", new JSONArray() + .put(new JSONObject() + .put("kind", "debit") + .put("name", "Item 0") + .put("quantity", "1") + .put("unit_amount", "2") + .put("description", "A new item") + .put("product_code", "abc-123") + .put("unit_tax_amount", "1.50") + .put("url", "http://example.com"))) + .put("experience_profile", new JSONObject() + .put("no_shipping", false) + .put("landing_page_type", "login") + .put("brand_name", "sample-display-name") + .put("locale_code", "US") + .put("address_override", false)) + .put("line1", "123 Fake St.") + .put("line2", "Apt. v.0") + .put("city", "Oakland") + .put("state", "CA") + .put("postal_code", "12345") + .put("country_code", "US") + .put("recipient_name", "Brianna Tree") + .put("merchant_account_id", "sample-merchant-account-id"); JSONAssert.assertEquals(expected, actual, true); } @@ -243,12 +259,18 @@ public void sendRequest_withPayPalCheckoutRequest_sendsAllParameters() throws JS @Test public void sendRequest_withTokenizationKey_sendsClientKeyParam() throws JSONException { BraintreeClient braintreeClient = new MockBraintreeClientBuilder() - .configuration(configuration) - .authorizationSuccess(tokenizationKey) - .build(); + .configuration(configuration) + .build(); when(tokenizationKey.getBearer()).thenReturn("tokenization-key-bearer"); - - PayPalInternalClient sut = new PayPalInternalClient(braintreeClient, dataCollector, apiClient, deviceInspector); + when(merchantRepository.getAuthorization()).thenReturn(tokenizationKey); + + PayPalInternalClient sut = new PayPalInternalClient( + braintreeClient, + dataCollector, + apiClient, + deviceInspector, + merchantRepository + ); PayPalVaultRequest payPalRequest = new PayPalVaultRequest(true); sut.sendRequest(context, payPalRequest, payPalInternalClientCallback); @@ -270,13 +292,20 @@ public void sendRequest_withTokenizationKey_sendsClientKeyParam() throws JSONExc @Test public void sendRequest_withEmptyDisplayName_fallsBackToPayPalConfigurationDisplayName() - throws JSONException { + throws JSONException { BraintreeClient braintreeClient = new MockBraintreeClientBuilder() - .configuration(configuration) - .authorizationSuccess(tokenizationKey) - .build(); + .configuration(configuration) + .build(); - PayPalInternalClient sut = new PayPalInternalClient(braintreeClient, dataCollector, apiClient, deviceInspector); + when(merchantRepository.getAuthorization()).thenReturn(tokenizationKey); + + PayPalInternalClient sut = new PayPalInternalClient( + braintreeClient, + dataCollector, + apiClient, + deviceInspector, + merchantRepository + ); PayPalVaultRequest payPalRequest = new PayPalVaultRequest(false); payPalRequest.setDisplayName(""); @@ -294,17 +323,24 @@ public void sendRequest_withEmptyDisplayName_fallsBackToPayPalConfigurationDispl JSONObject actual = new JSONObject(result); assertEquals("paypal_merchant", - ((JSONObject) actual.get("experience_profile")).get("brand_name")); + ((JSONObject) actual.get("experience_profile")).get("brand_name")); } @Test public void sendRequest_withLocaleNotSpecified_omitsLocale() throws JSONException { BraintreeClient braintreeClient = new MockBraintreeClientBuilder() - .configuration(configuration) - .authorizationSuccess(tokenizationKey) - .build(); + .configuration(configuration) + .build(); - PayPalInternalClient sut = new PayPalInternalClient(braintreeClient, dataCollector, apiClient, deviceInspector); + when(merchantRepository.getAuthorization()).thenReturn(tokenizationKey); + + PayPalInternalClient sut = new PayPalInternalClient( + braintreeClient, + dataCollector, + apiClient, + deviceInspector, + merchantRepository + ); PayPalVaultRequest payPalRequest = new PayPalVaultRequest(true); payPalRequest.setLocaleCode(null); @@ -326,13 +362,20 @@ public void sendRequest_withLocaleNotSpecified_omitsLocale() throws JSONExceptio @Test public void sendRequest_withMerchantAccountIdNotSpecified_omitsMerchantAccountId() - throws JSONException { + throws JSONException { BraintreeClient braintreeClient = new MockBraintreeClientBuilder() - .configuration(configuration) - .authorizationSuccess(tokenizationKey) - .build(); + .configuration(configuration) + .build(); + + when(merchantRepository.getAuthorization()).thenReturn(tokenizationKey); - PayPalInternalClient sut = new PayPalInternalClient(braintreeClient, dataCollector, apiClient, deviceInspector); + PayPalInternalClient sut = new PayPalInternalClient( + braintreeClient, + dataCollector, + apiClient, + deviceInspector, + merchantRepository + ); PayPalVaultRequest payPalRequest = new PayPalVaultRequest(true); payPalRequest.setMerchantAccountId(null); @@ -354,13 +397,20 @@ public void sendRequest_withMerchantAccountIdNotSpecified_omitsMerchantAccountId @Test public void sendRequest_withShippingAddressOverrideNotSpecified_sendsAddressOverrideFalse() - throws JSONException { + throws JSONException { BraintreeClient braintreeClient = new MockBraintreeClientBuilder() - .configuration(configuration) - .authorizationSuccess(tokenizationKey) - .build(); + .configuration(configuration) + .build(); + + when(merchantRepository.getAuthorization()).thenReturn(tokenizationKey); - PayPalInternalClient sut = new PayPalInternalClient(braintreeClient, dataCollector, apiClient, deviceInspector); + PayPalInternalClient sut = new PayPalInternalClient( + braintreeClient, + dataCollector, + apiClient, + deviceInspector, + merchantRepository + ); PayPalVaultRequest payPalRequest = new PayPalVaultRequest(true); payPalRequest.setShippingAddressOverride(null); @@ -378,19 +428,25 @@ public void sendRequest_withShippingAddressOverrideNotSpecified_sendsAddressOver JSONObject actual = new JSONObject(result); assertEquals(false, - ((JSONObject) actual.get("experience_profile")).get("address_override")); + ((JSONObject) actual.get("experience_profile")).get("address_override")); } @Test public void sendRequest_withShippingAddressSpecified_sendsAddressOverrideBasedOnShippingAdressEditability() - throws JSONException { + throws JSONException { BraintreeClient braintreeClient = new MockBraintreeClientBuilder() - .configuration(configuration) - .authorizationSuccess(clientToken) - .build(); + .configuration(configuration) + .build(); when(clientToken.getBearer()).thenReturn("client-token-bearer"); - - PayPalInternalClient sut = new PayPalInternalClient(braintreeClient, dataCollector, apiClient, deviceInspector); + when(merchantRepository.getAuthorization()).thenReturn(clientToken); + + PayPalInternalClient sut = new PayPalInternalClient( + braintreeClient, + dataCollector, + apiClient, + deviceInspector, + merchantRepository + ); PayPalVaultRequest payPalRequest = new PayPalVaultRequest(true); payPalRequest.setShippingAddressEditable(false); @@ -414,13 +470,20 @@ public void sendRequest_withShippingAddressSpecified_sendsAddressOverrideBasedOn @Test public void sendRequest_withPayPalVaultRequest_omitsEmptyBillingAgreementDescription() - throws JSONException { + throws JSONException { BraintreeClient braintreeClient = new MockBraintreeClientBuilder() - .configuration(configuration) - .authorizationSuccess(tokenizationKey) - .build(); + .configuration(configuration) + .build(); - PayPalInternalClient sut = new PayPalInternalClient(braintreeClient, dataCollector, apiClient, deviceInspector); + when(merchantRepository.getAuthorization()).thenReturn(tokenizationKey); + + PayPalInternalClient sut = new PayPalInternalClient( + braintreeClient, + dataCollector, + apiClient, + deviceInspector, + merchantRepository + ); PayPalVaultRequest payPalRequest = new PayPalVaultRequest(true); payPalRequest.setBillingAgreementDescription(""); @@ -442,13 +505,20 @@ public void sendRequest_withPayPalVaultRequest_omitsEmptyBillingAgreementDescrip @Test public void sendRequest_withPayPalCheckoutRequest_fallsBackToPayPalConfigurationCurrencyCode() - throws JSONException { + throws JSONException { BraintreeClient braintreeClient = new MockBraintreeClientBuilder() - .configuration(Configuration.fromJson(Fixtures.CONFIGURATION_WITH_LIVE_PAYPAL_INR)) - .authorizationSuccess(tokenizationKey) - .build(); + .configuration(Configuration.fromJson(Fixtures.CONFIGURATION_WITH_LIVE_PAYPAL_INR)) + .build(); - PayPalInternalClient sut = new PayPalInternalClient(braintreeClient, dataCollector, apiClient, deviceInspector); + when(merchantRepository.getAuthorization()).thenReturn(tokenizationKey); + + PayPalInternalClient sut = new PayPalInternalClient( + braintreeClient, + dataCollector, + apiClient, + deviceInspector, + merchantRepository + ); PayPalCheckoutRequest payPalRequest = new PayPalCheckoutRequest("1.00", true); sut.sendRequest(context, payPalRequest, payPalInternalClientCallback); @@ -470,11 +540,18 @@ public void sendRequest_withPayPalCheckoutRequest_fallsBackToPayPalConfiguration @Test public void sendRequest_withPayPalCheckoutRequest_omitsEmptyLineItems() throws JSONException { BraintreeClient braintreeClient = new MockBraintreeClientBuilder() - .configuration(configuration) - .authorizationSuccess(tokenizationKey) - .build(); + .configuration(configuration) + .build(); + + when(merchantRepository.getAuthorization()).thenReturn(tokenizationKey); - PayPalInternalClient sut = new PayPalInternalClient(braintreeClient, dataCollector, apiClient, deviceInspector); + PayPalInternalClient sut = new PayPalInternalClient( + braintreeClient, + dataCollector, + apiClient, + deviceInspector, + merchantRepository + ); PayPalCheckoutRequest payPalRequest = new PayPalCheckoutRequest("1.00", true); payPalRequest.setLineItems(new ArrayList()); @@ -499,12 +576,19 @@ public void sendRequest_whenRiskCorrelationIdNotNull_setsClientMetadataIdToRiskC when(dataCollector.getClientMetadataId(same(context), any(), same(configuration))).thenReturn("sample-client-metadata-id"); BraintreeClient braintreeClient = new MockBraintreeClientBuilder() - .configuration(configuration) - .authorizationSuccess(clientToken) - .sendPOSTSuccessfulResponse(Fixtures.PAYPAL_HERMES_RESPONSE) - .build(); + .configuration(configuration) + .sendPOSTSuccessfulResponse(Fixtures.PAYPAL_HERMES_RESPONSE) + .build(); - PayPalInternalClient sut = new PayPalInternalClient(braintreeClient, dataCollector, apiClient, deviceInspector); + when(merchantRepository.getAuthorization()).thenReturn(clientToken); + + PayPalInternalClient sut = new PayPalInternalClient( + braintreeClient, + dataCollector, + apiClient, + deviceInspector, + merchantRepository + ); PayPalCheckoutRequest payPalRequest = new PayPalCheckoutRequest("1.00", true); payPalRequest.setRiskCorrelationId("risk-correlation-id"); @@ -512,7 +596,7 @@ public void sendRequest_whenRiskCorrelationIdNotNull_setsClientMetadataIdToRiskC sut.sendRequest(context, payPalRequest, payPalInternalClientCallback); ArgumentCaptor captor = ArgumentCaptor.forClass( - PayPalPaymentAuthRequestParams.class); + PayPalPaymentAuthRequestParams.class); verify(payPalInternalClientCallback).onResult(captor.capture(), isNull()); PayPalPaymentAuthRequestParams payPalPaymentAuthRequestParams = captor.getValue(); @@ -524,19 +608,26 @@ public void sendRequest_whenRiskCorrelationIdNull_setsClientMetadataIdFromPayPal when(dataCollector.getClientMetadataId(same(context), any(), any())).thenReturn("sample-client-metadata-id"); BraintreeClient braintreeClient = new MockBraintreeClientBuilder() - .configuration(configuration) - .authorizationSuccess(clientToken) - .sendPOSTSuccessfulResponse(Fixtures.PAYPAL_HERMES_RESPONSE) - .build(); + .configuration(configuration) + .sendPOSTSuccessfulResponse(Fixtures.PAYPAL_HERMES_RESPONSE) + .build(); + + when(merchantRepository.getAuthorization()).thenReturn(clientToken); - PayPalInternalClient sut = new PayPalInternalClient(braintreeClient, dataCollector, apiClient, deviceInspector); + PayPalInternalClient sut = new PayPalInternalClient( + braintreeClient, + dataCollector, + apiClient, + deviceInspector, + merchantRepository + ); PayPalCheckoutRequest payPalRequest = new PayPalCheckoutRequest("1.00", true); sut.sendRequest(context, payPalRequest, payPalInternalClientCallback); ArgumentCaptor captor = ArgumentCaptor.forClass( - PayPalPaymentAuthRequestParams.class); + PayPalPaymentAuthRequestParams.class); verify(payPalInternalClientCallback).onResult(captor.capture(), (Exception) isNull()); PayPalPaymentAuthRequestParams payPalPaymentAuthRequestParams = captor.getValue(); @@ -546,13 +637,20 @@ public void sendRequest_whenRiskCorrelationIdNull_setsClientMetadataIdFromPayPal @Test public void sendRequest_withPayPalCheckoutRequest_whenRequestBillingAgreementFalse_andBillingAgreementDescriptionSet_doesNotSettBillingAgreementDescription() - throws JSONException { + throws JSONException { BraintreeClient braintreeClient = new MockBraintreeClientBuilder() - .configuration(configuration) - .authorizationSuccess(tokenizationKey) - .build(); + .configuration(configuration) + .build(); - PayPalInternalClient sut = new PayPalInternalClient(braintreeClient, dataCollector, apiClient, deviceInspector); + when(merchantRepository.getAuthorization()).thenReturn(tokenizationKey); + + PayPalInternalClient sut = new PayPalInternalClient( + braintreeClient, + dataCollector, + apiClient, + deviceInspector, + merchantRepository + ); PayPalCheckoutRequest payPalRequest = new PayPalCheckoutRequest("1.00", true); payPalRequest.setShouldRequestBillingAgreement(false); @@ -579,13 +677,20 @@ public void sendRequest_withPayPalVaultRequest_callsBackPayPalResponseOnSuccess( when(dataCollector.getClientMetadataId(context, configuration, true)).thenReturn("sample-client-metadata-id"); BraintreeClient braintreeClient = new MockBraintreeClientBuilder() - .configuration(configuration) - .authorizationSuccess(clientToken) - .appLinkReturnUri(Uri.parse("https://example.com")) - .sendPOSTSuccessfulResponse(Fixtures.PAYPAL_HERMES_RESPONSE_WITH_BA_TOKEN_PARAM) - .build(); + .configuration(configuration) + .sendPOSTSuccessfulResponse(Fixtures.PAYPAL_HERMES_RESPONSE_WITH_BA_TOKEN_PARAM) + .build(); - PayPalInternalClient sut = new PayPalInternalClient(braintreeClient, dataCollector, apiClient, deviceInspector); + when(merchantRepository.getAuthorization()).thenReturn(clientToken); + when(merchantRepository.getAppLinkReturnUri()).thenReturn(Uri.parse("https://example.com")); + + PayPalInternalClient sut = new PayPalInternalClient( + braintreeClient, + dataCollector, + apiClient, + deviceInspector, + merchantRepository + ); PayPalVaultRequest payPalRequest = new PayPalVaultRequest(true); payPalRequest.setMerchantAccountId("sample-merchant-account-id"); @@ -594,11 +699,11 @@ public void sendRequest_withPayPalVaultRequest_callsBackPayPalResponseOnSuccess( sut.sendRequest(context, payPalRequest, payPalInternalClientCallback); ArgumentCaptor captor = ArgumentCaptor.forClass( - PayPalPaymentAuthRequestParams.class); + PayPalPaymentAuthRequestParams.class); verify(payPalInternalClientCallback).onResult(captor.capture(), (Exception) isNull()); String expectedUrl = - "https://checkout.paypal.com/one-touch-login-sandbox/index.html?ba_token=fake-ba-token&action=create_payment_resource&amount=1.00&authorization_fingerprint=63cc461306c35080ce674a3372bffe1580b4130c7fd33d33968aa76bb93cdd06%7Ccreated_at%3D2015-10-13T18%3A49%3A48.371382792%2B0000%26merchant_id%3Ddcpspy2brwdjr3qn%26public_key%3D9wwrzqk3vr3t4nc8&cancel_url=com.braintreepayments.api.test.braintree%3A%2F%2Fonetouch%2Fv1%2Fcancel&controller=client_api%2Fpaypal_hermes¤cy_iso_code=USD&experience_profile%5Baddress_override%5D=false&experience_profile%5Bno_shipping%5D=false&merchant_id=dcpspy2brwdjr3qn&return_url=com.braintreepayments.api.test.braintree%3A%2F%2Fonetouch%2Fv1%2Fsuccess&offer_paypal_credit=true&version=1"; + "https://checkout.paypal.com/one-touch-login-sandbox/index.html?ba_token=fake-ba-token&action=create_payment_resource&amount=1.00&authorization_fingerprint=63cc461306c35080ce674a3372bffe1580b4130c7fd33d33968aa76bb93cdd06%7Ccreated_at%3D2015-10-13T18%3A49%3A48.371382792%2B0000%26merchant_id%3Ddcpspy2brwdjr3qn%26public_key%3D9wwrzqk3vr3t4nc8&cancel_url=com.braintreepayments.api.test.braintree%3A%2F%2Fonetouch%2Fv1%2Fcancel&controller=client_api%2Fpaypal_hermes¤cy_iso_code=USD&experience_profile%5Baddress_override%5D=false&experience_profile%5Bno_shipping%5D=false&merchant_id=dcpspy2brwdjr3qn&return_url=com.braintreepayments.api.test.braintree%3A%2F%2Fonetouch%2Fv1%2Fsuccess&offer_paypal_credit=true&version=1"; PayPalPaymentAuthRequestParams payPalPaymentAuthRequestParams = captor.getValue(); assertTrue(payPalPaymentAuthRequestParams.isBillingAgreement()); assertEquals("sample-merchant-account-id", payPalPaymentAuthRequestParams.getMerchantAccountId()); @@ -611,13 +716,20 @@ public void sendRequest_withPayPalVaultRequest_callsBackPayPalResponseOnSuccess( @Test public void sendRequest_withPayPalVaultRequest_callsBackPayPalResponseOnSuccess_returnsPayPalURL() { BraintreeClient braintreeClient = new MockBraintreeClientBuilder() - .configuration(configuration) - .authorizationSuccess(clientToken) - .appLinkReturnUri(Uri.parse("https://example.com")) - .sendPOSTSuccessfulResponse(Fixtures.PAYPAL_HERMES_RESPONSE_WITH_PAYPAL_REDIRECT_URL) - .build(); + .configuration(configuration) + .sendPOSTSuccessfulResponse(Fixtures.PAYPAL_HERMES_RESPONSE_WITH_PAYPAL_REDIRECT_URL) + .build(); - PayPalInternalClient sut = new PayPalInternalClient(braintreeClient, dataCollector, apiClient, deviceInspector); + when(merchantRepository.getAuthorization()).thenReturn(clientToken); + when(merchantRepository.getAppLinkReturnUri()).thenReturn(Uri.parse("https://example.com")); + + PayPalInternalClient sut = new PayPalInternalClient( + braintreeClient, + dataCollector, + apiClient, + deviceInspector, + merchantRepository + ); PayPalVaultRequest payPalRequest = new PayPalVaultRequest(true); payPalRequest.setUserAuthenticationEmail("example@mail.com"); @@ -628,7 +740,7 @@ public void sendRequest_withPayPalVaultRequest_callsBackPayPalResponseOnSuccess_ sut.sendRequest(context, payPalRequest, payPalInternalClientCallback); ArgumentCaptor captor = ArgumentCaptor.forClass( - PayPalPaymentAuthRequestParams.class); + PayPalPaymentAuthRequestParams.class); verify(payPalInternalClientCallback).onResult(captor.capture(), (Exception) isNull()); PayPalPaymentAuthRequestParams payPalPaymentAuthRequestParams = captor.getValue(); @@ -646,20 +758,27 @@ public void sendRequest_withPayPalVaultRequest_callsBackPayPalResponseOnSuccess_ @Test public void sendRequest_withPayPalVaultRequest_callsBackPayPalResponseOnSuccess_returnsApprovalURL() { BraintreeClient braintreeClient = new MockBraintreeClientBuilder() - .configuration(configuration) - .authorizationSuccess(clientToken) - .appLinkReturnUri(Uri.parse("https://example.com")) - .sendPOSTSuccessfulResponse(Fixtures.PAYPAL_HERMES_RESPONSE_WITH_APPROVAL_URL) - .build(); + .configuration(configuration) + .sendPOSTSuccessfulResponse(Fixtures.PAYPAL_HERMES_RESPONSE_WITH_APPROVAL_URL) + .build(); + + when(merchantRepository.getAuthorization()).thenReturn(clientToken); + when(merchantRepository.getAppLinkReturnUri()).thenReturn(Uri.parse("https://example.com")); - PayPalInternalClient sut = new PayPalInternalClient(braintreeClient, dataCollector, apiClient, deviceInspector); + PayPalInternalClient sut = new PayPalInternalClient( + braintreeClient, + dataCollector, + apiClient, + deviceInspector, + merchantRepository + ); PayPalVaultRequest payPalRequest = new PayPalVaultRequest(true); sut.sendRequest(context, payPalRequest, payPalInternalClientCallback); ArgumentCaptor captor = ArgumentCaptor.forClass( - PayPalPaymentAuthRequestParams.class); + PayPalPaymentAuthRequestParams.class); verify(payPalInternalClientCallback).onResult(captor.capture(), (Exception) isNull()); String expectedUrl = "https://www.example.com/some?ba_token=fake-ba-token"; @@ -674,13 +793,20 @@ public void sendRequest_withPayPalCheckoutRequest_callsBackPayPalResponseOnSucce when(dataCollector.getClientMetadataId(context, configuration, true)).thenReturn("sample-client-metadata-id"); BraintreeClient braintreeClient = new MockBraintreeClientBuilder() - .configuration(configuration) - .authorizationSuccess(clientToken) - .sendPOSTSuccessfulResponse(Fixtures.PAYPAL_HERMES_RESPONSE_WITH_TOKEN_PARAM) - .appLinkReturnUri(Uri.parse("https://example.com")) - .build(); + .configuration(configuration) + .sendPOSTSuccessfulResponse(Fixtures.PAYPAL_HERMES_RESPONSE_WITH_TOKEN_PARAM) + .build(); + + when(merchantRepository.getAuthorization()).thenReturn(clientToken); + when(merchantRepository.getAppLinkReturnUri()).thenReturn(Uri.parse("https://example.com")); - PayPalInternalClient sut = new PayPalInternalClient(braintreeClient, dataCollector, apiClient, deviceInspector); + PayPalInternalClient sut = new PayPalInternalClient( + braintreeClient, + dataCollector, + apiClient, + deviceInspector, + merchantRepository + ); PayPalCheckoutRequest payPalRequest = new PayPalCheckoutRequest("1.00", true); payPalRequest.setIntent(PayPalPaymentIntent.AUTHORIZE); @@ -691,11 +817,11 @@ public void sendRequest_withPayPalCheckoutRequest_callsBackPayPalResponseOnSucce sut.sendRequest(context, payPalRequest, payPalInternalClientCallback); ArgumentCaptor captor = ArgumentCaptor.forClass( - PayPalPaymentAuthRequestParams.class); + PayPalPaymentAuthRequestParams.class); verify(payPalInternalClientCallback).onResult(captor.capture(), (Exception) isNull()); String expectedUrl = - "https://checkout.paypal.com/one-touch-login-sandbox/index.html?token=fake-token&action=create_payment_resource&amount=1.00&authorization_fingerprint=63cc461306c35080ce674a3372bffe1580b4130c7fd33d33968aa76bb93cdd06%7Ccreated_at%3D2015-10-13T18%3A49%3A48.371382792%2B0000%26merchant_id%3Ddcpspy2brwdjr3qn%26public_key%3D9wwrzqk3vr3t4nc8&cancel_url=com.braintreepayments.api.test.braintree%3A%2F%2Fonetouch%2Fv1%2Fcancel&controller=client_api%2Fpaypal_hermes¤cy_iso_code=USD&experience_profile%5Baddress_override%5D=false&experience_profile%5Bno_shipping%5D=false&merchant_id=dcpspy2brwdjr3qn&return_url=com.braintreepayments.api.test.braintree%3A%2F%2Fonetouch%2Fv1%2Fsuccess&offer_paypal_credit=true&version=1"; + "https://checkout.paypal.com/one-touch-login-sandbox/index.html?token=fake-token&action=create_payment_resource&amount=1.00&authorization_fingerprint=63cc461306c35080ce674a3372bffe1580b4130c7fd33d33968aa76bb93cdd06%7Ccreated_at%3D2015-10-13T18%3A49%3A48.371382792%2B0000%26merchant_id%3Ddcpspy2brwdjr3qn%26public_key%3D9wwrzqk3vr3t4nc8&cancel_url=com.braintreepayments.api.test.braintree%3A%2F%2Fonetouch%2Fv1%2Fcancel&controller=client_api%2Fpaypal_hermes¤cy_iso_code=USD&experience_profile%5Baddress_override%5D=false&experience_profile%5Bno_shipping%5D=false&merchant_id=dcpspy2brwdjr3qn&return_url=com.braintreepayments.api.test.braintree%3A%2F%2Fonetouch%2Fv1%2Fsuccess&offer_paypal_credit=true&version=1"; PayPalPaymentAuthRequestParams payPalPaymentAuthRequestParams = captor.getValue(); assertFalse(payPalPaymentAuthRequestParams.isBillingAgreement()); assertEquals(PayPalPaymentIntent.AUTHORIZE, payPalPaymentAuthRequestParams.getIntent()); @@ -710,12 +836,19 @@ public void sendRequest_withPayPalCheckoutRequest_callsBackPayPalResponseOnSucce public void sendRequest_propagatesHttpErrors() { Exception httpError = new Exception("http error"); BraintreeClient braintreeClient = new MockBraintreeClientBuilder() - .configuration(configuration) - .authorizationSuccess(clientToken) - .sendPOSTErrorResponse(httpError) - .build(); + .configuration(configuration) + .sendPOSTErrorResponse(httpError) + .build(); + + when(merchantRepository.getAuthorization()).thenReturn(clientToken); - PayPalInternalClient sut = new PayPalInternalClient(braintreeClient, dataCollector, apiClient, deviceInspector); + PayPalInternalClient sut = new PayPalInternalClient( + braintreeClient, + dataCollector, + apiClient, + deviceInspector, + merchantRepository + ); PayPalCheckoutRequest payPalRequest = new PayPalCheckoutRequest("1.00", true); sut.sendRequest(context, payPalRequest, payPalInternalClientCallback); @@ -726,29 +859,43 @@ public void sendRequest_propagatesHttpErrors() { @Test public void sendRequest_propagatesMalformedJSONResponseErrors() { BraintreeClient braintreeClient = new MockBraintreeClientBuilder() - .configuration(configuration) - .authorizationSuccess(clientToken) - .sendPOSTSuccessfulResponse("{bad:") - .build(); + .configuration(configuration) + .sendPOSTSuccessfulResponse("{bad:") + .build(); - PayPalInternalClient sut = new PayPalInternalClient(braintreeClient, dataCollector, apiClient, deviceInspector); + when(merchantRepository.getAuthorization()).thenReturn(clientToken); + + PayPalInternalClient sut = new PayPalInternalClient( + braintreeClient, + dataCollector, + apiClient, + deviceInspector, + merchantRepository + ); PayPalCheckoutRequest payPalRequest = new PayPalCheckoutRequest("1.00", true); sut.sendRequest(context, payPalRequest, payPalInternalClientCallback); verify(payPalInternalClientCallback).onResult((PayPalPaymentAuthRequestParams) isNull(), - any(JSONException.class)); + any(JSONException.class)); } @Test public void sendRequest_onConfigurationFailure_forwardsError() { Exception configurationError = new Exception("configuration error"); BraintreeClient braintreeClient = new MockBraintreeClientBuilder() - .authorizationSuccess(clientToken) - .configurationError(configurationError) - .build(); + .configurationError(configurationError) + .build(); - PayPalInternalClient sut = new PayPalInternalClient(braintreeClient, dataCollector, apiClient, deviceInspector); + when(merchantRepository.getAuthorization()).thenReturn(clientToken); + + PayPalInternalClient sut = new PayPalInternalClient( + braintreeClient, + dataCollector, + apiClient, + deviceInspector, + merchantRepository + ); PayPalCheckoutRequest payPalRequest = new PayPalCheckoutRequest("1.00", true); sut.sendRequest(context, payPalRequest, payPalInternalClientCallback); @@ -762,7 +909,13 @@ public void tokenize_tokenizesWithApiClient() { PayPalAccount payPalAccount = mock(PayPalAccount.class); PayPalInternalTokenizeCallback callback = mock(PayPalInternalTokenizeCallback.class); - PayPalInternalClient sut = new PayPalInternalClient(braintreeClient, dataCollector, apiClient, deviceInspector); + PayPalInternalClient sut = new PayPalInternalClient( + braintreeClient, + dataCollector, + apiClient, + deviceInspector, + merchantRepository + ); sut.tokenize(payPalAccount, callback); @@ -773,22 +926,28 @@ public void tokenize_tokenizesWithApiClient() { public void tokenize_onTokenizeResult_returnsAccountNonceToCallback() throws JSONException { BraintreeClient braintreeClient = new MockBraintreeClientBuilder().build(); ApiClient apiClient = new MockApiClientBuilder() - .tokenizeRESTSuccess( - new JSONObject(Fixtures.PAYMENT_METHODS_PAYPAL_ACCOUNT_RESPONSE)) - .build(); + .tokenizeRESTSuccess( + new JSONObject(Fixtures.PAYMENT_METHODS_PAYPAL_ACCOUNT_RESPONSE)) + .build(); PayPalAccount payPalAccount = mock(PayPalAccount.class); PayPalInternalTokenizeCallback callback = mock(PayPalInternalTokenizeCallback.class); - PayPalInternalClient sut = new PayPalInternalClient(braintreeClient, dataCollector, apiClient, deviceInspector); + PayPalInternalClient sut = new PayPalInternalClient( + braintreeClient, + dataCollector, + apiClient, + deviceInspector, + merchantRepository + ); sut.tokenize(payPalAccount, callback); ArgumentCaptor captor = - ArgumentCaptor.forClass(PayPalAccountNonce.class); + ArgumentCaptor.forClass(PayPalAccountNonce.class); verify(callback).onResult(captor.capture(), (Exception) isNull()); PayPalAccountNonce expectedNonce = PayPalAccountNonce.fromJSON( - new JSONObject(Fixtures.PAYMENT_METHODS_PAYPAL_ACCOUNT_RESPONSE)); + new JSONObject(Fixtures.PAYMENT_METHODS_PAYPAL_ACCOUNT_RESPONSE)); PayPalAccountNonce result = captor.getValue(); assertEquals(expectedNonce.getString(), result.getString()); } @@ -798,12 +957,18 @@ public void tokenize_onTokenizeError_returnsErrorToCallback() { BraintreeClient braintreeClient = new MockBraintreeClientBuilder().build(); Exception error = new Exception("error"); ApiClient apiClient = new MockApiClientBuilder() - .tokenizeRESTError(error) - .build(); + .tokenizeRESTError(error) + .build(); PayPalAccount payPalAccount = mock(PayPalAccount.class); PayPalInternalTokenizeCallback callback = mock(PayPalInternalTokenizeCallback.class); - PayPalInternalClient sut = new PayPalInternalClient(braintreeClient, dataCollector, apiClient, deviceInspector); + PayPalInternalClient sut = new PayPalInternalClient( + braintreeClient, + dataCollector, + apiClient, + deviceInspector, + merchantRepository + ); sut.tokenize(payPalAccount, callback); @@ -815,12 +980,19 @@ public void payPalDataCollector_passes_correct_arguments_to_getClientMetadataId( Configuration configuration = Configuration.fromJson(Fixtures.CONFIGURATION_WITH_LIVE_PAYPAL); BraintreeClient braintreeClient = new MockBraintreeClientBuilder() .configuration(configuration) - .authorizationSuccess(clientToken) .returnUrlScheme("sample-scheme") .sendPOSTSuccessfulResponse(Fixtures.PAYPAL_HERMES_RESPONSE) .build(); - PayPalInternalClient sut = new PayPalInternalClient(braintreeClient, dataCollector, apiClient, deviceInspector); + when(merchantRepository.getAuthorization()).thenReturn(clientToken); + + PayPalInternalClient sut = new PayPalInternalClient( + braintreeClient, + dataCollector, + apiClient, + deviceInspector, + merchantRepository + ); PayPalCheckoutRequest payPalRequest = new PayPalCheckoutRequest("1.00", true); payPalRequest.setIntent(PayPalPaymentIntent.AUTHORIZE); diff --git a/ShopperInsights/src/main/java/com/braintreepayments/api/shopperinsights/ShopperInsightsClient.kt b/ShopperInsights/src/main/java/com/braintreepayments/api/shopperinsights/ShopperInsightsClient.kt index becd62b804..2011056c21 100644 --- a/ShopperInsights/src/main/java/com/braintreepayments/api/shopperinsights/ShopperInsightsClient.kt +++ b/ShopperInsights/src/main/java/com/braintreepayments/api/shopperinsights/ShopperInsightsClient.kt @@ -6,6 +6,7 @@ import com.braintreepayments.api.core.AnalyticsParamRepository import com.braintreepayments.api.core.BraintreeClient import com.braintreepayments.api.core.BraintreeException import com.braintreepayments.api.core.ExperimentalBetaApi +import com.braintreepayments.api.core.MerchantRepository import com.braintreepayments.api.core.TokenizationKey import com.braintreepayments.api.shopperinsights.ShopperInsightsAnalytics.GET_RECOMMENDED_PAYMENTS_FAILED import com.braintreepayments.api.shopperinsights.ShopperInsightsAnalytics.GET_RECOMMENDED_PAYMENTS_STARTED @@ -30,6 +31,7 @@ class ShopperInsightsClient internal constructor( private val api: ShopperInsightsApi = ShopperInsightsApi( EligiblePaymentsApi(braintreeClient, analyticsParamRepository) ), + private val merchantRepository: MerchantRepository = MerchantRepository.instance, ) { /** @@ -72,7 +74,7 @@ class ShopperInsightsClient internal constructor( return } - if (braintreeClient.authorization is TokenizationKey) { + if (merchantRepository.authorization is TokenizationKey) { callbackFailure( callback = callback, error = BraintreeException( diff --git a/ShopperInsights/src/test/java/com/braintreepayments/api/shopperinsights/ShopperInsightsClientUnitTest.kt b/ShopperInsights/src/test/java/com/braintreepayments/api/shopperinsights/ShopperInsightsClientUnitTest.kt index ea6f81abc7..11f84afb38 100644 --- a/ShopperInsights/src/test/java/com/braintreepayments/api/shopperinsights/ShopperInsightsClientUnitTest.kt +++ b/ShopperInsights/src/test/java/com/braintreepayments/api/shopperinsights/ShopperInsightsClientUnitTest.kt @@ -4,11 +4,12 @@ import android.content.Context import androidx.test.core.app.ApplicationProvider import com.braintreepayments.api.core.AnalyticsEventParams import com.braintreepayments.api.core.AnalyticsParamRepository -import com.braintreepayments.api.core.Authorization import com.braintreepayments.api.core.BraintreeClient import com.braintreepayments.api.core.BraintreeException +import com.braintreepayments.api.core.ClientToken import com.braintreepayments.api.core.ExperimentalBetaApi -import com.braintreepayments.api.testutils.Fixtures +import com.braintreepayments.api.core.MerchantRepository +import com.braintreepayments.api.core.TokenizationKey import com.braintreepayments.api.testutils.MockkBraintreeClientBuilder import io.mockk.every import io.mockk.just @@ -39,14 +40,21 @@ class ShopperInsightsClientUnitTest { private lateinit var api: ShopperInsightsApi private lateinit var braintreeClient: BraintreeClient private lateinit var analyticsParamRepository: AnalyticsParamRepository + private lateinit var merchantRepository: MerchantRepository private lateinit var context: Context + private val clientToken = mockk() + @Before fun beforeEach() { api = mockk(relaxed = true) braintreeClient = mockk(relaxed = true) analyticsParamRepository = mockk(relaxed = true) - sut = ShopperInsightsClient(braintreeClient, analyticsParamRepository, api) + merchantRepository = mockk(relaxed = true) + + every { merchantRepository.authorization } returns clientToken + + sut = ShopperInsightsClient(braintreeClient, analyticsParamRepository, api, merchantRepository) context = ApplicationProvider.getApplicationContext() } @@ -392,11 +400,10 @@ class ShopperInsightsClientUnitTest { @Test fun `test getRecommendPaymentMethods is called with a tokenization key, error is sent`() { - val braintreeClient = MockkBraintreeClientBuilder() - .authorizationSuccess(Authorization.fromString(Fixtures.TOKENIZATION_KEY)) - .build() + every { merchantRepository.authorization } returns mockk() + val braintreeClient = MockkBraintreeClientBuilder().build() - sut = ShopperInsightsClient(braintreeClient, analyticsParamRepository, api) + sut = ShopperInsightsClient(braintreeClient, analyticsParamRepository, api, merchantRepository) val request = ShopperInsightsRequest("some-email", null) sut.getRecommendedPaymentMethods(request) { result -> diff --git a/TestUtils/src/main/java/com/braintreepayments/api/testutils/MockBraintreeClientBuilder.java b/TestUtils/src/main/java/com/braintreepayments/api/testutils/MockBraintreeClientBuilder.java index 0eed0176fd..36852509b1 100644 --- a/TestUtils/src/main/java/com/braintreepayments/api/testutils/MockBraintreeClientBuilder.java +++ b/TestUtils/src/main/java/com/braintreepayments/api/testutils/MockBraintreeClientBuilder.java @@ -33,11 +33,8 @@ public class MockBraintreeClientBuilder { private Configuration configuration; private Exception configurationError; - private Authorization authorization; - private IntegrationType integration; private String returnUrlScheme; - private Uri appLinkReturnUri; private ActivityInfo activityInfo; @@ -53,11 +50,6 @@ public MockBraintreeClientBuilder configurationError(Exception configurationErro return this; } - public MockBraintreeClientBuilder authorizationSuccess(Authorization authorization) { - this.authorization = authorization; - return this; - } - public MockBraintreeClientBuilder activityInfo(ActivityInfo activityInfo) { this.activityInfo = activityInfo; return this; @@ -93,11 +85,6 @@ public MockBraintreeClientBuilder sendGraphQLPOSTErrorResponse(Exception error) return this; } - public MockBraintreeClientBuilder integration(IntegrationType integration) { - this.integration = integration; - return this; - } - public MockBraintreeClientBuilder returnUrlScheme(String returnUrlScheme) { this.returnUrlScheme = returnUrlScheme; return this; @@ -109,21 +96,12 @@ public MockBraintreeClientBuilder launchesBrowserSwitchAsNewTask( return this; } - public MockBraintreeClientBuilder appLinkReturnUri( - Uri appLinkReturnUri) { - this.appLinkReturnUri = appLinkReturnUri; - return this; - } - public BraintreeClient build() { BraintreeClient braintreeClient = mock(BraintreeClient.class); - when(braintreeClient.getIntegrationType()).thenReturn(integration); - when(braintreeClient.getAuthorization()).thenReturn(authorization); when(braintreeClient.getReturnUrlScheme()).thenReturn(returnUrlScheme); when(braintreeClient.getManifestActivityInfo(any())).thenReturn(activityInfo); when(braintreeClient.launchesBrowserSwitchAsNewTask()).thenReturn( launchesBrowserSwitchAsNewTask); - when(braintreeClient.getAppLinkReturnUri()).thenReturn(appLinkReturnUri); doAnswer((Answer) invocation -> { ConfigurationCallback callback = (ConfigurationCallback) invocation.getArguments()[0]; diff --git a/ThreeDSecure/src/main/java/com/braintreepayments/api/threedsecure/ThreeDSecureClient.kt b/ThreeDSecure/src/main/java/com/braintreepayments/api/threedsecure/ThreeDSecureClient.kt index 14efbce75c..121487ecf4 100644 --- a/ThreeDSecure/src/main/java/com/braintreepayments/api/threedsecure/ThreeDSecureClient.kt +++ b/ThreeDSecure/src/main/java/com/braintreepayments/api/threedsecure/ThreeDSecureClient.kt @@ -7,6 +7,7 @@ import com.braintreepayments.api.core.BraintreeException import com.braintreepayments.api.core.BuildConfig import com.braintreepayments.api.core.Configuration import com.braintreepayments.api.core.InvalidArgumentException +import com.braintreepayments.api.core.MerchantRepository import com.braintreepayments.api.threedsecure.ThreeDSecureParams.Companion.fromJson import com.cardinalcommerce.cardinalmobilesdk.models.CardinalActionCode import org.json.JSONException @@ -24,7 +25,8 @@ import org.json.JSONObject class ThreeDSecureClient internal constructor( private val braintreeClient: BraintreeClient, private val cardinalClient: CardinalClient = CardinalClient(), - private val api: ThreeDSecureAPI = ThreeDSecureAPI(braintreeClient) + private val api: ThreeDSecureAPI = ThreeDSecureAPI(braintreeClient), + private val merchantRepository: MerchantRepository = MerchantRepository.instance, ) { /** * Initializes a new [ThreeDSecureClient] instance @@ -161,7 +163,7 @@ class ThreeDSecureClient internal constructor( val lookupJSON = JSONObject() try { lookupJSON - .put("authorizationFingerprint", braintreeClient.authorization.bearer) + .put("authorizationFingerprint", merchantRepository.authorization.bearer) .put("braintreeLibraryVersion", "Android-${BuildConfig.VERSION_NAME}") .put("nonce", request.nonce) .put( diff --git a/ThreeDSecure/src/test/java/com/braintreepayments/api/threedsecure/ThreeDSecureClientUnitTest.java b/ThreeDSecure/src/test/java/com/braintreepayments/api/threedsecure/ThreeDSecureClientUnitTest.java index 1a20707e15..8db8436e20 100644 --- a/ThreeDSecure/src/test/java/com/braintreepayments/api/threedsecure/ThreeDSecureClientUnitTest.java +++ b/ThreeDSecure/src/test/java/com/braintreepayments/api/threedsecure/ThreeDSecureClientUnitTest.java @@ -21,6 +21,7 @@ import com.braintreepayments.api.core.BraintreeClient; import com.braintreepayments.api.core.BraintreeException; import com.braintreepayments.api.core.Configuration; +import com.braintreepayments.api.core.MerchantRepository; import com.braintreepayments.api.testutils.Fixtures; import com.braintreepayments.api.sharedutils.HttpResponseCallback; import com.braintreepayments.api.testutils.MockBraintreeClientBuilder; @@ -45,6 +46,7 @@ public class ThreeDSecureClientUnitTest { private FragmentActivity activity; private ThreeDSecureAPI threeDSecureAPI; + private MerchantRepository merchantRepository = mock(MerchantRepository.class); private ThreeDSecurePaymentAuthRequestCallback paymentAuthRequestCallback; private ThreeDSecureTokenizeCallback threeDSecureTokenizeCallback; @@ -74,8 +76,9 @@ public void beforeEach() throws JSONException { billingAddress.setGivenName("billing-given-name"); basicRequest.setBillingAddress(billingAddress); - threeDSecureParams = - ThreeDSecureParams.fromJson(Fixtures.THREE_D_SECURE_V2_LOOKUP_RESPONSE); + threeDSecureParams = ThreeDSecureParams.fromJson(Fixtures.THREE_D_SECURE_V2_LOOKUP_RESPONSE); + + when(merchantRepository.getAuthorization()).thenReturn(Authorization.fromString(Fixtures.BASE64_CLIENT_TOKEN)); } // region prepareLookup @@ -88,13 +91,15 @@ public void prepareLookup_returnsValidLookupJSONString() .build(); BraintreeClient braintreeClient = new MockBraintreeClientBuilder() - .authorizationSuccess(Authorization.fromString(Fixtures.BASE64_CLIENT_TOKEN)) .configuration(threeDSecureEnabledConfig) .build(); - ThreeDSecureClient sut = - new ThreeDSecureClient(braintreeClient, cardinalClient, - new ThreeDSecureAPI(braintreeClient)); + ThreeDSecureClient sut = new ThreeDSecureClient( + braintreeClient, + cardinalClient, + new ThreeDSecureAPI(braintreeClient), + merchantRepository + ); ThreeDSecurePrepareLookupCallback callback = mock(ThreeDSecurePrepareLookupCallback.class); sut.prepareLookup(activity, basicRequest, callback); @@ -130,13 +135,15 @@ public void prepareLookup_returnsValidLookupJSONString_whenCardinalSetupFails() .build(); BraintreeClient braintreeClient = new MockBraintreeClientBuilder() - .authorizationSuccess(Authorization.fromString(Fixtures.BASE64_CLIENT_TOKEN)) .configuration(threeDSecureEnabledConfig) .build(); - ThreeDSecureClient sut = - new ThreeDSecureClient(braintreeClient, cardinalClient, - new ThreeDSecureAPI(braintreeClient)); + ThreeDSecureClient sut = new ThreeDSecureClient( + braintreeClient, + cardinalClient, + new ThreeDSecureAPI(braintreeClient), + merchantRepository + ); ThreeDSecurePrepareLookupCallback callback = mock(ThreeDSecurePrepareLookupCallback.class); sut.prepareLookup(activity, basicRequest, callback); @@ -170,13 +177,15 @@ public void prepareLookup_initializesCardinal() throws BraintreeException { .build(); BraintreeClient braintreeClient = new MockBraintreeClientBuilder() - .authorizationSuccess(Authorization.fromString(Fixtures.BASE64_CLIENT_TOKEN)) .configuration(threeDSecureEnabledConfig) .build(); - ThreeDSecureClient sut = - new ThreeDSecureClient(braintreeClient, cardinalClient, - new ThreeDSecureAPI(braintreeClient)); + ThreeDSecureClient sut = new ThreeDSecureClient( + braintreeClient, + cardinalClient, + new ThreeDSecureAPI(braintreeClient), + merchantRepository + ); ThreeDSecurePrepareLookupCallback callback = mock(ThreeDSecurePrepareLookupCallback.class); sut.prepareLookup(activity, basicRequest, callback); @@ -194,13 +203,15 @@ public void prepareLookup_whenCardinalClientInitializeFails_forwardsError() .build(); BraintreeClient braintreeClient = new MockBraintreeClientBuilder() - .authorizationSuccess(Authorization.fromString(Fixtures.BASE64_CLIENT_TOKEN)) .configuration(threeDSecureEnabledConfig) .build(); - ThreeDSecureClient sut = - new ThreeDSecureClient(braintreeClient, cardinalClient, - new ThreeDSecureAPI(braintreeClient)); + ThreeDSecureClient sut = new ThreeDSecureClient( + braintreeClient, + cardinalClient, + new ThreeDSecureAPI(braintreeClient), + merchantRepository + ); ThreeDSecurePrepareLookupCallback callback = mock(ThreeDSecurePrepareLookupCallback.class); sut.prepareLookup(activity, basicRequest, callback); @@ -220,13 +231,15 @@ public void prepareLookup_withoutCardinalJWT_postsException() throws BraintreeEx .buildConfiguration(); BraintreeClient braintreeClient = new MockBraintreeClientBuilder() - .authorizationSuccess(Authorization.fromString(Fixtures.BASE64_CLIENT_TOKEN)) .configuration(configuration) .build(); - ThreeDSecureClient sut = - new ThreeDSecureClient(braintreeClient, cardinalClient, - new ThreeDSecureAPI(braintreeClient)); + ThreeDSecureClient sut = new ThreeDSecureClient( + braintreeClient, + cardinalClient, + new ThreeDSecureAPI(braintreeClient), + merchantRepository + ); ThreeDSecurePrepareLookupCallback callback = mock(ThreeDSecurePrepareLookupCallback.class); sut.prepareLookup(activity, basicRequest, callback); @@ -257,9 +270,12 @@ public void createPaymentAuthRequest_sendsAnalyticEvent() throws BraintreeExcept .configuration(threeDSecureEnabledConfig) .build(); - ThreeDSecureClient sut = - new ThreeDSecureClient(braintreeClient, cardinalClient, - threeDSecureAPI); + ThreeDSecureClient sut = new ThreeDSecureClient( + braintreeClient, + cardinalClient, + threeDSecureAPI, + merchantRepository + ); sut.createPaymentAuthRequest(activity, basicRequest, paymentAuthRequestCallback); verify(braintreeClient).sendAnalyticsEvent(ThreeDSecureAnalytics.VERIFY_STARTED, new AnalyticsEventParams()); @@ -285,9 +301,12 @@ public void createPaymentAuthRequest_sendsParamsInLookupRequest() billingAddress.setGivenName("billing-given-name"); request.setBillingAddress(billingAddress); - ThreeDSecureClient sut = - new ThreeDSecureClient(braintreeClient, cardinalClient, - new ThreeDSecureAPI(braintreeClient)); + ThreeDSecureClient sut = new ThreeDSecureClient( + braintreeClient, + cardinalClient, + new ThreeDSecureAPI(braintreeClient), + merchantRepository + ); sut.createPaymentAuthRequest(activity, request, paymentAuthRequestCallback); String expectedUrl = "/v1/payment_methods/a-nonce/three_d_secure/lookup"; @@ -322,9 +341,12 @@ public void createPaymentAuthRequest_performsLookup_WhenCardinalSDKInitFails() billingAddress.setGivenName("billing-given-name"); request.setBillingAddress(billingAddress); - ThreeDSecureClient sut = - new ThreeDSecureClient(braintreeClient, cardinalClient, - new ThreeDSecureAPI(braintreeClient)); + ThreeDSecureClient sut = new ThreeDSecureClient( + braintreeClient, + cardinalClient, + new ThreeDSecureAPI(braintreeClient), + merchantRepository + ); sut.createPaymentAuthRequest(activity, request, paymentAuthRequestCallback); ArgumentCaptor pathCaptor = ArgumentCaptor.forClass(String.class); @@ -364,9 +386,12 @@ public void createPaymentAuthRequest_callsLookupListener() throws BraintreeExcep billingAddress.setGivenName("billing-given-name"); request.setBillingAddress(billingAddress); - ThreeDSecureClient sut = - new ThreeDSecureClient(braintreeClient, cardinalClient, - new ThreeDSecureAPI(braintreeClient)); + ThreeDSecureClient sut = new ThreeDSecureClient( + braintreeClient, + cardinalClient, + new ThreeDSecureAPI(braintreeClient), + merchantRepository + ); sut.createPaymentAuthRequest(activity, request, paymentAuthRequestCallback); @@ -379,9 +404,12 @@ public void createPaymentAuthRequest_withInvalidRequest_postsException() throws BraintreeClient braintreeClient = new MockBraintreeClientBuilder().build(); - ThreeDSecureClient sut = - new ThreeDSecureClient(braintreeClient, cardinalClient, - threeDSecureAPI); + ThreeDSecureClient sut = new ThreeDSecureClient( + braintreeClient, + cardinalClient, + threeDSecureAPI, + merchantRepository + ); ThreeDSecureRequest request = new ThreeDSecureRequest(); request.setAmount("5"); @@ -402,13 +430,15 @@ public void createPaymentAuthRequest_initializesCardinal() throws BraintreeExcep .build(); BraintreeClient braintreeClient = new MockBraintreeClientBuilder() - .authorizationSuccess(Authorization.fromString(Fixtures.BASE64_CLIENT_TOKEN)) .configuration(threeDSecureEnabledConfig) .build(); - ThreeDSecureClient sut = - new ThreeDSecureClient(braintreeClient, cardinalClient, - new ThreeDSecureAPI(braintreeClient)); + ThreeDSecureClient sut = new ThreeDSecureClient( + braintreeClient, + cardinalClient, + new ThreeDSecureAPI(braintreeClient), + merchantRepository + ); sut.createPaymentAuthRequest(activity, basicRequest, paymentAuthRequestCallback); verify(cardinalClient).initialize(same(activity), same(threeDSecureEnabledConfig), @@ -424,13 +454,15 @@ public void createPaymentAuthRequest_whenCardinalClientInitializeFails_forwardsE .build(); BraintreeClient braintreeClient = new MockBraintreeClientBuilder() - .authorizationSuccess(Authorization.fromString(Fixtures.BASE64_CLIENT_TOKEN)) .configuration(threeDSecureEnabledConfig) .build(); - ThreeDSecureClient sut = - new ThreeDSecureClient(braintreeClient, cardinalClient, - new ThreeDSecureAPI(braintreeClient)); + ThreeDSecureClient sut = new ThreeDSecureClient( + braintreeClient, + cardinalClient, + new ThreeDSecureAPI(braintreeClient), + merchantRepository + ); sut.createPaymentAuthRequest(activity, basicRequest, paymentAuthRequestCallback); @@ -450,13 +482,15 @@ public void createPaymentAuthRequest_whenCardinalSetupFailed_sendsAnalyticEvent( .build(); BraintreeClient braintreeClient = new MockBraintreeClientBuilder() - .authorizationSuccess(Authorization.fromString(Fixtures.BASE64_CLIENT_TOKEN)) .configuration(threeDSecureEnabledConfig) .build(); - ThreeDSecureClient sut = - new ThreeDSecureClient(braintreeClient, cardinalClient, - new ThreeDSecureAPI(braintreeClient)); + ThreeDSecureClient sut = new ThreeDSecureClient( + braintreeClient, + cardinalClient, + new ThreeDSecureAPI(braintreeClient), + merchantRepository + ); sut.createPaymentAuthRequest(activity, basicRequest, paymentAuthRequestCallback); verify(braintreeClient).sendAnalyticsEvent(ThreeDSecureAnalytics.VERIFY_STARTED, new AnalyticsEventParams()); @@ -472,13 +506,15 @@ public void createPaymentAuthRequest_withoutCardinalJWT_postsException() throws .buildConfiguration(); BraintreeClient braintreeClient = new MockBraintreeClientBuilder() - .authorizationSuccess(Authorization.fromString(Fixtures.BASE64_CLIENT_TOKEN)) .configuration(configuration) .build(); - ThreeDSecureClient sut = - new ThreeDSecureClient(braintreeClient, cardinalClient, - new ThreeDSecureAPI(braintreeClient)); + ThreeDSecureClient sut = new ThreeDSecureClient( + braintreeClient, + cardinalClient, + new ThreeDSecureAPI(braintreeClient), + merchantRepository + ); sut.createPaymentAuthRequest(activity, basicRequest, paymentAuthRequestCallback); @@ -504,13 +540,15 @@ public void sendAnalyticsAndCallbackResult_whenAuthenticatingWithCardinal_sendsA .build(); BraintreeClient braintreeClient = new MockBraintreeClientBuilder() - .authorizationSuccess(Authorization.fromString(Fixtures.BASE64_CLIENT_TOKEN)) .configuration(threeDSecureEnabledConfig) .build(); - ThreeDSecureClient sut = - new ThreeDSecureClient(braintreeClient, cardinalClient, - new ThreeDSecureAPI(braintreeClient)); + ThreeDSecureClient sut = new ThreeDSecureClient( + braintreeClient, + cardinalClient, + new ThreeDSecureAPI(braintreeClient), + merchantRepository + ); ThreeDSecureParams threeDSecureParams = ThreeDSecureParams.fromJson(Fixtures.THREE_D_SECURE_V2_LOOKUP_RESPONSE); @@ -527,14 +565,16 @@ public void sendAnalyticsAndCallbackResult_whenChallengeIsRequired_sendsAnalytic .build(); BraintreeClient braintreeClient = new MockBraintreeClientBuilder() - .authorizationSuccess(Authorization.fromString(Fixtures.BASE64_CLIENT_TOKEN)) .configuration(threeDSecureEnabledConfig) .returnUrlScheme("sample-return-url://") .build(); - ThreeDSecureClient sut = - new ThreeDSecureClient(braintreeClient, cardinalClient, - new ThreeDSecureAPI(braintreeClient)); + ThreeDSecureClient sut = new ThreeDSecureClient( + braintreeClient, + cardinalClient, + new ThreeDSecureAPI(braintreeClient), + merchantRepository + ); ThreeDSecureParams threeDSecureParams = ThreeDSecureParams.fromJson(Fixtures.THREE_D_SECURE_LOOKUP_RESPONSE); @@ -552,13 +592,15 @@ public void sendAnalyticsAndCallbackResult_whenChallengeIsNotPresented_returnsRe .build(); BraintreeClient braintreeClient = new MockBraintreeClientBuilder() - .authorizationSuccess(Authorization.fromString(Fixtures.BASE64_CLIENT_TOKEN)) .configuration(threeDSecureEnabledConfig) .build(); - ThreeDSecureClient sut = - new ThreeDSecureClient(braintreeClient, cardinalClient, - new ThreeDSecureAPI(braintreeClient)); + ThreeDSecureClient sut = new ThreeDSecureClient( + braintreeClient, + cardinalClient, + new ThreeDSecureAPI(braintreeClient), + merchantRepository + ); ThreeDSecureParams threeDSecureParams = ThreeDSecureParams.fromJson(Fixtures.THREE_D_SECURE_LOOKUP_RESPONSE_NO_ACS_URL); @@ -580,13 +622,15 @@ public void sendAnalyticsAndCallbackResult_callsBackThreeDSecureResultForLaunch( .build(); BraintreeClient braintreeClient = new MockBraintreeClientBuilder() - .authorizationSuccess(Authorization.fromString(Fixtures.BASE64_CLIENT_TOKEN)) .configuration(threeDSecureEnabledConfig) .build(); - ThreeDSecureClient sut = - new ThreeDSecureClient(braintreeClient, cardinalClient, - new ThreeDSecureAPI(braintreeClient)); + ThreeDSecureClient sut = new ThreeDSecureClient( + braintreeClient, + cardinalClient, + new ThreeDSecureAPI(braintreeClient), + merchantRepository + ); ThreeDSecureParams threeDSecureParams = ThreeDSecureParams.fromJson(Fixtures.THREE_D_SECURE_V2_LOOKUP_RESPONSE); @@ -609,9 +653,12 @@ public void tokenize_whenErrorExists_forwardsErrorToCallback_andSendsAnalytics() CardinalClient cardinalClient = new MockCardinalClientBuilder().build(); BraintreeClient braintreeClient = new MockBraintreeClientBuilder().build(); - ThreeDSecureClient sut = - new ThreeDSecureClient(braintreeClient, cardinalClient, - threeDSecureAPI); + ThreeDSecureClient sut = new ThreeDSecureClient( + braintreeClient, + cardinalClient, + threeDSecureAPI, + merchantRepository + ); Exception threeDSecureError = new Exception("3DS error."); ThreeDSecurePaymentAuthResult paymentAuthResult = new ThreeDSecurePaymentAuthResult(null, null, null, threeDSecureError); @@ -634,9 +681,12 @@ public void tokenize_whenValidateResponseTimeout_returnsErrorAndSendsAnalytics() when(validateResponse.getActionCode()).thenReturn(CardinalActionCode.TIMEOUT); when(validateResponse.getErrorDescription()).thenReturn("Error"); - ThreeDSecureClient sut = - new ThreeDSecureClient(braintreeClient, cardinalClient, - threeDSecureAPI); + ThreeDSecureClient sut = new ThreeDSecureClient( + braintreeClient, + cardinalClient, + threeDSecureAPI, + merchantRepository + ); ThreeDSecurePaymentAuthResult paymentAuthResult = new ThreeDSecurePaymentAuthResult("jwt", validateResponse, threeDSecureParams, null); @@ -663,9 +713,12 @@ public void tokenize_whenValidateResponseCancel_returnsUserCanceledErrorAndSends ValidateResponse validateResponse = mock(ValidateResponse.class); when(validateResponse.getActionCode()).thenReturn(CardinalActionCode.CANCEL); - ThreeDSecureClient sut = - new ThreeDSecureClient(braintreeClient, cardinalClient, - threeDSecureAPI); + ThreeDSecureClient sut = new ThreeDSecureClient( + braintreeClient, + cardinalClient, + threeDSecureAPI, + merchantRepository + ); ThreeDSecurePaymentAuthResult paymentAuthResult = new ThreeDSecurePaymentAuthResult("jwt", validateResponse, threeDSecureParams, null); @@ -696,9 +749,12 @@ public void tokenize_whenValidateResponseSuccess_onAuthenticateCardinalJWTResult }).when(threeDSecureAPI).authenticateCardinalJWT(any(ThreeDSecureParams.class), anyString(), any(ThreeDSecureResultCallback.class)); - ThreeDSecureClient sut = - new ThreeDSecureClient(braintreeClient, cardinalClient, - threeDSecureAPI); + ThreeDSecureClient sut = new ThreeDSecureClient( + braintreeClient, + cardinalClient, + threeDSecureAPI, + merchantRepository + ); ThreeDSecurePaymentAuthResult paymentAuthResult = new ThreeDSecurePaymentAuthResult("jwt", validateResponse, threeDSecureParams, null); @@ -733,9 +789,12 @@ public void tokenize_whenValidateResponseSuccess_onAuthenticateCardinalJWTResult }).when(threeDSecureAPI).authenticateCardinalJWT(any(ThreeDSecureParams.class), anyString(), any(ThreeDSecureResultCallback.class)); - ThreeDSecureClient sut = - new ThreeDSecureClient(braintreeClient, cardinalClient, - threeDSecureAPI); + ThreeDSecureClient sut = new ThreeDSecureClient( + braintreeClient, + cardinalClient, + threeDSecureAPI, + merchantRepository + ); ThreeDSecurePaymentAuthResult paymentAuthResult = new ThreeDSecurePaymentAuthResult("jwt", validateResponse, threeDSecureParams, null); @@ -771,9 +830,12 @@ public void tokenize_whenValidateResponseSuccess_onAuthenticateCardinalJWTError_ }).when(threeDSecureAPI).authenticateCardinalJWT(any(ThreeDSecureParams.class), anyString(), any(ThreeDSecureResultCallback.class)); - ThreeDSecureClient sut = - new ThreeDSecureClient(braintreeClient, cardinalClient, - threeDSecureAPI); + ThreeDSecureClient sut = new ThreeDSecureClient( + braintreeClient, + cardinalClient, + threeDSecureAPI, + merchantRepository + ); ThreeDSecurePaymentAuthResult paymentAuthResult = new ThreeDSecurePaymentAuthResult("jwt", validateResponse, threeDSecureParams, null); diff --git a/Venmo/src/main/java/com/braintreepayments/api/venmo/VenmoApi.kt b/Venmo/src/main/java/com/braintreepayments/api/venmo/VenmoApi.kt index f4c7138126..88624c65d0 100644 --- a/Venmo/src/main/java/com/braintreepayments/api/venmo/VenmoApi.kt +++ b/Venmo/src/main/java/com/braintreepayments/api/venmo/VenmoApi.kt @@ -5,6 +5,7 @@ import com.braintreepayments.api.core.AnalyticsParamRepository import com.braintreepayments.api.core.ApiClient import com.braintreepayments.api.core.BraintreeClient import com.braintreepayments.api.core.BraintreeException +import com.braintreepayments.api.core.MerchantRepository import com.braintreepayments.api.core.MetadataBuilder import com.braintreepayments.api.venmo.VenmoAccountNonce.Companion.fromJSON import org.json.JSONArray @@ -14,7 +15,8 @@ import org.json.JSONObject internal class VenmoApi( private val braintreeClient: BraintreeClient, private val apiClient: ApiClient, - private val analyticsParamRepository: AnalyticsParamRepository = AnalyticsParamRepository.instance + private val analyticsParamRepository: AnalyticsParamRepository = AnalyticsParamRepository.instance, + private val merchantRepository: MerchantRepository = MerchantRepository.instance, ) { @Suppress("LongMethod") @@ -82,7 +84,7 @@ internal class VenmoApi( val braintreeData = MetadataBuilder() .sessionId(analyticsParamRepository.sessionId) - .integration(braintreeClient.integrationType) + .integration(merchantRepository.integrationType) .version() .build() diff --git a/Venmo/src/main/java/com/braintreepayments/api/venmo/VenmoClient.kt b/Venmo/src/main/java/com/braintreepayments/api/venmo/VenmoClient.kt index f2296ff55e..764c51b45e 100644 --- a/Venmo/src/main/java/com/braintreepayments/api/venmo/VenmoClient.kt +++ b/Venmo/src/main/java/com/braintreepayments/api/venmo/VenmoClient.kt @@ -16,6 +16,7 @@ import com.braintreepayments.api.core.BraintreeException import com.braintreepayments.api.core.BraintreeRequestCodes import com.braintreepayments.api.core.ClientToken import com.braintreepayments.api.core.Configuration +import com.braintreepayments.api.core.MerchantRepository import com.braintreepayments.api.core.MetadataBuilder import org.json.JSONException import org.json.JSONObject @@ -29,7 +30,8 @@ class VenmoClient internal constructor( private val apiClient: ApiClient = ApiClient(braintreeClient), private val venmoApi: VenmoApi = VenmoApi(braintreeClient, apiClient), private val sharedPrefsWriter: VenmoSharedPrefsWriter = VenmoSharedPrefsWriter(), - private val analyticsParamRepository: AnalyticsParamRepository = AnalyticsParamRepository.instance + private val analyticsParamRepository: AnalyticsParamRepository = AnalyticsParamRepository.instance, + private val merchantRepository: MerchantRepository = MerchantRepository.instance, ) { /** * Used for linking events from the client to server side request @@ -117,7 +119,7 @@ class VenmoClient internal constructor( try { createPaymentAuthRequest( context, request, configuration, - braintreeClient.authorization, finalVenmoProfileId, + merchantRepository.authorization, finalVenmoProfileId, paymentContextId, callback ) } catch (e: JSONException) { @@ -146,7 +148,7 @@ class VenmoClient internal constructor( val metadata = MetadataBuilder() .sessionId(analyticsParamRepository.sessionId) - .integration(braintreeClient.integrationType) + .integration(merchantRepository.integrationType) .version() .build() @@ -228,14 +230,14 @@ class VenmoClient internal constructor( val paymentMethodNonce = parse(deepLinkUri.toString(), "payment_method_nonce") val username = parse(deepLinkUri.toString(), "username") - val isClientTokenAuth = (braintreeClient.authorization is ClientToken) + val isClientTokenAuth = (merchantRepository.authorization is ClientToken) if (paymentContextId != null) { venmoApi.createNonceFromPaymentContext(paymentContextId) { nonce: VenmoAccountNonce?, error: Exception? -> if (nonce != null) { isVaultRequest = sharedPrefsWriter.getVenmoVaultOption( - braintreeClient.applicationContext + merchantRepository.applicationContext ) if (isVaultRequest && isClientTokenAuth) { vaultVenmoAccountNonce( @@ -262,7 +264,7 @@ class VenmoClient internal constructor( } } else if (paymentMethodNonce != null && username != null) { isVaultRequest = sharedPrefsWriter.getVenmoVaultOption( - braintreeClient.applicationContext + merchantRepository.applicationContext ) if (isVaultRequest && isClientTokenAuth) { diff --git a/Venmo/src/test/java/com/braintreepayments/api/venmo/VenmoApiUnitTest.java b/Venmo/src/test/java/com/braintreepayments/api/venmo/VenmoApiUnitTest.java index a2d76a2132..d2d15d9859 100644 --- a/Venmo/src/test/java/com/braintreepayments/api/venmo/VenmoApiUnitTest.java +++ b/Venmo/src/test/java/com/braintreepayments/api/venmo/VenmoApiUnitTest.java @@ -12,6 +12,7 @@ import static org.mockito.Mockito.when; import com.braintreepayments.api.core.AnalyticsParamRepository; +import com.braintreepayments.api.core.MerchantRepository; import com.braintreepayments.api.testutils.Fixtures; import com.braintreepayments.api.testutils.MockApiClientBuilder; import com.braintreepayments.api.testutils.MockBraintreeClientBuilder; @@ -38,6 +39,7 @@ public class VenmoApiUnitTest { private BraintreeClient braintreeClient; private ApiClient apiClient; private AnalyticsParamRepository analyticsParamRepository; + private MerchantRepository merchantRepository = mock(MerchantRepository.class); @Before public void beforeEach() { @@ -50,7 +52,7 @@ public void beforeEach() { @Test public void createPaymentContext_createsPaymentContextViaGraphQL() throws JSONException { - VenmoApi venmoAPI = new VenmoApi(braintreeClient, apiClient, analyticsParamRepository); + VenmoApi venmoAPI = new VenmoApi(braintreeClient, apiClient, analyticsParamRepository, merchantRepository); VenmoRequest request = new VenmoRequest(VenmoPaymentMethodUsage.SINGLE_USE); request.setProfileId("sample-venmo-merchant"); @@ -104,7 +106,7 @@ public void createPaymentContext_createsPaymentContextViaGraphQL() throws JSONEx @Test public void createPaymentContext_whenTransactionAmountOptionsMissing() throws JSONException { - VenmoApi venmoAPI = new VenmoApi(braintreeClient, apiClient, analyticsParamRepository); + VenmoApi venmoAPI = new VenmoApi(braintreeClient, apiClient, analyticsParamRepository, merchantRepository); VenmoRequest request = new VenmoRequest(VenmoPaymentMethodUsage.SINGLE_USE); request.setProfileId("sample-venmo-merchant"); @@ -137,7 +139,7 @@ public void createPaymentContext_whenGraphQLPostSuccess_includesPaymentContextID .sendGraphQLPOSTSuccessfulResponse( Fixtures.VENMO_GRAPHQL_CREATE_PAYMENT_METHOD_CONTEXT_RESPONSE) .build(); - VenmoApi venmoAPI = new VenmoApi(braintreeClient, apiClient, analyticsParamRepository); + VenmoApi venmoAPI = new VenmoApi(braintreeClient, apiClient, analyticsParamRepository, merchantRepository); VenmoRequest request = new VenmoRequest(VenmoPaymentMethodUsage.SINGLE_USE); request.setProfileId("sample-venmo-merchant"); @@ -154,7 +156,7 @@ public void createPaymentContext_whenGraphQLPostSuccess_missingPaymentContextID_ .sendGraphQLPOSTSuccessfulResponse( Fixtures.VENMO_GRAPHQL_CREATE_PAYMENT_METHOD_RESPONSE_WITHOUT_PAYMENT_CONTEXT_ID) .build(); - VenmoApi venmoAPI = new VenmoApi(braintreeClient, apiClient, analyticsParamRepository); + VenmoApi venmoAPI = new VenmoApi(braintreeClient, apiClient, analyticsParamRepository, merchantRepository); VenmoRequest request = new VenmoRequest(VenmoPaymentMethodUsage.SINGLE_USE); request.setProfileId("sample-venmo-merchant"); @@ -177,7 +179,7 @@ public void createPaymentContext_whenGraphQLPostError_forwardsErrorToCallback() BraintreeClient braintreeClient = new MockBraintreeClientBuilder() .sendGraphQLPOSTErrorResponse(error) .build(); - VenmoApi venmoAPI = new VenmoApi(braintreeClient, apiClient, analyticsParamRepository); + VenmoApi venmoAPI = new VenmoApi(braintreeClient, apiClient, analyticsParamRepository, merchantRepository); VenmoRequest request = new VenmoRequest(VenmoPaymentMethodUsage.SINGLE_USE); request.setProfileId("sample-venmo-merchant"); @@ -190,7 +192,7 @@ public void createPaymentContext_whenGraphQLPostError_forwardsErrorToCallback() @Test public void createPaymentContext_withTotalAmountAndSetsFinalAmountToTrue() throws JSONException { - VenmoApi venmoAPI = new VenmoApi(braintreeClient, apiClient, analyticsParamRepository); + VenmoApi venmoAPI = new VenmoApi(braintreeClient, apiClient, analyticsParamRepository, merchantRepository); VenmoRequest request = new VenmoRequest(VenmoPaymentMethodUsage.SINGLE_USE); request.setProfileId("sample-venmo-merchant"); @@ -216,7 +218,7 @@ public void createPaymentContext_withTotalAmountAndSetsFinalAmountToTrue() throw @Test public void createPaymentContext_withTotalAmountAndSetsFinalAmountToFalse() throws JSONException { - VenmoApi venmoAPI = new VenmoApi(braintreeClient, apiClient, analyticsParamRepository); + VenmoApi venmoAPI = new VenmoApi(braintreeClient, apiClient, analyticsParamRepository, merchantRepository); VenmoRequest request = new VenmoRequest(VenmoPaymentMethodUsage.SINGLE_USE); request.setProfileId("sample-venmo-merchant"); @@ -242,7 +244,7 @@ public void createPaymentContext_withTotalAmountAndSetsFinalAmountToFalse() thro @Test public void createNonceFromPaymentContext_queriesGraphQLPaymentContext() throws JSONException { - VenmoApi sut = new VenmoApi(braintreeClient, apiClient, analyticsParamRepository); + VenmoApi sut = new VenmoApi(braintreeClient, apiClient, analyticsParamRepository, merchantRepository); sut.createNonceFromPaymentContext("payment-context-id", mock(VenmoInternalCallback.class)); ArgumentCaptor captor = ArgumentCaptor.forClass(JSONObject.class); @@ -259,7 +261,7 @@ public void createNonceFromPaymentContext_whenGraphQLPostSuccess_forwardsNonceTo .sendGraphQLPOSTSuccessfulResponse(graphQLResponse) .build(); - VenmoApi sut = new VenmoApi(braintreeClient, apiClient, analyticsParamRepository); + VenmoApi sut = new VenmoApi(braintreeClient, apiClient, analyticsParamRepository, merchantRepository); VenmoInternalCallback callback = mock(VenmoInternalCallback.class); sut.createNonceFromPaymentContext("payment-context-id", callback); @@ -275,7 +277,7 @@ public void createNonceFromPaymentContext_whenGraphQLPostResponseMalformed_calls .sendGraphQLPOSTSuccessfulResponse("not-json") .build(); - VenmoApi sut = new VenmoApi(braintreeClient, apiClient, analyticsParamRepository); + VenmoApi sut = new VenmoApi(braintreeClient, apiClient, analyticsParamRepository, merchantRepository); VenmoInternalCallback callback = mock(VenmoInternalCallback.class); sut.createNonceFromPaymentContext("payment-context-id", callback); @@ -292,7 +294,7 @@ public void createNonceFromPaymentContext_whenGraphQLPostError_forwardsErrorToCa .sendGraphQLPOSTErrorResponse(error) .build(); - VenmoApi sut = new VenmoApi(braintreeClient, apiClient, analyticsParamRepository); + VenmoApi sut = new VenmoApi(braintreeClient, apiClient, analyticsParamRepository, merchantRepository); VenmoInternalCallback callback = mock(VenmoInternalCallback.class); sut.createNonceFromPaymentContext("payment-context-id", callback); @@ -302,7 +304,7 @@ public void createNonceFromPaymentContext_whenGraphQLPostError_forwardsErrorToCa @Test public void vaultVenmoAccountNonce_performsVaultRequest() throws JSONException { - VenmoApi sut = new VenmoApi(braintreeClient, apiClient, analyticsParamRepository); + VenmoApi sut = new VenmoApi(braintreeClient, apiClient, analyticsParamRepository, merchantRepository); sut.vaultVenmoAccountNonce("nonce", mock(VenmoInternalCallback.class)); ArgumentCaptor accountBuilderCaptor = @@ -320,7 +322,7 @@ public void vaultVenmoAccountNonce_tokenizeRESTSuccess_callsBackNonce() throws J .tokenizeRESTSuccess(new JSONObject( Fixtures.VENMO_PAYMENT_METHOD_CONTEXT_WITH_NULL_PAYER_INFO_JSON)) .build(); - VenmoApi sut = new VenmoApi(braintreeClient, apiClient, analyticsParamRepository); + VenmoApi sut = new VenmoApi(braintreeClient, apiClient, analyticsParamRepository, merchantRepository); VenmoInternalCallback callback = mock(VenmoInternalCallback.class); sut.vaultVenmoAccountNonce("nonce", callback); @@ -338,7 +340,7 @@ public void vaultVenmoAccountNonce_tokenizeRESTError_forwardsErrorToCallback() { ApiClient apiClient = new MockApiClientBuilder() .tokenizeRESTError(error) .build(); - VenmoApi sut = new VenmoApi(braintreeClient, apiClient, analyticsParamRepository); + VenmoApi sut = new VenmoApi(braintreeClient, apiClient, analyticsParamRepository, merchantRepository); VenmoInternalCallback callback = mock(VenmoInternalCallback.class); sut.vaultVenmoAccountNonce("nonce", callback); diff --git a/Venmo/src/test/java/com/braintreepayments/api/venmo/VenmoClientUnitTest.java b/Venmo/src/test/java/com/braintreepayments/api/venmo/VenmoClientUnitTest.java index 971818bf08..89f81a09f8 100644 --- a/Venmo/src/test/java/com/braintreepayments/api/venmo/VenmoClientUnitTest.java +++ b/Venmo/src/test/java/com/braintreepayments/api/venmo/VenmoClientUnitTest.java @@ -22,6 +22,7 @@ import com.braintreepayments.api.core.AnalyticsParamRepository; import com.braintreepayments.api.core.ApiClient; import com.braintreepayments.api.core.IntegrationType; +import com.braintreepayments.api.core.MerchantRepository; import com.braintreepayments.api.testutils.Fixtures; import com.braintreepayments.api.testutils.MockBraintreeClientBuilder; import com.braintreepayments.api.core.Authorization; @@ -64,6 +65,8 @@ public class VenmoClientUnitTest { private final String LINK_TYPE = "universal"; private final AnalyticsEventParams expectedAnalyticsParams = new AnalyticsEventParams(); private final AnalyticsEventParams expectedVaultAnalyticsParams = new AnalyticsEventParams(); + + private final MerchantRepository merchantRepository = mock(MerchantRepository.class); @Before public void beforeEach() throws JSONException { @@ -92,16 +95,18 @@ public void beforeEach() throws JSONException { paymentAuthResult = new VenmoPaymentAuthResult.Success(browserSwitchResult); when(analyticsParamRepository.getSessionId()).thenReturn("session-id"); + when(merchantRepository.getIntegrationType()).thenReturn(IntegrationType.CUSTOM); + when(merchantRepository.getApplicationContext()).thenReturn(context); } @Test public void createPaymentAuthRequest_whenCreatePaymentContextFails_collectAddressWithEcdDisabled() { BraintreeClient braintreeClient = new MockBraintreeClientBuilder() .configuration(venmoEnabledConfiguration) - .integration(IntegrationType.CUSTOM) - .authorizationSuccess(clientToken) .build(); + when(merchantRepository.getAuthorization()).thenReturn(clientToken); + VenmoApi venmoApi = new MockVenmoApiBuilder() .createPaymentContextSuccess("venmo-payment-context-id") .build(); @@ -113,8 +118,14 @@ public void createPaymentAuthRequest_whenCreatePaymentContextFails_collectAddres request.setProfileId("sample-venmo-merchant"); request.setCollectCustomerBillingAddress(true); - VenmoClient sut = - new VenmoClient(braintreeClient, apiClient, venmoApi, sharedPrefsWriter, analyticsParamRepository); + VenmoClient sut = new VenmoClient( + braintreeClient, + apiClient, + venmoApi, + sharedPrefsWriter, + analyticsParamRepository, + merchantRepository + ); sut.createPaymentAuthRequest(context, request, venmoPaymentAuthRequestCallback); verify(venmoPaymentAuthRequestCallback).onVenmoPaymentAuthRequest(captor.capture()); @@ -130,11 +141,11 @@ public void createPaymentAuthRequest_whenCreatePaymentContextFails_collectAddres public void createPaymentAuthRequest_whenCreatePaymentContextSucceeds_createsVenmoAuthChallenge() { BraintreeClient braintreeClient = new MockBraintreeClientBuilder() .configuration(venmoEnabledConfiguration) - .integration(IntegrationType.CUSTOM) - .authorizationSuccess(clientToken) .returnUrlScheme("com.example") .build(); + when(merchantRepository.getAuthorization()).thenReturn(clientToken); + VenmoApi venmoApi = new MockVenmoApiBuilder() .createPaymentContextSuccess("venmo-payment-context-id") .build(); @@ -143,8 +154,14 @@ public void createPaymentAuthRequest_whenCreatePaymentContextSucceeds_createsVen request.setProfileId("sample-venmo-merchant"); request.setShouldVault(false); - VenmoClient sut = - new VenmoClient(braintreeClient, apiClient, venmoApi, sharedPrefsWriter, analyticsParamRepository); + VenmoClient sut = new VenmoClient( + braintreeClient, + apiClient, + venmoApi, + sharedPrefsWriter, + analyticsParamRepository, + merchantRepository + ); sut.createPaymentAuthRequest(context, request, venmoPaymentAuthRequestCallback); InOrder inOrder = Mockito.inOrder(venmoPaymentAuthRequestCallback, braintreeClient); @@ -186,8 +203,14 @@ public void createPaymentAuthRequest_whenConfigurationException_forwardsExceptio request.setProfileId(null); request.setShouldVault(false); - VenmoClient sut = - new VenmoClient(braintreeClient, apiClient, venmoApi, sharedPrefsWriter, analyticsParamRepository); + VenmoClient sut = new VenmoClient( + braintreeClient, + apiClient, + venmoApi, + sharedPrefsWriter, + analyticsParamRepository, + merchantRepository + ); sut.createPaymentAuthRequest(context, request, venmoPaymentAuthRequestCallback); ArgumentCaptor captor = @@ -209,8 +232,14 @@ public void createPaymentAuthRequest_whenVenmoNotEnabled_forwardsExceptionToList request.setProfileId(null); request.setShouldVault(false); - VenmoClient sut = - new VenmoClient(braintreeClient, apiClient, venmoApi, sharedPrefsWriter, analyticsParamRepository); + VenmoClient sut = new VenmoClient( + braintreeClient, + apiClient, + venmoApi, + sharedPrefsWriter, + analyticsParamRepository, + merchantRepository + ); sut.createPaymentAuthRequest(context, request, venmoPaymentAuthRequestCallback); ArgumentCaptor captor = @@ -226,10 +255,10 @@ public void createPaymentAuthRequest_whenVenmoNotEnabled_forwardsExceptionToList public void createPaymentAuthRequest_whenProfileIdIsNull_appSwitchesWithMerchantId() { BraintreeClient braintreeClient = new MockBraintreeClientBuilder() .configuration(venmoEnabledConfiguration) - .integration(IntegrationType.CUSTOM) - .authorizationSuccess(clientToken) .build(); + when(merchantRepository.getAuthorization()).thenReturn(clientToken); + VenmoApi venmoApi = new MockVenmoApiBuilder() .createPaymentContextSuccess("venmo-payment-context-id") .build(); @@ -238,8 +267,14 @@ public void createPaymentAuthRequest_whenProfileIdIsNull_appSwitchesWithMerchant request.setProfileId(null); request.setShouldVault(false); - VenmoClient sut = - new VenmoClient(braintreeClient, apiClient, venmoApi, sharedPrefsWriter, analyticsParamRepository); + VenmoClient sut = new VenmoClient( + braintreeClient, + apiClient, + venmoApi, + sharedPrefsWriter, + analyticsParamRepository, + merchantRepository + ); sut.createPaymentAuthRequest(context, request, venmoPaymentAuthRequestCallback); ArgumentCaptor captor = @@ -258,10 +293,10 @@ public void createPaymentAuthRequest_whenProfileIdIsNull_appSwitchesWithMerchant public void createPaymentAuthRequest_whenProfileIdIsSpecified_appSwitchesWithProfileIdAndAccessToken() { BraintreeClient braintreeClient = new MockBraintreeClientBuilder() .configuration(venmoEnabledConfiguration) - .integration(IntegrationType.CUSTOM) - .authorizationSuccess(clientToken) .build(); + when(merchantRepository.getAuthorization()).thenReturn(clientToken); + VenmoApi venmoApi = new MockVenmoApiBuilder() .createPaymentContextSuccess("venmo-payment-context-id") .build(); @@ -270,8 +305,14 @@ public void createPaymentAuthRequest_whenProfileIdIsSpecified_appSwitchesWithPro request.setProfileId("second-pwv-profile-id"); request.setShouldVault(false); - VenmoClient sut = - new VenmoClient(braintreeClient, apiClient, venmoApi, sharedPrefsWriter, analyticsParamRepository); + VenmoClient sut = new VenmoClient( + braintreeClient, + apiClient, + venmoApi, + sharedPrefsWriter, + analyticsParamRepository, + merchantRepository + ); sut.createPaymentAuthRequest(context, request, venmoPaymentAuthRequestCallback); ArgumentCaptor captor = @@ -298,8 +339,14 @@ public void createPaymentAuthRequest_sendsAnalyticsEvent() { request.setProfileId(null); request.setShouldVault(false); - VenmoClient sut = - new VenmoClient(braintreeClient, apiClient, venmoApi, sharedPrefsWriter, analyticsParamRepository); + VenmoClient sut = new VenmoClient( + braintreeClient, + apiClient, + venmoApi, + sharedPrefsWriter, + analyticsParamRepository, + merchantRepository + ); sut.createPaymentAuthRequest(context, request, venmoPaymentAuthRequestCallback); verify(braintreeClient).sendAnalyticsEvent(VenmoAnalytics.TOKENIZE_STARTED,new AnalyticsEventParams()); } @@ -308,9 +355,10 @@ public void createPaymentAuthRequest_sendsAnalyticsEvent() { public void createPaymentAuthRequest_whenShouldVaultIsTrue_persistsVenmoVaultTrue() { BraintreeClient braintreeClient = new MockBraintreeClientBuilder() .configuration(venmoEnabledConfiguration) - .authorizationSuccess(clientToken) .build(); + when(merchantRepository.getAuthorization()).thenReturn(clientToken); + VenmoApi venmoApi = new MockVenmoApiBuilder() .createPaymentContextSuccess("venmo-payment-context-id") .build(); @@ -319,8 +367,14 @@ public void createPaymentAuthRequest_whenShouldVaultIsTrue_persistsVenmoVaultTru request.setProfileId(null); request.setShouldVault(true); - VenmoClient sut = - new VenmoClient(braintreeClient, apiClient, venmoApi, sharedPrefsWriter, analyticsParamRepository); + VenmoClient sut = new VenmoClient( + braintreeClient, + apiClient, + venmoApi, + sharedPrefsWriter, + analyticsParamRepository, + merchantRepository + ); sut.createPaymentAuthRequest(context, request, venmoPaymentAuthRequestCallback); verify(sharedPrefsWriter).persistVenmoVaultOption(context, true); @@ -330,9 +384,10 @@ public void createPaymentAuthRequest_whenShouldVaultIsTrue_persistsVenmoVaultTru public void createPaymentAuthRequest_whenShouldVaultIsFalse_persistsVenmoVaultFalse() { BraintreeClient braintreeClient = new MockBraintreeClientBuilder() .configuration(venmoEnabledConfiguration) - .authorizationSuccess(clientToken) .build(); + when(merchantRepository.getAuthorization()).thenReturn(clientToken); + VenmoApi venmoApi = new MockVenmoApiBuilder() .createPaymentContextSuccess("venmo-payment-context-id") .build(); @@ -341,8 +396,14 @@ public void createPaymentAuthRequest_whenShouldVaultIsFalse_persistsVenmoVaultFa request.setProfileId(null); request.setShouldVault(false); - VenmoClient sut = - new VenmoClient(braintreeClient, apiClient, venmoApi, sharedPrefsWriter, analyticsParamRepository); + VenmoClient sut = new VenmoClient( + braintreeClient, + apiClient, + venmoApi, + sharedPrefsWriter, + analyticsParamRepository, + merchantRepository + ); sut.createPaymentAuthRequest(context, request, venmoPaymentAuthRequestCallback); verify(sharedPrefsWriter).persistVenmoVaultOption(context, false); @@ -352,9 +413,10 @@ public void createPaymentAuthRequest_whenShouldVaultIsFalse_persistsVenmoVaultFa public void createPaymentAuthRequest_withTokenizationKey_persistsVenmoVaultFalse() { BraintreeClient braintreeClient = new MockBraintreeClientBuilder() .configuration(venmoEnabledConfiguration) - .authorizationSuccess(clientToken) .build(); + when(merchantRepository.getAuthorization()).thenReturn(clientToken); + VenmoApi venmoApi = new MockVenmoApiBuilder() .createPaymentContextSuccess("venmo-payment-context-id") .build(); @@ -363,8 +425,14 @@ public void createPaymentAuthRequest_withTokenizationKey_persistsVenmoVaultFalse request.setProfileId(null); request.setShouldVault(false); - VenmoClient sut = - new VenmoClient(braintreeClient, apiClient, venmoApi, sharedPrefsWriter, analyticsParamRepository); + VenmoClient sut = new VenmoClient( + braintreeClient, + apiClient, + venmoApi, + sharedPrefsWriter, + analyticsParamRepository, + merchantRepository + ); sut.createPaymentAuthRequest(context, request, venmoPaymentAuthRequestCallback); verify(sharedPrefsWriter).persistVenmoVaultOption(context, false); @@ -385,8 +453,14 @@ public void createPaymentAuthRequest_whenVenmoApiError_forwardsErrorToListener_a VenmoRequest request = new VenmoRequest(VenmoPaymentMethodUsage.SINGLE_USE); request.setShouldVault(true); - VenmoClient sut = - new VenmoClient(braintreeClient, apiClient, venmoApi, sharedPrefsWriter, analyticsParamRepository); + VenmoClient sut = new VenmoClient( + braintreeClient, + apiClient, + venmoApi, + sharedPrefsWriter, + analyticsParamRepository, + merchantRepository + ); sut.createPaymentAuthRequest(context, request, venmoPaymentAuthRequestCallback); ArgumentCaptor captor = @@ -402,12 +476,18 @@ public void createPaymentAuthRequest_whenVenmoApiError_forwardsErrorToListener_a public void tokenize_withPaymentContextId_requestFromVenmoApi() { BraintreeClient braintreeClient = new MockBraintreeClientBuilder() .configuration(venmoEnabledConfiguration) - .authorizationSuccess(clientToken) .build(); when(browserSwitchResult.getReturnUrl()).thenReturn(SUCCESS_URL); + when(merchantRepository.getAuthorization()).thenReturn(clientToken); - VenmoClient sut = - new VenmoClient(braintreeClient, apiClient, venmoApi, sharedPrefsWriter, analyticsParamRepository); + VenmoClient sut = new VenmoClient( + braintreeClient, + apiClient, + venmoApi, + sharedPrefsWriter, + analyticsParamRepository, + merchantRepository + ); sut.tokenize(paymentAuthResult, venmoTokenizeCallback); @@ -421,12 +501,18 @@ public void tokenize_withPaymentContextId_requestFromVenmoApi() { public void tokenize_withPaymentAuthResult_whenUserCanceled_returnsCancelAndSendsAnalytics() { BraintreeClient braintreeClient = new MockBraintreeClientBuilder() .configuration(venmoEnabledConfiguration) - .authorizationSuccess(clientToken) .build(); when(browserSwitchResult.getReturnUrl()).thenReturn(CANCEL_URL); + when(merchantRepository.getAuthorization()).thenReturn(clientToken); - VenmoClient sut = - new VenmoClient(braintreeClient, apiClient, venmoApi, sharedPrefsWriter, analyticsParamRepository); + VenmoClient sut = new VenmoClient( + braintreeClient, + apiClient, + venmoApi, + sharedPrefsWriter, + analyticsParamRepository, + merchantRepository + ); sut.tokenize(paymentAuthResult, venmoTokenizeCallback); @@ -444,17 +530,23 @@ public void tokenize_onGraphQLPostSuccess_returnsNonceToListener_andSendsAnalyti throws JSONException { BraintreeClient braintreeClient = new MockBraintreeClientBuilder() .configuration(venmoEnabledConfiguration) - .authorizationSuccess(clientToken) .build(); when(browserSwitchResult.getReturnUrl()).thenReturn(SUCCESS_URL); + when(merchantRepository.getAuthorization()).thenReturn(clientToken); VenmoApi venmoApi = new MockVenmoApiBuilder() .createNonceFromPaymentContextSuccess(VenmoAccountNonce.fromJSON( new JSONObject(Fixtures.PAYMENT_METHODS_VENMO_ACCOUNT_RESPONSE))) .build(); - VenmoClient sut = - new VenmoClient(braintreeClient, apiClient, venmoApi, sharedPrefsWriter, analyticsParamRepository); + VenmoClient sut = new VenmoClient( + braintreeClient, + apiClient, + venmoApi, + sharedPrefsWriter, + analyticsParamRepository, + merchantRepository + ); sut.tokenize(paymentAuthResult, venmoTokenizeCallback); @@ -475,17 +567,23 @@ public void tokenize_onGraphQLPostFailure_forwardsExceptionToListener_andSendsAn BraintreeException graphQLError = new BraintreeException("graphQL error"); BraintreeClient braintreeClient = new MockBraintreeClientBuilder() .configuration(venmoEnabledConfiguration) - .authorizationSuccess(clientToken) .sendGraphQLPOSTErrorResponse(graphQLError) .build(); when(browserSwitchResult.getReturnUrl()).thenReturn(SUCCESS_URL); + when(merchantRepository.getAuthorization()).thenReturn(clientToken); VenmoApi venmoApi = new MockVenmoApiBuilder() .createNonceFromPaymentContextError(graphQLError) .build(); - VenmoClient sut = - new VenmoClient(braintreeClient, apiClient, venmoApi, sharedPrefsWriter, analyticsParamRepository); + VenmoClient sut = new VenmoClient( + braintreeClient, + apiClient, + venmoApi, + sharedPrefsWriter, + analyticsParamRepository, + merchantRepository + ); sut.tokenize(paymentAuthResult, venmoTokenizeCallback); @@ -502,10 +600,9 @@ public void tokenize_onGraphQLPostFailure_forwardsExceptionToListener_andSendsAn public void tokenize_withPaymentContext_performsVaultRequestIfRequestPersisted() { BraintreeClient braintreeClient = new MockBraintreeClientBuilder() .configuration(venmoEnabledConfiguration) - .authorizationSuccess(clientToken) .build(); - when(braintreeClient.getApplicationContext()).thenReturn(context); when(browserSwitchResult.getReturnUrl()).thenReturn(SUCCESS_URL); + when(merchantRepository.getAuthorization()).thenReturn(clientToken); VenmoAccountNonce nonce = mock(VenmoAccountNonce.class); when(nonce.getString()).thenReturn("some-nonce"); @@ -520,8 +617,14 @@ public void tokenize_withPaymentContext_performsVaultRequestIfRequestPersisted() when(sharedPrefsWriter.getVenmoVaultOption(context)).thenReturn(true); - VenmoClient sut = - new VenmoClient(braintreeClient, apiClient, venmoApi, sharedPrefsWriter, analyticsParamRepository); + VenmoClient sut = new VenmoClient( + braintreeClient, + apiClient, + venmoApi, + sharedPrefsWriter, + analyticsParamRepository, + merchantRepository + ); sut.tokenize(paymentAuthResult, venmoTokenizeCallback); @@ -530,13 +633,18 @@ public void tokenize_withPaymentContext_performsVaultRequestIfRequestPersisted() @Test public void tokenize_postsPaymentMethodNonceOnSuccess() { - BraintreeClient braintreeClient = new MockBraintreeClientBuilder() - .authorizationSuccess(clientToken) - .build(); + BraintreeClient braintreeClient = new MockBraintreeClientBuilder().build(); when(browserSwitchResult.getReturnUrl()).thenReturn(SUCCESS_URL); + when(merchantRepository.getAuthorization()).thenReturn(clientToken); - VenmoClient sut = - new VenmoClient(braintreeClient, apiClient, venmoApi, sharedPrefsWriter, analyticsParamRepository); + VenmoClient sut = new VenmoClient( + braintreeClient, + apiClient, + venmoApi, + sharedPrefsWriter, + analyticsParamRepository, + merchantRepository + ); sut.tokenize(paymentAuthResult, venmoTokenizeCallback); @@ -548,10 +656,9 @@ public void tokenize_postsPaymentMethodNonceOnSuccess() { public void tokenize_performsVaultRequestIfRequestPersisted() throws JSONException { BraintreeClient braintreeClient = new MockBraintreeClientBuilder() .configuration(venmoEnabledConfiguration) - .authorizationSuccess(clientToken) .build(); - when(braintreeClient.getApplicationContext()).thenReturn(context); when(browserSwitchResult.getReturnUrl()).thenReturn(SUCCESS_URL); + when(merchantRepository.getAuthorization()).thenReturn(clientToken); VenmoApi venmoApi = new MockVenmoApiBuilder() .createNonceFromPaymentContextSuccess(VenmoAccountNonce.fromJSON( @@ -564,8 +671,14 @@ public void tokenize_performsVaultRequestIfRequestPersisted() throws JSONExcepti when(sharedPrefsWriter.getVenmoVaultOption(context)).thenReturn(true); - VenmoClient sut = - new VenmoClient(braintreeClient, apiClient, venmoApi, sharedPrefsWriter, analyticsParamRepository); + VenmoClient sut = new VenmoClient( + braintreeClient, + apiClient, + venmoApi, + sharedPrefsWriter, + analyticsParamRepository, + merchantRepository + ); sut.tokenize(paymentAuthResult, venmoTokenizeCallback); @@ -575,16 +688,19 @@ public void tokenize_performsVaultRequestIfRequestPersisted() throws JSONExcepti @Test public void tokenize_doesNotPerformRequestIfTokenizationKeyUsed() { - BraintreeClient braintreeClient = new MockBraintreeClientBuilder() - - .authorizationSuccess(tokenizationKey) - .build(); + BraintreeClient braintreeClient = new MockBraintreeClientBuilder().build(); when(browserSwitchResult.getReturnUrl()).thenReturn(SUCCESS_URL); - when(sharedPrefsWriter.getVenmoVaultOption(context)).thenReturn(true); + when(merchantRepository.getAuthorization()).thenReturn(tokenizationKey); - VenmoClient sut = - new VenmoClient(braintreeClient, apiClient, venmoApi, sharedPrefsWriter, analyticsParamRepository); + VenmoClient sut = new VenmoClient( + braintreeClient, + apiClient, + venmoApi, + sharedPrefsWriter, + analyticsParamRepository, + merchantRepository + ); sut.tokenize(paymentAuthResult, venmoTokenizeCallback); @@ -595,10 +711,9 @@ public void tokenize_doesNotPerformRequestIfTokenizationKeyUsed() { @Test public void tokenize_withSuccessfulVaultCall_forwardsResultToActivityResultListener_andSendsAnalytics() { BraintreeClient braintreeClient = new MockBraintreeClientBuilder() - .authorizationSuccess(clientToken) .build(); - when(braintreeClient.getApplicationContext()).thenReturn(context); when(browserSwitchResult.getReturnUrl()).thenReturn(SUCCESS_URL_WITHOUT_RESOURCE_ID); + when(merchantRepository.getAuthorization()).thenReturn(clientToken); VenmoAccountNonce venmoAccountNonce = mock(VenmoAccountNonce.class); @@ -608,8 +723,14 @@ public void tokenize_withSuccessfulVaultCall_forwardsResultToActivityResultListe when(sharedPrefsWriter.getVenmoVaultOption(context)).thenReturn(true); - VenmoClient sut = - new VenmoClient(braintreeClient, apiClient, venmoApi, sharedPrefsWriter, analyticsParamRepository); + VenmoClient sut = new VenmoClient( + braintreeClient, + apiClient, + venmoApi, + sharedPrefsWriter, + analyticsParamRepository, + merchantRepository + ); sut.tokenize(paymentAuthResult, venmoTokenizeCallback); @@ -627,12 +748,10 @@ public void tokenize_withSuccessfulVaultCall_forwardsResultToActivityResultListe public void tokenize_withPaymentContext_withSuccessfulVaultCall_forwardsNonceToCallback_andSendsAnalytics() throws JSONException { BraintreeClient braintreeClient = new MockBraintreeClientBuilder() - .authorizationSuccess(clientToken) - .sendGraphQLPOSTSuccessfulResponse( - Fixtures.VENMO_GRAPHQL_GET_PAYMENT_CONTEXT_RESPONSE) + .sendGraphQLPOSTSuccessfulResponse(Fixtures.VENMO_GRAPHQL_GET_PAYMENT_CONTEXT_RESPONSE) .build(); - when(braintreeClient.getApplicationContext()).thenReturn(context); when(browserSwitchResult.getReturnUrl()).thenReturn(SUCCESS_URL); + when(merchantRepository.getAuthorization()).thenReturn(clientToken); VenmoAccountNonce venmoAccountNonce = VenmoAccountNonce.fromJSON( new JSONObject(Fixtures.PAYMENT_METHODS_VENMO_ACCOUNT_RESPONSE)); @@ -644,8 +763,14 @@ public void tokenize_withPaymentContext_withSuccessfulVaultCall_forwardsNonceToC when(sharedPrefsWriter.getVenmoVaultOption(context)).thenReturn(true); - VenmoClient sut = - new VenmoClient(braintreeClient, apiClient, venmoApi, sharedPrefsWriter, analyticsParamRepository); + VenmoClient sut = new VenmoClient( + braintreeClient, + apiClient, + venmoApi, + sharedPrefsWriter, + analyticsParamRepository, + merchantRepository + ); sut.tokenize(paymentAuthResult, venmoTokenizeCallback); @@ -661,11 +786,9 @@ public void tokenize_withPaymentContext_withSuccessfulVaultCall_forwardsNonceToC @Test public void tokenize_withFailedVaultCall_forwardsErrorToActivityResultListener_andSendsAnalytics() { - BraintreeClient braintreeClient = new MockBraintreeClientBuilder() - .authorizationSuccess(clientToken) - .build(); - when(braintreeClient.getApplicationContext()).thenReturn(context); + BraintreeClient braintreeClient = new MockBraintreeClientBuilder().build(); when(browserSwitchResult.getReturnUrl()).thenReturn(SUCCESS_URL_WITHOUT_RESOURCE_ID); + when(merchantRepository.getAuthorization()).thenReturn(clientToken); Exception error = new Exception("error"); @@ -675,8 +798,14 @@ public void tokenize_withFailedVaultCall_forwardsErrorToActivityResultListener_a when(sharedPrefsWriter.getVenmoVaultOption(context)).thenReturn(true); - VenmoClient sut = - new VenmoClient(braintreeClient, apiClient, venmoApi, sharedPrefsWriter, analyticsParamRepository); + VenmoClient sut = new VenmoClient( + braintreeClient, + apiClient, + venmoApi, + sharedPrefsWriter, + analyticsParamRepository, + merchantRepository + ); sut.tokenize(paymentAuthResult, venmoTokenizeCallback); @@ -697,12 +826,10 @@ public void tokenize_withFailedVaultCall_forwardsErrorToActivityResultListener_a public void tokenize_withPaymentContext_withFailedVaultCall_forwardsErrorToCallback_andSendsAnalytics() throws JSONException { BraintreeClient braintreeClient = new MockBraintreeClientBuilder() - .authorizationSuccess(clientToken) - .sendGraphQLPOSTSuccessfulResponse( - Fixtures.VENMO_GRAPHQL_GET_PAYMENT_CONTEXT_RESPONSE) + .sendGraphQLPOSTSuccessfulResponse(Fixtures.VENMO_GRAPHQL_GET_PAYMENT_CONTEXT_RESPONSE) .build(); - when(braintreeClient.getApplicationContext()).thenReturn(context); when(browserSwitchResult.getReturnUrl()).thenReturn(SUCCESS_URL); + when(merchantRepository.getAuthorization()).thenReturn(clientToken); VenmoAccountNonce venmoAccountNonce = VenmoAccountNonce.fromJSON( new JSONObject(Fixtures.PAYMENT_METHODS_VENMO_ACCOUNT_RESPONSE)); @@ -715,8 +842,14 @@ public void tokenize_withPaymentContext_withFailedVaultCall_forwardsErrorToCallb when(sharedPrefsWriter.getVenmoVaultOption(context)).thenReturn(true); - VenmoClient sut = - new VenmoClient(braintreeClient, apiClient, venmoApi, sharedPrefsWriter, analyticsParamRepository); + VenmoClient sut = new VenmoClient( + braintreeClient, + apiClient, + venmoApi, + sharedPrefsWriter, + analyticsParamRepository, + merchantRepository + ); sut.tokenize(paymentAuthResult, venmoTokenizeCallback);