How to Integrate Payment Gateway in a Mobile App

Contents:

1. Introduction
2. How To Integrate Mobile Payments in an iOS App
3. How To Integrate Mobile Payments in an Android App
4. Conclusion

Introduction

There’s a golden rule in sales: the easier the payment process is, the higher the probability the client will buy the product. This is especially true for e-commerce, where any problem can be a serious obstacle to purchasing.

In-app purchases have already become a standard for any m-commerce or e-commerce application, and clients expect it from a high-quality application with top-notch service. Several big companies like PayPal have set this trend when they found this easy way to help transfer money in exchange to any possible products or services. This trend doesn’t seem to go anywhere soon — it is only going to grow and evolve. Now there is a wide choice of payment processors of which you can choose from: they have different audience, rules, fees and conditions.

In this article, we’ll tell you how to accept payments in a mobile app quickly and easily by integrating a payment gateway.

The best payment processors that we had experience with are Braintree, PayPal, Stripe and Apple Pay. Look at what they have to offer, what currency they support and which areas they cover, so that you can offer your clients the best service on the market.

If you don’t know, how to choose a right payment processor for your business, try to compare all the processors by their basic parameters like user interface, coverage, fees and supported currencies. Another important thing about any payment processor is, of course, security. The processor you will eventually choose has to take it seriously.

In this article we’ll focus on Braintree integration into Android and iOS apps. Based on this experience, we’ll provide examples of:

  • Mobile payment integration for iOS
  • Mobile payment gateway integration for Android

But first, let’s look briefly at how Braintree works.

Braintree Overview

Braintree is suitable for m-commerce businesses of all sizes, from small companies to big corporations. Recently, Braintree has become even more progressive and popular than PayPal, which owns it.

It’s also extremely flexible. The Braintree SDK lets you use a lot of popular payment methods: credit and debit cards, PayPal, Apple Pay, Venmo, Android pay, and even Coinbase with bitcoins! In short, it’s one of the easiest ways to pay for anything in an app, across any device.

Many famous apps are already using Braintree’s libraries. Uber, Dropbox, Airbnb, Stubhub, American Airlines – all of these companies have entrusted Braintree with their online payments.

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

Braintree supports sandbox mode as well, so you can test your integration with test values for payment method nonces, card numbers, transaction amounts, and more.

If you want to find out more about Braintree or other payment gateways, check out our article on the best payment gateways on the market.

How To Integrate Mobile Payments in an iOS App

Here’s a tutorial on integrating Braintree into an iOS application (based on our experience).

1. Collect customer payment information

  • Get a checkout for PayPal and credit card payments by adding the Drop-in UI. It will take you only a few lines of code.
  • Add buttons for PayPal, Apple Pay, Android Pay, and Venmo to accept more types of payments, if you already have a checkout
  • If you roll your own checkout UI, you can use credit card tokenization and thus save your customer’s card info.

2. 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: "https://your-server.com/client_token")!
	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...
    	}.resume()
}

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

4. Add the import statements to any class using Braintree:

import BraintreeDropIn
import Braintree

5. Drop-in is the easiest way to get started. It provides a fully fledged payment experience out of the box. You can also choose to create a custom UI and then tokenize the payment information directly, however. To do so, add an action on some button:

func showDropIn(clientTokenOrTokenizationKey: String) {
	let request =  BTDropInRequest()
	let dropIn = BTDropInController(authorization: clientTokenOrTokenizationKey, request: request)
	{ (controller, result, error) in
    	if (error != nil) {
        	print("ERROR")
    	} else if (result?.isCancelled == true) {
        	print("CANCELLED")
    	} 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 resulting payment method nonce to your server (again, adapt this to your own setup):

func postNonceToServer(paymentMethodNonce: String) {
	// Update URL with your server
	let paymentURL = URL(string: "https://your-server.example.com/payment-methods")!
	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
	}.resume()
}

6. For testing, you’ll need to have a Braintree sandbox account and get your sandbox API credentials:

  • Sandbox merchant ID
  • Public key
  • Private key

7. Real payment method data will not work in the sandbox; you need to use Braintree test card numbers and nonces.

8. When you go live, you’ll need to replace the sandbox API credentials with production credentials.

There you go! Now you’ll be able to integrate a payment system in your iOS application.

Now let’s find out how to integrate a payment gateway in an Android mobile app.

How To Integrate Mobile Payments in an Android App

This tutorial will help you integrate Braintree into your Android application.

1. Set up your client

Braintree provides SDK v2 for Android devices.
1. To establish and authorize connection with Braintree’s servers you will need to get a client token.

2. To initialize the client SDK, you will need configuration and authorization details. They are placed inside the client token, that your server generates.

3. Initialize Braintree after requesting a client token from your server. You can choose how you get the client token via the backend (instead of AsyncHttpClient):

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;
    }
});

