Set Up Your Client

Choose an SDK preference:

The Braintree Android SDK helps you accept payments in your Android app.

Requirements

  • Android API >= 16

Installation

There are several ways to include Braintree in your project, but Gradle is the preferred build system for working with the Braintree Android SDK.

Build systems

Gradle

In your build.gradle, add the following:

dependencies {
  compile 'com.braintreepayments.api:braintree:2.+'
}

Then, continue to Browser switch setup below.

Maven

You must be using android-maven-plugin 4.1.0 or higher.

In your pom.xml add the following:

<dependencies>
  <dependency>
    <groupId>com.braintreepayments.api</groupId>
    <artifactId>braintree</artifactId>
    <version>[2.0.0,)</version>
    <type>aar</type>
    <configuration>
      <manifestMergeLibraries>true</manifestMergeLibraries>
    </configuration>
  </dependency>
</dependencies>

Then, continue to Browser switch setup below.

Browser switch setup

For PayPal a URL scheme must be defined to accept return browser switches.

Edit your AndroidManifest.xml to include BraintreeBrowserSwitchActivity and set the android:scheme:

<activity android:name="com.braintreepayments.api.BraintreeBrowserSwitchActivity"
    android:launchMode="singleTask">
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="${applicationId}.braintree" />
    </intent-filter>
</activity>
important

Your app's URL scheme must begin with your app's package ID and end with .braintree. For example, if the Package ID is com.your-company.your-app, then your URL scheme should be com.your-company.your-app.braintree. ${applicationId} is automatically applied with your app's package when using Gradle.

Note: The scheme you define must use all lowercase letters. If your package contains underscores, the underscores should be removed when specifying the scheme in your Android Manifest.

Initialization

The setup of BraintreeFragment is simply a call to BraintreeFragment.newInstance(activity, authorization) with the current Activity and a client token.

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  try {
    mBraintreeFragment = BraintreeFragment.newInstance(this, mAuthorization);
    // mBraintreeFragment is ready to use!
  } catch (InvalidArgumentException e) {
    // There was an issue with your authorization string.
  }
}

This static method will:

  • Prepare a BraintreeFragment.
  • Add the BraintreeFragment to the given activity.
  • Check for validity on the given mAuthorization string.

Register listeners

Braintree provides several interfaces which will be called when events occur. Any Braintree interface that BraintreeFragment's host Activity implements will be automatically managed for you. However, if you wish to manage the Braintree listeners yourself, use BraintreeFragment#addListener. In this case, be sure to use BraintreeFragment#removeListener to clean up in the event of a state change to avoid memory leaks.

The following interfaces may be implemented to receive events:

  • PaymentMethodNonceCreatedListener is called when a PaymentMethodNonce has been successfully tokenized. Send the nonce from this PaymentMethodNonce to your server to create a transaction.

    @Override
    public void onPaymentMethodNonceCreated(PaymentMethodNonce paymentMethodNonce) {
      // Send this nonce to your server
      String nonce = paymentMethodNonce.getNonce();
    }
  • ConfigurationListener is called after configuration has been retrieved from Braintree. The Configuration class contains information about your current environment as well as information about which payment methods are currently available.

  • BraintreeCancelListener is called when BraintreeFragment is notified of a Activity#RESULT_CANCELED result code in Fragment#onActivityResult.

    @Override
    public void onCancel(int requestCode) {
      // Use this to handle a canceled activity, if the given requestCode is important.
      // You may want to use this callback to hide loading indicators, and prepare your UI for input
    }
  • BraintreeErrorListener is called when there has been an error. ErrorWithResponse is called when there are validations errors with the request. Exception is thrown when an error such as a network issue or server error occurs.

    @Override
    public void onError(Exception error) {
      if (error instanceof ErrorWithResponse) {
        ErrorWithResponse errorWithResponse = (ErrorWithResponse) error;
        BraintreeError cardErrors = errorWithResponse.errorFor("creditCard");
        if (cardErrors != null) {
          // There is an issue with the credit card.
          BraintreeError expirationMonthError = cardErrors.errorFor("expirationMonth");
          if (expirationMonthError != null) {
            // There is an issue with the expiration month.
            setErrorMessage(expirationMonthError.getMessage());
          }
        }
      }
    }

