Search in sources :

Example 46 with Configuration

use of com.braintreepayments.api.models.Configuration in project braintree_android by braintree.

the class AmericanExpress method getRewardsBalance.

/**
 * Gets the rewards balance associated with a Braintree nonce. Only for American Express cards.
 *
 * @param fragment the {@link BraintreeFragment} This fragment will also be responsible
 * for handling callbacks to it's listeners
 * @param nonce A nonce representing a card that will be used to look up the rewards balance
 * @param currencyIsoCode The currencyIsoCode to use. Example: 'USD'
 */
public static void getRewardsBalance(final BraintreeFragment fragment, final String nonce, final String currencyIsoCode) {
    fragment.waitForConfiguration(new ConfigurationListener() {

        @Override
        public void onConfigurationFetched(Configuration configuration) {
            String getRewardsBalanceUrl = Uri.parse(AMEX_REWARDS_BALANCE_PATH).buildUpon().appendQueryParameter("paymentMethodNonce", nonce).appendQueryParameter("currencyIsoCode", currencyIsoCode).build().toString();
            fragment.sendAnalyticsEvent("amex.rewards-balance.start");
            fragment.getHttpClient().get(getRewardsBalanceUrl, new HttpResponseCallback() {

                @Override
                public void success(String responseBody) {
                    fragment.sendAnalyticsEvent("amex.rewards-balance.success");
                    try {
                        fragment.postAmericanExpressCallback(AmericanExpressRewardsBalance.fromJson(responseBody));
                    } catch (JSONException e) {
                        fragment.sendAnalyticsEvent("amex.rewards-balance.parse.failed");
                        fragment.postCallback(e);
                    }
                }

                @Override
                public void failure(Exception exception) {
                    fragment.postCallback(exception);
                    fragment.sendAnalyticsEvent("amex.rewards-balance.error");
                }
            });
        }
    });
}
Also used : ConfigurationListener(com.braintreepayments.api.interfaces.ConfigurationListener) Configuration(com.braintreepayments.api.models.Configuration) JSONException(org.json.JSONException) HttpResponseCallback(com.braintreepayments.api.interfaces.HttpResponseCallback) JSONException(org.json.JSONException)

Example 47 with Configuration

use of com.braintreepayments.api.models.Configuration in project braintree_android by braintree.

the class AndroidPay method requestAndroidPay.

/**
 * @deprecated Android Pay is deprecated, use {@link GooglePayment} instead. For more information see the
 * <a href="https://developers.braintreepayments.com/guides/pay-with-google/overview">documentation</a>
 *
 * Launch an Android Pay masked wallet request. This method will show the payment instrument
 * chooser to the user.
 *
 * @param fragment The current {@link BraintreeFragment}.
 * @param cart The cart representation with price, currency code, and optionally items.
 * @param shippingAddressRequired {@code true} if this request requires a shipping address, {@code false} otherwise.
 * @param phoneNumberRequired {@code true} if this request requires a phone number, {@code false} otherwise.
 * @param allowedCountries ISO 3166-2 country codes that shipping is allowed to.
 */
@Deprecated
public static void requestAndroidPay(final BraintreeFragment fragment, @NonNull final Cart cart, final boolean shippingAddressRequired, final boolean phoneNumberRequired, final ArrayList<CountrySpecification> allowedCountries) {
    fragment.sendAnalyticsEvent("android-pay.selected");
    if (!validateManifest(fragment.getApplicationContext())) {
        fragment.postCallback(new BraintreeException("AndroidPayActivity was not found in the Android manifest, " + "or did not have a theme of R.style.bt_transparent_activity"));
        fragment.sendAnalyticsEvent("android-pay.failed");
        return;
    }
    if (cart == null) {
        fragment.postCallback(new BraintreeException("Cannot pass null cart to performMaskedWalletRequest"));
        fragment.sendAnalyticsEvent("android-pay.failed");
        return;
    }
    fragment.waitForConfiguration(new ConfigurationListener() {

        @Override
        public void onConfigurationFetched(Configuration configuration) {
            fragment.sendAnalyticsEvent("android-pay.started");
            Intent intent = new Intent(fragment.getApplicationContext(), AndroidPayActivity.class).putExtra(EXTRA_ENVIRONMENT, GooglePayment.getEnvironment(configuration.getAndroidPay())).putExtra(EXTRA_MERCHANT_NAME, configuration.getAndroidPay().getDisplayName()).putExtra(EXTRA_CART, cart).putExtra(EXTRA_TOKENIZATION_PARAMETERS, GooglePayment.getTokenizationParameters(fragment)).putIntegerArrayListExtra(EXTRA_ALLOWED_CARD_NETWORKS, GooglePayment.getAllowedCardNetworks(fragment)).putExtra(EXTRA_SHIPPING_ADDRESS_REQUIRED, shippingAddressRequired).putExtra(EXTRA_PHONE_NUMBER_REQUIRED, phoneNumberRequired).putParcelableArrayListExtra(EXTRA_ALLOWED_COUNTRIES, allowedCountries).putExtra(EXTRA_REQUEST_TYPE, AUTHORIZE);
            fragment.startActivityForResult(intent, BraintreeRequestCodes.ANDROID_PAY);
        }
    });
}
Also used : ConfigurationListener(com.braintreepayments.api.interfaces.ConfigurationListener) Configuration(com.braintreepayments.api.models.Configuration) BraintreeException(com.braintreepayments.api.exceptions.BraintreeException) Intent(android.content.Intent)

