Mobindustry merges with Apriorit,
a Specialized Cybersecurity R&D Company
Month: April 2020
How to Integrate Payment Gateway in a Mobile App
Introduction
In-app purchases have already become a standard for any m-commerce or ecommerce 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 payment gateway integration.
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 Integration
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.
Stripe Integration
Along with Braintree, Stripe is one of the most popular mobile payment processors. It allows to perform payments in social media, supports Apple Pay and Android Pay, and also reports monthly on all payment activity. In addition to that, Stripe is very customizable: if you want to make a unique form for payments, you can do it in Stripe: pick your mcommerce shop colors and make the design complimentary to your app’s.
Stripe accepts over 100 currencies and supports lots of libraries – iOS, Andriod, Ruby, PHP and others.
Stripe’s rates are 2.9% + 30 cents for each successful charge. There are no monthly and setup fees, and the currency conversion fee is 2%.
PayPal Integration
PayPal is the most widespread payment processor as it was the first one. PayPal made a revolution in online payments and has set a standard for other payment processors. However, nowadays some online retailers start to decline it in favour of Braintree or Stripe.
However, PayPal is still extremely popular: 79% of US users have it. PayPal offers split payments, allows to host your own checkout page and supports over 23 currencies in 203 countries.
PayPal charges 2.9% + 30 cents for each successful payment. In case you process over $30,000 per month, the fee is lower. If you choose a Pro package, you’ll need to pay $30 per month, otherwise, it’s free. The currency conversion fee is different for every location: it can vary from 0.4% to 3.3%.
Now that you know more about payment gateways, let’s find out how to integrate payment gateway in Android or iOS. We’ll start with iOS.
What is a payment gateway?
So, what is a payment gateway and how does it work? A payment gateway is a technology for credit or debit card payments integration into mobile applications and on websites. Payment gateway technology is responsible for secure customer data gathering on the frontend part of the app. A payment gateway sends data to an acquiring bank or payment processor in order to perform the transaction.
How it works: Users select products that they want to buy and add them to their shopping carts. The cart is connected to the payment gateway service, which allows users to enter their credit card details. When users write out cards and pay for their order, the gateway sends a request to the bank that issued the card. Ideally, the bank approves the transaction.
Best online payment processors
A payment processor is a company that a seller uses to process credit card transactions. Payment systems use anti-fraud measures to protect both the client and the seller. Before integrating payment gateway in android app let’s see what are best gateway payment services. Here’s the list of best online payment processors:
- Dwolla
- Google Checkout
- Authorize.Net
- PayPal
- Amazon Payments
- Stripe
- Braintree
How To Integrate Payment Gateway 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. If you want to integrate mobile payments in your iOS app, don’t hesitate and contact us right now. We’ll answer any questions you might have.
Now let’s find out how to integrate a payment gateway in an Android mobile app.
How To Integrate Payment Gateway in an Android Application
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 payment gateway integration in Android 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 ecommerce and m-commerce mobile application development.
Article written by:
Pavel Peday
Valentin Ostapolets