ProGuard

A ProGuard configuration is provided as part of the Braintree Android SDK. There is no need to add any Braintree specific rules to your ProGuard configuration.

Get a client token

Your server is responsible for generating a client token, which contains the authorization and configuration details that your client needs to initialize the client SDK.

Request the client token from your server, then initialize Braintree and present drop-in UI (this example uses Android Async Http Client to request a client token from your server - adapt to your own setup):

AsyncHttpClient client = new AsyncHttpClient();
client.get("https://your-server/client_token", new TextHttpResponseHandler() {
  @Override
  public void onSuccess(int statusCode, Header[] headers, String clientToken) {
    this.clientToken = clientToken;
  }
});

You should obtain a new client token often, at least as often as your app restarts. For the best experience, you should kick off this network operation before it would block a user interaction.

important

You must generate a client token on your server once per user checkout session. The endpoint we provide in this example is for demonstration purposes only.

PayPal configuration

Invoking Express Checkout

First, make sure you have defined your URL scheme. Then, use PayPal.requestOneTimePayment to start the process. An example integration might look like this:

public void setupBraintreeAndStartExpressCheckout() {
  PayPalRequest request = new PayPalRequest("1")
    .currencyCode("USD")
    .intent(PayPalRequest.INTENT_AUTHORIZE);
  PayPal.requestOneTimePayment(mBraintreeFragment, request);
}

Button

You can provide your own button that starts the PayPal flow.

Initialize BraintreeFragment with your client token to make the request.

yourButton.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View view) {
    setupBraintreeAndStartExpressCheckout();
  }
});

When you receive a callback in onPaymentMethodNonceCreated, you can query the PayPalAccountNonce object you get back for specific customer information.

@Override
public void onPaymentMethodNonceCreated(PaymentMethodNonce paymentMethodNonce) {
  // Send nonce to server
  String nonce = paymentMethodNonce.getNonce();
  if (paymentMethodNonce instanceof PayPalAccountNonce) {
    PayPalAccountNonce payPalAccountNonce = (PayPalAccountNonce)paymentMethodNonce;

    // Access additional information
    String email = payPalAccountNonce.getEmail();
    String firstName = payPalAccountNonce.getFirstName();
    String lastName = payPalAccountNonce.getLastName();
    String phone = payPalAccountNonce.getPhone();

    // See PostalAddress.java for details
    PostalAddress billingAddress = payPalAccountNonce.getBillingAddress();
    PostalAddress shippingAddress = payPalAccountNonce.getShippingAddress();
  }
}

Supported currencies

The currencyCode field determines the currency of the transaction displayed to the customer in the Express Checkout flow. You'll pass the same currency with the transaction request on the server side.

note

When you first create your PayPal business account, you'll be able to pass only the default currency for the country associated with your business account. If you'd like to display transactions in additional currencies, see the multi-currency setup section below.

See the full list of supported currencies for Express Checkout.

Multi-currency setup

In order to display transactions in currencies other than the default currency for the country associated with your business account, you'll need to add them to your account as follows:

  1. Access the My Apps & Credentials page in your PayPal Developer Dashboard
    • Select your Live account
    • View currently enabled currencies for your account
    • Select currencies you would like to add and click the Add Currencies button
  2. Access the My Money page of your PayPal business account

Once a currency is enabled, you can begin passing it in the currencyCode field.

note

Currencies can't be removed from your Developer Dashboard once they have been added. If you no longer wish to display a particular currency, you can choose not to pass it in the currencyCode field. You can close the currency in your business account, if you'd like.

Send payment method nonce to server

Send the resulting payment method nonce to your server (again, this example uses Android Async Http Client - adapt to your own setup):

void postNonceToServer(String nonce) {
  AsyncHttpClient client = new AsyncHttpClient();
  RequestParams params = new RequestParams();
  params.put("payment_method_nonce", nonce);
  client.post("http://your-server/checkout", params,
    new AsyncHttpResponseHandler() {
      // Your implementation here
    }
  );
}

A PaymentMethodNonce will be returned in your PaymentMethodNonceCreatedListener.

See also

Next Page: Set Up Your Server →

Still Have Questions?

Browse our support options or submit a question to our technical support team.