Example 48 with Configuration

use of com.braintreepayments.api.models.Configuration in project braintree_android by braintree.

the class BraintreeFragment method fetchConfiguration.

@VisibleForTesting
protected void fetchConfiguration() {
    if (getConfiguration() != null || ConfigurationManager.isFetchingConfiguration() || mAuthorization == null || mHttpClient == null) {
        return;
    }
    if (mConfigurationRequestAttempts >= 3) {
        postCallback(new ConfigurationException("Configuration retry limit has been exceeded. Create a new " + "BraintreeFragment and try again."));
        return;
    }
    mConfigurationRequestAttempts++;
    ConfigurationManager.getConfiguration(this, new ConfigurationListener() {

        @Override
        public void onConfigurationFetched(Configuration configuration) {
            setConfiguration(configuration);
            postConfigurationCallback();
            flushCallbacks();
        }
    }, new BraintreeResponseListener<Exception>() {

        @Override
        public void onResponse(final Exception e) {
            final ConfigurationException exception = new ConfigurationException("Request for configuration has failed: " + e.getMessage() + ". " + "Future requests will retry up to 3 times", e);
            postCallback(exception);
            postOrQueueCallback(new QueuedCallback() {

                @Override
                public boolean shouldRun() {
                    return mConfigurationErrorListener != null;
                }

                @Override
                public void run() {
                    mConfigurationErrorListener.onResponse(exception);
                }
            });
            flushCallbacks();
        }
    });
}
Also used : ConfigurationListener(com.braintreepayments.api.interfaces.ConfigurationListener) Configuration(com.braintreepayments.api.models.Configuration) ConfigurationException(com.braintreepayments.api.exceptions.ConfigurationException) BraintreeException(com.braintreepayments.api.exceptions.BraintreeException) JSONException(org.json.JSONException) InvalidArgumentException(com.braintreepayments.api.exceptions.InvalidArgumentException) GoogleApiClientException(com.braintreepayments.api.exceptions.GoogleApiClientException) ConfigurationException(com.braintreepayments.api.exceptions.ConfigurationException) QueuedCallback(com.braintreepayments.api.interfaces.QueuedCallback) VisibleForTesting(android.support.annotation.VisibleForTesting)

Example 49 with Configuration

use of com.braintreepayments.api.models.Configuration in project braintree_android by braintree.

the class ConfigurationManager method getConfiguration.

static void getConfiguration(final BraintreeFragment fragment, @NonNull final ConfigurationListener listener, @NonNull final BraintreeResponseListener<Exception> errorListener) {
    final String configUrl = Uri.parse(fragment.getAuthorization().getConfigUrl()).buildUpon().appendQueryParameter("configVersion", "3").build().toString();
    Configuration cachedConfig = getCachedConfiguration(fragment.getApplicationContext(), configUrl + fragment.getAuthorization().getBearer());
    if (cachedConfig != null) {
        listener.onConfigurationFetched(cachedConfig);
    } else {
        sFetchingConfiguration = true;
        fragment.getHttpClient().get(configUrl, new HttpResponseCallback() {

            @Override
            public void success(String responseBody) {
                try {
                    Configuration configuration = Configuration.fromJson(responseBody);
                    cacheConfiguration(fragment.getApplicationContext(), configUrl + fragment.getAuthorization().getBearer(), configuration);
                    sFetchingConfiguration = false;
                    listener.onConfigurationFetched(configuration);
                } catch (final JSONException e) {
                    sFetchingConfiguration = false;
                    errorListener.onResponse(e);
                }
            }

            @Override
            public void failure(final Exception exception) {
                sFetchingConfiguration = false;
                errorListener.onResponse(exception);
            }
        });
    }
}
Also used : Configuration(com.braintreepayments.api.models.Configuration) JSONException(org.json.JSONException) HttpResponseCallback(com.braintreepayments.api.interfaces.HttpResponseCallback) JSONException(org.json.JSONException)

