The Google Pay API introduced the PayButton API on Android. This guide explains how to update from the Google Pay payment button formatted with static assets to the new configurable Google Pay view.
The new Google Pay button view lets you customize the button theme, shape and corner roundness to match your UI design.
The "Buy" and "Pay" payment buttons provide a personalized experience to users discover when they have an eligible card in their Google Pay account.
Setup dependencies
app/build.gradle
for:
dependencies { implementation 'com.google.android.gms:play-services-wallet:19.4.0' }
Add new payment button to application
Add the PayButton layout to your application’s checkout layout, which is
commonly on the app/main/res/layout/activity_checkout.xml
:
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" xmlns:wallet="http://schemas.android.com/apk/res-auto"> <com.google.android.gms.wallet.button.PayButton android:id="@+id/google_pay_payment_button" wallet:buttonTheme="dark" wallet:cornerRadius="100" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="0.5"/> </LinearLayout>
Initialize the payment button
In the Android activity (for example, in the onCreate
method), initialize the
payment button:
PayButton payButton = layoutBinding.googlePayPaymentButton; JSONArray paymentMethods = new JSONArray().put(getBaseCardPaymentMethod()); payButton.initialize( ButtonOptions.newBuilder() .setButtonTheme(ButtonConstants.ButtonTheme.DARK) .setButtonType(ButtonConstants.ButtonType.BUY) .setCornerRadius(100) .setAllowedPaymentMethods(paymentMethods.toString()) .build() );
Initialize the Google Pay buy-flow
In the Android activity (for example, in the onCreate
method), initialize the
Google Pay buy-flow when the user clicks in the payment button:
payButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { paymentsClient.loadPaymentData(paymentDataRequest); } });
Show or hide the payment button
In the Android activity (for example, in the onCreate
method), hide the payment button
when the user isn't ready-to-pay:
Task<Boolean> task = paymentsClient.isReadyToPay(request); task.addOnCompleteListener( completedTask -> { if (completedTask.isSuccessful()) { completedTask.getResult()? payButton.setVisible(View.VISIBLE) : payButton.setVisible(View.GONE); } else { Log.w("isReadyToPay failed", completedTask.getException()); payButton.setVisible(View.GONE); } });