DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • How To Integrate Chatbot With an Android App
  • Guide for Voice Search Integration to Your Flutter Streaming App
  • 7 Awesome Libraries for Java Unit and Integration Testing
  • Overview of Android Networking Tools: Receiving, Sending, Inspecting, and Mock Servers

Trending

  • Ingesting Fixed-Width Mainframe Files Into Delta Lake: The Details Nobody Writes Down
  • From AI Chaos to Control: Building Enterprise-Grade LLM Gateways With MuleSoft Anypoint
  • Catching Data Perimeter Drift Before It Reaches Production
  • Beyond Partitioning and Z-Order: A Deep Dive into Liquid Clustering for Unity Catalog Managed Tables
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Deployment
  4. How to Integrate Google Pay Service and Why You Should

How to Integrate Google Pay Service and Why You Should

In this article, learn how to integrate Google Pay Service into your Android app, while also learning the benefits of the integration.

By 
Andrii Zhumela user avatar
Andrii Zhumela
·
Updated Feb. 23, 21 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
24.8K Views

Join the DZone community and get the full member experience.

Join For Free

Until recently, the implementation of a payment method into your business software solution was a matter of your clients’ convenience and an important factor of success in e-commerce. Today, in the condition of the COVID-19 pandemic, contactless payments have also become an important aspect of safety for both buyers and sellers.

When speaking about business mobile apps, the statistics say you may lose up to 80% of your clients just because the payment service is inconvenient or untrustworthy. Just think of all those attempts to enter data with the help of a touchscreen — not to mention multiple shifts and the fear of data leaks. In this situation, the Google Pay payment gateway integration is a win-win solution for all parties. Besides contactless payments with Android phones and wearable devices, GPAY guarantees secure online payments with quick and safe checkout in apps and websites. Although it’s simple to integrate Google Pay in the Android app, it's a great solution with access to hundreds of cards saved in a Google account which can open up more opportunities for your business. What's more important is that it is free for both entrepreneurs and customers.

Business Advantages of Google Pay

Google Pay (previously known as Android Pay) enables mobile payments in just two steps. The users register in Google and, when it comes to the payment, they tap the button "Buy with GPAY," choose one of their cards, and submit. Shipping mode being attached once, they dispose of the necessity to enter the same contact data again and again. No wonder that such an easy payment method is really popular among the users: as of September 2018, the Google Pay app was downloaded more than 100 million times. So, what are the business benefits? Airbnb, for instance, saw an 11x increase in the number of online payments after they integrated this service. Google does not charge for Google Pay, so everything you get from the integration is growth in conversions and income. Let’s summarize:

  • G-Pay is free.
  • It’s easy to integrate.
  • It allows access to hundreds of cards.
  • It skyrockets your conversions.
  • It boosts your income.

Any e-commerce software solution dealing with a retail or service provider can benefit a lot from Google Pay implementation in Android applications.

Google Pay is available for all goods and service providers in the countries where the service is supported. Implementing Google Pay in Android is a perfect way to connect the user with dozens of payment systems all over the world through a unified interface. 

Google Pay Integration

Import GPAY Service Library

The first thing you need to do for Google Pay integration in the Android app is to import a library. In the project file Gradle, you need to add a dependency: 

Shell
 




x


 
1
implementation ’com.google.android.gms:play-services-wallet:$play_service_wallet_version’ 


Here, $play_service_wallet_version is the version of the library we are going to use.

The current version is 18.0.0. More detailed instruction for the library data and information about Google Pay Services libraries can be found in their docs here.

Initialize the Payment Client

Assuming the product or the service has already been formed and everything is ready for it to pass into your ownership, what we still need is to adjust the purchase process itself. For this, let’s initialize the payment client like so:

Java
 




xxxxxxxxxx
1
13


 
1
private lateinit var mPaymentsClient: PaymentsClient
2
 
3
private lateinit var mPaymentsClient: PaymentsClient
4
 