Example 50 with Configuration

use of com.braintreepayments.api.models.Configuration in project braintree_android by braintree.

the class IdealUnitTest method pollForCompletion_pollsUntilMaxRetryCountExceeded.

@Test(timeout = 5000)
public void pollForCompletion_pollsUntilMaxRetryCountExceeded() throws InterruptedException, JSONException, InvalidArgumentException {
    Configuration configuration = new TestConfigurationBuilder().ideal(new TestIdealConfigurationBuilder().routeId("some-route-id")).braintreeApi(new TestBraintreeApiConfigurationBuilder().accessToken("access-token").url("http://api.braintree.com")).buildConfiguration();
    final BraintreeFragment fragment = new MockFragmentBuilder().authorization(Authorization.fromString(stringFromFixture("client_token.json"))).configuration(configuration).build();
    BraintreeApiHttpClient apiHttpClient = mock(BraintreeApiHttpClient.class);
    when(fragment.getBraintreeApiHttpClient()).thenReturn(apiHttpClient);
    final String resultFixture = stringFromFixture("payment_methods/pending_ideal_bank_payment.json");
    final CountDownLatch latch = new CountDownLatch(2);
    doAnswer(new Answer() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            HttpResponseCallback callback = (HttpResponseCallback) invocation.getArguments()[1];
            callback.success(resultFixture);
            latch.countDown();
            return null;
        }
    }).when(apiHttpClient).get(eq("/ideal-payments/ideal_payment_id/status"), any(HttpResponseCallback.class));
    IdealResult idealResult = IdealResult.fromJson(resultFixture);
    putResultIdInPrefs(idealResult.getId());
    Ideal.pollForCompletion(fragment, idealResult.getId(), 1, 1000);
    // Two retries = three calls to latch.countDown
    latch.await();
}
Also used : Configuration(com.braintreepayments.api.models.Configuration) TestConfigurationBuilder(com.braintreepayments.testutils.TestConfigurationBuilder) CountDownLatch(java.util.concurrent.CountDownLatch) HttpResponseCallback(com.braintreepayments.api.interfaces.HttpResponseCallback) BraintreeApiHttpClient(com.braintreepayments.api.internal.BraintreeApiHttpClient) Answer(org.mockito.stubbing.Answer) PowerMockito.doAnswer(org.powermock.api.mockito.PowerMockito.doAnswer) TestBraintreeApiConfigurationBuilder(com.braintreepayments.testutils.TestConfigurationBuilder.TestBraintreeApiConfigurationBuilder) TestIdealConfigurationBuilder(com.braintreepayments.testutils.TestConfigurationBuilder.TestIdealConfigurationBuilder) InvocationOnMock(org.mockito.invocation.InvocationOnMock) JSONObject(org.json.JSONObject) IdealResult(com.braintreepayments.api.models.IdealResult) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

Configuration (com.braintreepayments.api.models.Configuration)84 Test (org.junit.Test)66 ConfigurationListener (com.braintreepayments.api.interfaces.ConfigurationListener)36 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)35 InvalidArgumentException (com.braintreepayments.api.exceptions.InvalidArgumentException)19 JSONException (org.json.JSONException)19 Authorization (com.braintreepayments.api.models.Authorization)14 Intent (android.content.Intent)13 HttpResponseCallback (com.braintreepayments.api.interfaces.HttpResponseCallback)13 TestConfigurationBuilder (com.braintreepayments.testutils.TestConfigurationBuilder)12 AuthorizationRequest (com.paypal.android.sdk.onetouch.core.AuthorizationRequest)11 BillingAgreementRequest (com.paypal.android.sdk.onetouch.core.BillingAgreementRequest)11 CheckoutRequest (com.paypal.android.sdk.onetouch.core.CheckoutRequest)11 JSONObject (org.json.JSONObject)11 UnexpectedException (com.braintreepayments.api.exceptions.UnexpectedException)10 SharedPreferencesHelper.writeMockConfiguration (com.braintreepayments.testutils.SharedPreferencesHelper.writeMockConfiguration)10 Request (com.paypal.android.sdk.onetouch.core.Request)10 Bundle (android.os.Bundle)9 BraintreeFragmentTestUtils.getMockFragmentWithConfiguration (com.braintreepayments.api.BraintreeFragmentTestUtils.getMockFragmentWithConfiguration)6 BraintreeFragmentTestUtils.getFragmentWithConfiguration (com.braintreepayments.api.BraintreeFragmentTestUtils.getFragmentWithConfiguration)5