Note:
Each time your app launches, you need to obtain a new client token. For the best result, this operation should go before a user interaction is blocked.

A tokenization key is another way to authorize a client with the help of Braintree’s SDK. This value is lightweight and reusable.

On the other hand, its privileges are reduced, and it is static. Unlike the case with client token, tokenization key doesn’t need to be generated again and again after each session.

Any configuration is suitable for a tokenization key — there is no need to specify customer’s ID and set a specific merchant ID.

Such payment methods like credit cards, PayPal, Android and Apple Pay as well as Venmo can be tokenized with the help of tokenization key.

The following payment methods can be tokenized using a tokenization key: credit cards, PayPal, Venmo, Apple Pay, and Android Pay. You can’t use a tokenization key to create a 3D Secure transaction.

You can obtain a tokenization key in the Braintree Control Panel (separately for production and sandbox modes). Tokenization keys are specific to the environment in which they will be used.

Note:
1. Tokenization keys are only compatible with Android SDK v2 or higher.
Avoid shipping an app with a sandbox tokenization key.
2. Customer payment data can’t be saved directly to the Vault using a tokenization key. To save a payment method, you’ll need to pass the resulting payment method nonce to your server. Otherwise, you can generate a client token with a customer ID.

You can’t use Drop-in to retrieve a customer’s saved payment methods. Repeat purchases will show the add payment method UI

2. Drop-in UI

The easiest way to collect customer payment information via the client SDK is with the Drop-in UI component. It provides a fully fledged payment experience out of the box. You can also choose to create a custom UI and then tokenize the payment information directly.

To get access to the Drop-in UI, you should add the following dependency to your build.gradle file:

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()
      .clientToken("your_client_token");
  startActivityForResult(dropInRequest.getIntent(this), REQUEST_CODE);
}

If you use a tokenization key, you should add the following code:

public void onBraintreeSubmit() {
  DropInRequest dropInRequest = new DropInRequest()
      .tokenizationKey("your_tokenization_key");
  startActivityForResult(dropInRequest.getIntent(this), REQUEST_CODE);
}

After you added this code, the bottom layout will appear and the user will be able to enter or select payment information.

When a user provides payment information, your app will receive a paymentMethodNonce in your calling Activity’s onActivityResult(), which you can override to get the response (including any errors):

   @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                DropInResult result = data
.getParcelableExtra(DropInResult.EXTRA_DROP_IN_RESULT);
                // 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);

                postNonceToServer(nonce);
            } 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.
                        }
                    }
                }
            }
        }
    }

Note:
When testing in the sandbox, be sure to use the test card numbers (e.g. 4111111111111111) and nonces (e.g. fake-valid-nonce) that Braintree provides. Real payment data will not work in the sandbox.

3. Send nonce to the server

The postNonceToServer() method from our previous example should send the resulting payment method nonce to your server.

Don’t forget that you can choose how you send the nonce to your backend (instead of AsyncHttpClient):

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
    }
  );
}

At this point, you should have a working client-side checkout flow. When a user provides payment information, you should receive a payment method nonce and send it to your server.

Then, your server should close the loop by using the payment method nonce to create a transaction.

Conclusion

That’s it! Now you know how to integrate a payment gateway into your mobile app, whether it’s for Android or iOS.

We have taken integration with Braintree as the example, but in fact, you can choose from any payment processor. Don’t forget to consider all the conditions and make sure they meet the best interest of your customer as well as your own. If you have a hard time trying to find your perfect payment gateway, consider the basic parameters that define the convenience of a payment processor.

If you have any questions, don’t hesitate to contact us for more information. At Mobindustry, we specialize in e-commerce and m-commerce mobile application development.

Request Callback

Request Callback

+