5
mPaymentsClient = GooglePayUtil.createPaymentsClient(this)
6
 
7
fun createPaymentsClient(activity: Activity): PaymentsClient {
8
    val walletOptions = Wallet.WalletOptions.Builder()
9
    .setEnvironment(PAYMENTS_ENVIRONMENT)
10
    .build()
11
    return Wallet.getPaymentsClient(activity, walletOptions)
12
}
13
For PAYMENTS_ENVIRONMENT, we will specify the environment type WalletConstants.ENVIRONMENT_TEST.


Check the Possibility of Purchasing

Next, I propose to first check the possibility of purchasing with Google Pay like so:

Java
 




xxxxxxxxxx
1
17


 
1
GooglePayUtil.isReadyToPay(mPaymentsClient).addOnCompleteListener { task ->
2
try {
3
    setGooglePayButtonAvailable(task.getResult(ApiException::class.java))
4
    } catch (exception: ApiException) {
5
    mGooglePayStatusText.text = «Payment status: Error init»
6
    Log.d("isReadyToPay failed«, exception.statusCode.toString())
7
    }
8
}
9
 
10
 
11
fun isReadyToPay(client: PaymentsClient): Task<Boolean> {
12
    val request = IsReadyToPayRequest.newBuilder()
13
    for (allowedMethod in&nbsp;SUPPORTED_METHODS) {
14
        request.addAllowedPaymentMethod(allowedMethod)
15
    }
16
    return client.isReadyToPay(request.build())
17
}


Display or Hide the Button

Depending upon the result, we need to either display or hide the button like so:

Java
 




xxxxxxxxxx
1


 
1
private fun setGooglePayButtonAvailable(available: Boolean) {
2
    if&nbsp;(available) {
3
        mGooglePayStatusText.text = &laquo;Payment status: Supported&raquo;
4
        mGooglePayButton.visibility = View.VISIBLE
5
    } else {
6
        mGooglePayStatusText.text = &laquo;Payment status: Not supported&raquo;
7
    }
8
}


Specify the Payment Methods

Payment methods are specified in advance like so:

Java
 




xxxxxxxxxx
1


 
1
private val SUPPORTED_METHODS = Arrays.asList(
2
    WalletConstants.PAYMENT_METHOD_CARD,
3
    WalletConstants.PAYMENT_METHOD_TOKENIZED_CARD
4
)


Google Pay in the Android App: Further Steps for Integration

We have gone through all preparatory stages related to our payment systems usage. Now, we have come to the most complicated stage: payment committing. See below:

Java
 




xxxxxxxxxx
1


 
1
mGooglePayButton.setOnClickListener{
2
   requestPayment()
3
}


An important note: most payment systems use the minimal possible currency value. Consequently, in the case of a kopeck or penny, for example, when indicating the write-off sum equal to 17852, we confirm that we want to write off 178.52.

The currency type is seen below:

Java
 




xxxxxxxxxx
1
10


 
1
private fun requestPayment() {
2
   mGooglePayButton.isClickable = false
3
 
4
   val price = GooglePayUtil.microsToString(17852)
5
   val transaction = GooglePayUtil.createTransaction(price)
6
   val request = GooglePayUtil.createPaymentDataRequest(transaction)
7
   val futurePaymentData = mPaymentsClient.loadPaymentData(request)
8
 
9
   AutoResolveHelper.resolveTask(futurePaymentData, this, LOAD_PAYMENT_DATA_REQUEST_CODE)
10
}


Next, prepare the transaction. Don’t forget to indicate the currency type like so:

Java
 




xxxxxxxxxx
1


 
1
fun createTransaction(price: String): TransactionInfo {
2
   return TransactionInfo.newBuilder()
3
       .setTotalPriceStatus(WalletConstants.TOTAL_PRICE_STATUS_FINAL)
4
       .setTotalPrice(price)
5
       .setCurrencyCode("USD")
6
       .build()
7
}


Form the request. Right away, add the specifications for the merchant and the website link like so:

Java
 




xxxxxxxxxx
1


 
1
fun createPaymentDataRequest(transactionInfo: TransactionInfo): PaymentDataRequest {
2
   val paramsBuilder = PaymentMethodTokenizationParameters.newBuilder()
3
       .setPaymentMethodTokenizationType(
4
           WalletConstants.PAYMENT_METHOD_TOKENIZATION_TYPE_PAYMENT_GATEWAY
5
       )
6
       .addParameter("gateway", “http://www.example.com”)
7
       .addParameter("gatewayMerchantId", "Example Merchant Name")
8
   return createPaymentDataRequest(transactionInfo, paramsBuilder.build())
9
}


Next, the request itself. Here, specify all the necessary fields and ordering parameters. For example, we may specify that we need to request a phone number and e-mail and whether we need a delivery option at all. Here and now, we also specify the countries where the goods can be delivered, as well as the available payment options and payment systems (Visa, Mastercard, etc.) like so:

Java
 




xxxxxxxxxx
1
35


 
1
private fun createPaymentDataRequest(
2
   transactionInfo: TransactionInfo,
3
   params: PaymentMethodTokenizationParameters
4
): PaymentDataRequest {
5
 
6
   return PaymentDataRequest.newBuilder()
7
       .setPhoneNumberRequired(false)
8
       .setEmailRequired(true)
9
       .setShippingAddressRequired(true)
10
       .setShippingAddressRequirements(
11
           ShippingAddressRequirements.newBuilder()
12
               .addAllowedCountryCodes(SHIPPING_SUPPORTED_COUNTRIES)
13
               .build()
14
       )
15
       .setTransactionInfo(transactionInfo)
16
       .addAllowedPaymentMethods(SUPPORTED_METHODS)
17
       .setCardRequirements(
18
           CardRequirements.newBuilder()
19
               .addAllowedCardNetworks(SUPPORTED_NETWORKS)
20
               .setAllowPrepaidCards(true)
21
               .setBillingAddressFormat(WalletConstants.BILLING_ADDRESS_FORMAT_FULL)
22
               .build()
23
       )
24
       .setPaymentMethodTokenizationParameters(params)
25
       .setUiRequired(true)
26
       .build()
27
}
28
 
29
private val SHIPPING_SUPPORTED_COUNTRIES = Arrays.asList("UA, US, DE, GB")
30
 
31
private val SUPPORTED_NETWORKS = Arrays.asList(
32
   WalletConstants.CARD_NETWORK_VISA,
33
   WalletConstants.CARD_NETWORK_MASTERCARD
34
)
35

          


So, the request is formed. Next, we need to process the result of this request like so:

Java
 




xxxxxxxxxx
1
20


 
1
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
2
   when (requestCode) {
3
       LOAD_PAYMENT_DATA_REQUEST_CODE -> {
4
           when (resultCode) {
5
               Activity.RESULT_OK -> {
6
                   data?.let {
7
                       onPaymentSuccess(PaymentData.getFromIntent(data))
8
                   }
9
               }
10
               Activity.RESULT_CANCELED -> {
11
               }
12
               AutoResolveHelper.RESULT_ERROR -> {
13
                   onError(AutoResolveHelper.getStatusFromIntent(data)?.statusCode)
14
               }
15
           }
16
           mGooglePayButton.isClickable = true
17
       }
18
   }
19
}
20

          


Next up is the transaction processing. Here, a lot of various logic can be added, but in our version we will just check the result of the transaction and display it. This is just a trial version, so we will not dwell on the business logic. See below: 

Java
 




xxxxxxxxxx
1


 
1
private fun onPaymentSuccess(paymentData: PaymentData?) {
2
     Toast.makeText(this, “Payment Success”, Toast.LENGTH_LONG).show()
3
}
4
 
5
private fun onError(statusCode: Int?) {
6
   Log.w("loadPaymentData failed", String.format("Error code: %d", statusCode))
7
}


Android Google Pay Integration Outcome: What the User Sees

As a result, the users at the checkout stage will see the Google Pay button. After tapping it, they will see the checkout form.

Google Pay Update 2020

Time flies, and to keep this small Android Google Pay integration tutorial up-to-date, we decided to refresh it. Google has made a great tutorial already, so I'll just try to explain some points from the practical point of view.

Library Versions

First, over time, the version of the payment plug-in library has been upgraded.

com.google.android.gms:play-services-wallet:$play_service_wallet_version

The current version of the library is 18.0.0. The changes mainly affected security and bank interaction protocols.

Payment Providers

As to the banks and payment systems that work with Google Pay, you need to look at the up-to-date list. The payments can be realized only through the enumerated payment providers. By the way, the list is quite extensive and the most popular payment systems support Google Pay payments as well. Here, you can find global payment systems such as BrainTree, Stripe, and Square.

Display

To be able to use payments, you should also study the design guides. It’s quite possible that during a review, you'll get a blocked payment before all the problems are eliminated.

Usage

The first step to making successful payments is to register your business.

Then, you need to configure the payment client itself. To do this, you need to form a basic request, where the minimum version of API payment will be indicated. This part should be used during every request.

Java
 




xxxxxxxxxx
1


 
1
private val baseRequest = JSONObject().apply {
2
    put("apiVersion", 2)
3
    put("apiVersionMinor", 0)
4
}


We immediately form a request to tokenize your provider as follows:

Java
 




xxxxxxxxxx
1


 
1
private fun gatewayTokenizationSpecification(): JSONObject {
2
    return JSONObject().apply {
3
    put(&quot;type&laquo;, &laquo;PAYMENT_GATEWAY&raquo;)
4
    put(&quot;parameters&laquo;, JSONObject(mapOf(
5
    &laquo;gateway&raquo; to&nbsp;&laquo;example&raquo;,
6
    &laquo;gatewayMerchantId&raquo; to&nbsp;&laquo;exampleGatewayMerchantId&raquo;)))
7
    }
8
}


Next, we indicate what types of cards we will work with and the possible authentication options. See below:

Java
 




xxxxxxxxxx
1
11


 
1
private val allowedCardNetworks = JSONArray(listOf(
2
    &laquo;AMEX&raquo;,
3
    &laquo;DISCOVER&raquo;,
4
    &laquo;INTERAC&raquo;,
5
    &laquo;JCB&raquo;,
6
    &laquo;MASTERCARD&raquo;,
7
    &laquo;VISA&raquo;))
8
 
9
private val allowedCardAuthMethods = JSONArray(listOf(
10
    &laquo;PAN_ONLY&raquo;,
11
    &laquo;CRYPTOGRAM_3DS&raquo;))


As for authorization, there is an option to specify just PAN_ONLY, which will allow you to use Google Pay only with those cards that are already linked to your account. 

All we have left to do is to create the client for payment (PaymentClient), check the possibility of payment using Google Pay, and display the button as described above. All code examples are provided on GitHub, where you can find an almost complete sample from Google itself.

Let’s Sum It Up

Google Pay is a handy and safe payment service for mobile apps with the possibility to integrate numerous payment systems. It makes purchases easier for clients and boosts online sales for the merchants. With the help of the algorithm described above, you can easily add Google Pay to the Android app you develop for your business and, besides, now you have some idea how to cope with difficulties in its integration.

Google (verb) Integration mobile app Java (programming language) Android (robot) Library Requests

Published at DZone with permission of Andrii Zhumela. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How To Integrate Chatbot With an Android App
  • Guide for Voice Search Integration to Your Flutter Streaming App
  • 7 Awesome Libraries for Java Unit and Integration Testing
  • Overview of Android Networking Tools: Receiving, Sending, Inspecting, and Mock Servers

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook