Braintree for Mobile App: Tips on Integration

Braintree for Mobile App: Tips on Integration
Braintree for Mobile App: Tips on Integration

People don’t like problems while shopping. And if they encounter one in your mobile app when paying for their order, they are likely to never make this purchase. The competition in ecommerce now is really intense, and your customers typically have lots of alternatives. Once the payment system is too inconvenient for your customers, they will find a place they can make a quick and convenient payment.

That’s why your app needs to provide the best conditions, that will make your customers comfortable when parting with their money.

The global market of online mobile payments can offer you dozens of payment processors, that allow you to choose the best for your business. They all feature different conditions, have different coverage and fees.

Choosing a right mobile app payment gateway can be a real challenge as you need to take many aspects into account. Security, UI and fees for merchants are three most important criteria for your choice.

In this article we will be discussing Braintree and share our experience with integrating it into both Android and iOS. Let’s see how Braintree works first, and why we think it might be a good solution for your ecommerce app.

How Braintree Works

Braintree is a payment processor that is owned by PayPal. It is considered to be more flexible and convenient than its owner. It allowed it to gain popularity among retailers and mobile app owners.

Braintree works great for businesses at any scale, whether it’s small or big. Your customers will be able to enjoy a bunch of payment methods to choose from, as Braintree accepts credit and debit cards, PayPal, Apple Pay, Venmo, Android pay, and Bitcoins!

No wonder, that many big companies like Airbnb, Uber and American Airlines chose Braintree to handle payments from their users and customers. Braintree works worldwide and allows to make payments from any device.

Braintree’s fees are 2.9% of each transaction + $0.30 per transaction.

If you want to test how Braintree works in your application, you can do it with a help of a sandbox.

Braintree for iOS

This tutorial will allow you to integrate Braintree into your iOS app.

  1. Gather all payment info from customers

You can use different ways to collect this information with a Braintree’s SDK.

  • Add Drop-in UI to get a checkout for PayPal and credit card payments by adding the Drop-in UI. You’ll need only a few lines of code to do it.
  • In case you already have a cheсkout, add buttons for PayPal, Apple Pay, Android Pay, and Venmo. This will allow you to accept more types of payments.
  • Use credit card tokenization and save your customer’s card info if you have your own UI for checkout.
  1. Set up the iOS client


  1. First, you need to add the BraintreeDropIn pod to your podfile.
  2. Then your app should request a client token from your server:

func fetchClientToken() {

// TODO: Switch this URL to your own authenticated API

let clientTokenURL = NSURL(string: “”)!

let clientTokenRequest = NSMutableURLRequest(url: clientTokenURL as URL)

   clientTokenRequest.setValue(“text/plain”, forHTTPHeaderField: “Accept”)

URLSession.shared.dataTask(with: clientTokenRequest as URLRequest) { (data, response, error) -> Void in

    // TODO: Handle errors

    let clientToken = String(data: data!, encoding: String.Encoding.utf8)

    // As an example, you may wish to present Drop-in at this point.

    // Continue to the next section to learn more…



  1. Each time your app launches, you’ll need to obtain a new token. You should avoid blocking user interaction, and for that you need to start this network operation before blocking happens.
  2. Add the import statements to any class with the help of Braintree:

import BraintreeDropIn

import Braintree

  1. Get started easily and use Drop-in. It provides a fully fledged payment experience out of the box. Another way to do it is to create UI on your own and then tokenize the info directly. Add an action on some button to do so:

func showDropIn(clientTokenOrTokenizationKey: String) {

let request =  BTDropInRequest()

let dropIn = BTDropInController(authorization: clientTokenOrTokenizationKey, request: request)

{ (controller, result, error) in

    if (error != nil) {


    } else if (result?.isCancelled == true) {


    } else if let result = result {

        // Use the BTDropInResult properties to update your UI

        // result.paymentOptionType

        // result.paymentMethod

        // result.paymentIcon

        // result.paymentDescription


    controller.dismiss(animated: true, completion: nil)


self.present(dropIn!, animated: true, completion: nil)


Send the payment method nonce you got as a result, to your server (don’t forget to adapt this to your own setup):

func postNonceToServer(paymentMethodNonce: String) {

// Update URL with your server

let paymentURL = URL(string: “”)!

var request = URLRequest(url: paymentURL)

request.httpBody = “payment_method_nonce=\(paymentMethodNonce)”.data(using: String.Encoding.utf8)

request.httpMethod = “POST”

URLSession.shared.dataTask(with: request) { (data, response, error) -> Void in

    // TODO: Handle success or failure



  1. Now let’s find out how to test it. You’ll need to get sandbox API credentials from your Braintree sandbox account. The credentials include:
  • Sandbox merchant ID
  • Public key
  • Private key
  1. You won’t be able to use real payment method data in the sandbox. For a sandbox use Braintree test card numbers and nonces.
  2. When you go live, you’ll need to replace the sandbox API credentials with production credentials.

That’s it! Follow these steps, and you’ll get a payment gateway in your iOS app.

And now let’s see how to do the same with Android.


Braintree for Android

Follow the next steps to integrate Braintree into your Android app.

  1. Set up your client

For Android devices, Braintree provides SDK v2.

  1. The first thing you’ll need to do, is to get a client token. This will allow you to connect with Braintree’s servers and authorize.
  2. Inside the token you’ll find details about configuration and authorization details.You’ll need them to initialize client SDK.
  3. After you request a token from your server, Initialize Braintree. Instead of using AsyncHttpClient for getting the token, you can get it via backend.

AsyncHttpClient client = new AsyncHttpClient();

client.get(“https://your-server/client_token”, new TextHttpResponseHandler() {


   public void onSuccess(int statusCode, Header[] headers, String clientToken) {

       this.clientToken = clientToken;





As with iOS integration, you’ll need to obtain a new client token each time the app launches. It’s better to do before a user interaction is blocked.

Another option is to use a lightweight and reusable tokenization key to authorise a client through Braintree’s SDK. It doesn’t need to be generated each session. However, its privileges are limited.

You don’t need to make customer’s ID and merchant ID specific – tokenization key can have any configuration. The key can be used for credit cards, PayPal, Apple Pay and other payment methods. However, the key can’t be used to create a 3D Secure transaction.

A tokenization key is available in the Braintree Control Panel. Since keys are specific for the environment, where they can be used, you’ll be able to obtain them separately for production and sandbox modes.


  1. Tokenization keys are compatible only with Android SDK v2 or higher. You shouldn’t ship the application with a tokenization key specific for a sandbox.
  2. You can’t save customer payment data directly to the Vault with a help of a tokenization key. In order to do that, you need to pass the payment method nonce to the server. In other case you can generate a client token with a help of a customer ID.

Saved payment methods can’t be retrieved with Drop-in. Repeat purchases will show the add payment method UI.

  1. Drop-in UI

By using client SDK with the Drop-in UI component you can easily collect customer payment info. It offers a complete payment experience right away. If you like, you can create a custom UI and then tokenize the payment info directly.

Add this dependency to your build.gradle file to get access to Drop-in UI:

dependencies {

 compile ‘com.braintreepayments.api:drop-in:3.+’


For opening the Drop-in layout, add this code to your project:

public void onBraintreeSubmit() {

 DropInRequest dropInRequest = new DropInRequest()


 startActivityForResult(dropInRequest.getIntent(this), REQUEST_CODE);


This code is needed, if you use a tokenization key:

public void onBraintreeSubmit() {

 DropInRequest dropInRequest = new DropInRequest()


 startActivityForResult(dropInRequest.getIntent(this), REQUEST_CODE);


The bottom layout will appear once you add this code. There a user will be able to enter or select payment information.

Your app will receive a paymentMethodNonce  in your calling Activity’s onActivityResult(), once a user gives payment information. Then you can override it to get the response. If there are any errors, you’ll receive them as well:


   protected void onActivityResult(int requestCode, int resultCode, Intent data) {

       if (requestCode == REQUEST_CODE) {

           if (resultCode == Activity.RESULT_OK) {

               DropInResult result = data


               // use the result to update your UI and send the payment method nonce to your server

               PaymentMethodNonce paymentMethodNonce = result.getPaymentMethodNonce();

               PaymentMethodType paymentMethodType = result.getPaymentMethodType();

  String nonce = (paymentMethodNonce != null ? paymentMethodNonce.getNonce() : null);


           } else if (resultCode == Activity.RESULT_CANCELED) {

               // the user canceled

           } else {

               // handle errors here, an exception may be available in

               Exception error = (Exception) data.getSerializableExtra(DropInActivity.EXTRA_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.








Real payment information won’t work in a sandbox, so if you want to test your app in it, you should use test card numbers (for example, 5111111111111111) and nonces like fake-valid-nonce. These are provided by Braintree.

3. Send nonce to the server

The postNonceToServer() method we’ve already mentioned in an exapmle, should send the resulting payment method nonce to your server.

Note that you can choose how to send the nonce to the backend, instead of AsyncHttpClient.

void postNonceToServer(String nonce) {

 AsyncHttpClient client = new AsyncHttpClient();

 RequestParams params = new RequestParams();

 params.put(“payment_method_nonce”, nonce);“http://your-server/checkout”, params,

   new AsyncHttpResponseHandler() {

     // Your implementation here




Now the checkout flow should be working. You’ll get a payment method nonce once a user provides payment data, which you should send to your server afterwards.

By creating a transaction with the help of the payment method nonce, your server should then close the loop.


After you follow the steps of our tutorial, everything should be working properly. Now you’ll be able to provide a clear and convenient payment system to your clients both on Android and iOS.

You can choose any payment gateway from those available. Don’t forget to consider all the details and conditions to make it a suitable way to exchange money both for you and your clients.

If you have any questions about integrating a payment gateway into your m-commerce app, you can contact a developers company like Mobindustry for a consultation.

Sponsored content