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.
Join the DZone community and get the full member experience.
Join For FreeUntil 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:
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:
xxxxxxxxxx
private lateinit var mPaymentsClient: PaymentsClient
private lateinit var mPaymentsClient: PaymentsClient
mPaymentsClient = GooglePayUtil.createPaymentsClient(this)
fun createPaymentsClient(activity: Activity): PaymentsClient {
val walletOptions = Wallet.WalletOptions.Builder()
.setEnvironment(PAYMENTS_ENVIRONMENT)
.build()
return Wallet.getPaymentsClient(activity, walletOptions)
}
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:
xxxxxxxxxx
GooglePayUtil.isReadyToPay(mPaymentsClient).addOnCompleteListener { task ->
try {
setGooglePayButtonAvailable(task.getResult(ApiException::class.java))
} catch (exception: ApiException) {
mGooglePayStatusText.text = «Payment status: Error init»
Log.d("isReadyToPay failed«, exception.statusCode.toString())
}
}
fun isReadyToPay(client: PaymentsClient): Task<Boolean> {
val request = IsReadyToPayRequest.newBuilder()
for (allowedMethod in SUPPORTED_METHODS) {
request.addAllowedPaymentMethod(allowedMethod)
}
return client.isReadyToPay(request.build())
}
Display or Hide the Button
Depending upon the result, we need to either display or hide the button like so:
xxxxxxxxxx
private fun setGooglePayButtonAvailable(available: Boolean) {
if (available) {
mGooglePayStatusText.text = «Payment status: Supported»
mGooglePayButton.visibility = View.VISIBLE
} else {
mGooglePayStatusText.text = «Payment status: Not supported»
}
}
Specify the Payment Methods
Payment methods are specified in advance like so:
xxxxxxxxxx
private val SUPPORTED_METHODS = Arrays.asList(
WalletConstants.PAYMENT_METHOD_CARD,
WalletConstants.PAYMENT_METHOD_TOKENIZED_CARD
)
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:
xxxxxxxxxx
mGooglePayButton.setOnClickListener{
requestPayment()
}
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:
xxxxxxxxxx
private fun requestPayment() {
mGooglePayButton.isClickable = false
val price = GooglePayUtil.microsToString(17852)
val transaction = GooglePayUtil.createTransaction(price)
val request = GooglePayUtil.createPaymentDataRequest(transaction)
val futurePaymentData = mPaymentsClient.loadPaymentData(request)
AutoResolveHelper.resolveTask(futurePaymentData, this, LOAD_PAYMENT_DATA_REQUEST_CODE)
}
Next, prepare the transaction. Don’t forget to indicate the currency type like so:
xxxxxxxxxx
fun createTransaction(price: String): TransactionInfo {
return TransactionInfo.newBuilder()
.setTotalPriceStatus(WalletConstants.TOTAL_PRICE_STATUS_FINAL)
.setTotalPrice(price)
.setCurrencyCode("USD")
.build()
}
Form the request. Right away, add the specifications for the merchant and the website link like so:
xxxxxxxxxx
fun createPaymentDataRequest(transactionInfo: TransactionInfo): PaymentDataRequest {
val paramsBuilder = PaymentMethodTokenizationParameters.newBuilder()
.setPaymentMethodTokenizationType(
WalletConstants.PAYMENT_METHOD_TOKENIZATION_TYPE_PAYMENT_GATEWAY
)
.addParameter("gateway", “http://www.example.com”)
.addParameter("gatewayMerchantId", "Example Merchant Name")
return createPaymentDataRequest(transactionInfo, paramsBuilder.build())
}
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:
xxxxxxxxxx
private fun createPaymentDataRequest(
transactionInfo: TransactionInfo,
params: PaymentMethodTokenizationParameters
): PaymentDataRequest {
return PaymentDataRequest.newBuilder()
.setPhoneNumberRequired(false)
.setEmailRequired(true)
.setShippingAddressRequired(true)
.setShippingAddressRequirements(
ShippingAddressRequirements.newBuilder()
.addAllowedCountryCodes(SHIPPING_SUPPORTED_COUNTRIES)
.build()
)
.setTransactionInfo(transactionInfo)
.addAllowedPaymentMethods(SUPPORTED_METHODS)
.setCardRequirements(
CardRequirements.newBuilder()
.addAllowedCardNetworks(SUPPORTED_NETWORKS)
.setAllowPrepaidCards(true)
.setBillingAddressFormat(WalletConstants.BILLING_ADDRESS_FORMAT_FULL)
.build()
)
.setPaymentMethodTokenizationParameters(params)
.setUiRequired(true)
.build()
}
private val SHIPPING_SUPPORTED_COUNTRIES = Arrays.asList("UA, US, DE, GB")
private val SUPPORTED_NETWORKS = Arrays.asList(
WalletConstants.CARD_NETWORK_VISA,
WalletConstants.CARD_NETWORK_MASTERCARD
)
So, the request is formed. Next, we need to process the result of this request like so:
xxxxxxxxxx
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
when (requestCode) {
LOAD_PAYMENT_DATA_REQUEST_CODE -> {
when (resultCode) {
Activity.RESULT_OK -> {
data?.let {
onPaymentSuccess(PaymentData.getFromIntent(data))
}
}
Activity.RESULT_CANCELED -> {
}
AutoResolveHelper.RESULT_ERROR -> {
onError(AutoResolveHelper.getStatusFromIntent(data)?.statusCode)
}
}
mGooglePayButton.isClickable = true
}
}
}
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:
xxxxxxxxxx
private fun onPaymentSuccess(paymentData: PaymentData?) {
Toast.makeText(this, “Payment Success”, Toast.LENGTH_LONG).show()
}
private fun onError(statusCode: Int?) {
Log.w("loadPaymentData failed", String.format("Error code: %d", statusCode))
}
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.
xxxxxxxxxx
private val baseRequest = JSONObject().apply {
put("apiVersion", 2)
put("apiVersionMinor", 0)
}
We immediately form a request to tokenize your provider as follows:
xxxxxxxxxx
private fun gatewayTokenizationSpecification(): JSONObject {
return JSONObject().apply {
put("type«, «PAYMENT_GATEWAY»)
put("parameters«, JSONObject(mapOf(
«gateway» to «example»,
«gatewayMerchantId» to «exampleGatewayMerchantId»)))
}
}
Next, we indicate what types of cards we will work with and the possible authentication options. See below:
xxxxxxxxxx
private val allowedCardNetworks = JSONArray(listOf(
«AMEX»,
«DISCOVER»,
«INTERAC»,
«JCB»,
«MASTERCARD»,
«VISA»))
private val allowedCardAuthMethods = JSONArray(listOf(
«PAN_ONLY»,
«CRYPTOGRAM_3DS»))
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.
Published at DZone with permission of Andrii Zhumela. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments