The easier it is to pay, the more people will buy from you. This is the golden rule of any digital business. People are used to fast and convenient service, and this is exactly what Google Pay provides

According to Annex Cloud, a business can lose up to 80% of all potential customers at the checkout because of an inconvenient payment procedure. Why is that?

  • Customers know that they can always look for a similar product elsewhere
  • Customers don’t trust your payment processor and fear exposure of their personal data
  • Customers don’t already use your preferred payment method, so they need to perform additional actions
  • An unclear UI and poor UX makes customers transition between many screens

That’s why before you integrate any payment processor into your mobile app, you should make sure it’s convenient, is used by your target audience, and is secure. Google Pay is one of the best options for Android users across the world, as it works everywhere and is secure.

google pay integration mobile app
Google Pay is one of the best payment processors for Android users

Google announced the launch of its own payment gateway called Google Wallet in 2011 at Google I/O – the annual Google developer conference. In 2015, Google released a separate application for Android devices called Android Pay.

The main advantage of Android Pay was the ability to pay in stores and keep all loyalty cards in the app. In 2018, Google merged Google Wallet and Android Pay into one application called Google Pay.

Airbnb reported an 11x increase in online payments after integrating Google Pay into their mobile application

In this article, I’ll discuss why Google Pay is good for your business. Then I’ll provide you with a tutorial on integrating Google Pay into your app.

Why Google Pay is great for business

With Google Pay, users need to perform only three actions to pay for purchases in your mobile app:

  • Press the Pay with Google button
  • Choose a payment card
  • Confirm the payment

Additionally, a user can specify a delivery method in their Google account to avoid entering delivery information again and again.

This simple payment method has become so popular among users that by September 2018 the app had already been downloaded 100 million times. Airbnb reported an 11x increase in online payments after integrating Google Pay into their mobile application.

Google Pay allows customers to keep all their cards in one place

While many other payment services like PayPal and Braintree charge a fee for using their service, Google Pay is free. This is great for businesses, as they lose about $0.30 per transaction plus 3% of the transaction total with PayPal or Braintree.

Google Pay is available for all vendors in countries where Google provides its services. You can use Google Pay to connect several dozen payment gateways in a single interface. It’s also easy to integrate: see for yourself in our tutorial.

Google Pay integration tutorial

The first thing you need to do to integrate Google Pay is add a library to your project. To do that, add this dependency to your gradle file:

implementation 'com.google.android.gms:play-services-wallet:$version'

Here, $version is the version of the library we’re going to use. Currently, 16.0.1 is the most recent. If you need more detailed instructions on setting up a library, you can visit Google’s developer documentation. There, you’ll also find information on the types of libraries Google Play Services offer to programmers.

Let’s assume you already have a product or a service you’d like to sell. All you need to do now is set up the purchasing process. For this, let’s initialize a payment client:


private PaymentsClient mPaymentsClient;

mPaymentsClient = PaymentsUtil.createPaymentsClient(this);

public static PaymentsClient createPaymentsClient(Activity activity) {
   Wallet.WalletOptions walletOptions =new Wallet.WalletOptions.Builder()
       .setEnvironment(Constants.PAYMENTS_ENVIRONMENT)
       .setTheme(WalletConstants.THEME_DARK)
       .build();
   return Wallet.getPaymentsClient(activity, walletOptions);
}

Then you should choose a WalletConstants.ENVIRONMENT_TEST – a type of environment for your PAYMENTS_ENVIRONMENT.

The next step is to check whether you can actually make a purchase using Google Pay. This is how you can do it:


private void possiblyShowGooglePayButton() {
    final Optional isReadyToPayJson = PaymentsUtil.getIsReadyToPayRequest();
    if (!isReadyToPayJson.isPresent()) {
        return;
    }
    IsReadyToPayRequest request = IsReadyToPayRequest
        .fromJson(isReadyToPayJson.get().toString());
    if (request == null) {
        return;
    }

    Task task = mPaymentsClient.isReadyToPay(request);
    task.addOnCompleteListener(this,new OnCompleteListener() {
        @Override
        public void onComplete(@NonNull Task task) {
            if (task.isSuccessful()) {
               setGooglePayAvailable(task.getResult());
            } else {
                Log.w("isReadyToPay failed", task.getException());
            }
        }
    });
}

If everything is processed correctly, you then can put a Pay with Google button on your checkout screen.

private void setGooglePayButtonAvailable(boolean available) {
   if (available) {
       mGooglePayStatusText.setText("Payment status: Supported");
       mGooglePayButton.setVisibility(View.VISIBLE);
   } else {
       mGooglePayStatusText.setText("Payment status: Not supported");
   }
}

Setting up other payment gateways and search for available payment cards is handled by a static method called PaymentsUtil.getIsReadyToPayRequest. To make it work, you need to specify this information:

  • Your app’s API version
JSONObject().put("apiVersion", 2).put("apiVersionMinor", 0);
  • The type of tokenization
  • JSONObject tokenizationSpecification = new JSONObject();
      tokenizationSpecification.put("type", "PAYMENT_GATEWAY");
      tokenizationSpecification.put(
          "parameters",
          new JSONObject()
              .put("gateway", "example")
              .put("gatewayMerchantId", "exampleMerchantId"));
    
  • The payment gateways you plan to support in your app
  • 
    private static JSONArray getAllowedCardNetworks() {
      return new JSONArray()
          .put("AMEX")
          .put("DISCOVER")
          .put("JCB")
          .put("MASTERCARD")
          .put("VISA");
    }
    
  • A method of searching for payment cards in Google’s archives and/or tokens stored on a user’s device
  • 
    private static JSONArray getAllowedCardAuthMethods() {
      return new JSONArray()
          .put("PAN_ONLY")
          .put("CRYPTOGRAM_3DS");
    }
    
  • The identifier for the supported payment type (At the moment, Google supports only the CARD identifier.)
  • JSONObject cardPaymentMethod = new JSONObject();
      cardPaymentMethod.put("type", "CARD");
    Payment processing

    Now that you’re done setting up everything regarding payment gateways, the hard part is ahead: processing a payment.

    mGooglePayButton.setOnClickListener(
           new View.OnClickListener() {
               @Override
               public void onClick(View view) {
                   requestPayment(view);
               }
           });
    

    Keep in mind that when processing a payment, Google Pay (like most other payment gateways) uses the minimum possible currency value. For example, if you specify a withdrawal of 156358, this means that you’d like to withdraw $1563.58.

    The next step is to build a JSONObject from the entities we’ve created earlier:

    
    public static Optional getPaymentDataRequest(String price) {
       try {
           JSONObject paymentDataRequest = PaymentsUtil.getBaseRequest();
           paymentDataRequest.put(
               "allowedPaymentMethods", new JSONArray()
                         .put(PaymentsUtil.getCardPaymentMethod()));
           paymentDataRequest.put(
               "transactionInfo", PaymentsUtil.getTransactionInfo(price));
           paymentDataRequest.put(
               "merchantInfo", PaymentsUtil.getMerchantInfo());
           paymentDataRequest.put(
               "shippingAddressParameters", shippingAddressParameters);
           return Optional.of(paymentDataRequest);
       } catch (JSONException e) {
           return Optional.empty();
       }
    }
    

    Then you need to set up the transaction. Don’t forget to specify the currency:

    private static JSONObject getTransactionInfo(String price) throws JSONException {
       JSONObject transactionInfo = new JSONObject();
       transactionInfo.put("totalPrice", price);
       transactionInfo.put("totalPriceStatus", "FINAL");
       transactionInfo.put("currencyCode", “USD”);
       return transactionInfo;
    }
    

    Build a PaymentDataRequest object inside the requestPayment method. This object is basically a request for required payment information. To make a request automatically, use AutoResolveHelper.

    
    public void requestPayment(View view) {
       mGooglePayButton.setClickable(false);
    
       String price = PaymentsUtil.microsToString(item.getPriceMicros());
       Optional paymentDataRequestJson = 
               PaymentsUtil.getPaymentDataRequest(15635);
       PaymentDataRequest request =
               PaymentDataRequest.fromJson(paymentDataRequestJson.get().toString());
    
    
       AutoResolveHelper.resolveTask(
                   mPaymentsClient.loadPaymentData(request), 
                   this, 
                   LOAD_PAYMENT_DATA_REQUEST_CODE);
    }
    

    Now you’ve formed the request and sent it. Your next step is to process the result of this request:

    
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
       switch (requestCode) {
           case LOAD_PAYMENT_DATA_REQUEST_CODE:
               switch (resultCode) {
                   case Activity.RESULT_OK:
                       PaymentData paymentData = PaymentData.getFromIntent(data);
                       handlePaymentSuccess(paymentData);
                       break;
                   case Activity.RESULT_CANCELED:
                       break;
                   case AutoResolveHelper.RESULT_ERROR:
                       Status status = AutoResolveHelper.getStatusFromIntent(data);
                       handleError(status.getStatusCode());
                       break;
                   default:
               }
    
    
               mGooglePayButton.setClickable(true);
               break;
       }
    }
    

    This is where you can link Google Pay to the business logic of your app. For example, you can specify what information you’d like to show on a screen to thank your users for their purchase, or switch to the next screen.

    
    private void handlePaymentSuccess(PaymentData paymentData) {
         Toast.makeText(this, "Payment Success", Toast.LENGTH_LONG).show()
    }
     
    private void handleError(int statusCode) {
       Log.w("loadPaymentData failed", String.format("Error code: %d", statusCode))
    }
    

    That’s it! Now you know how you can receive payments from your app users with the help of Google Pay.

    Final thoughts

    Google Pay is a modern, safe, and extremely convenient payment service that allows you to integrate many payment processors at once. It makes payments more convenient for your users and therefore increases your revenue from online sales.

    We’ve provided you with detailed instructions on integrating Google Pay into your Android app. If you have any further questions on integrating this or any other payment gateway into your app, be sure to contact us.

    Our engineers have experience creating enterprise-sized e-commerce applications as well as mobile apps for small retailers and have a knack for integrating payment services into digital solutions that sell.

    Ecommerce development services

    Are you planning to expand your business online? We will translate your ideas into intelligent and powerful ecommerce solutions.

    Get a Free Consultation!
    Contact Us

    Contact Us

    +