Skip to content

Most visited

Recently visited

navigation

Preparing Your In-app Billing App

Before you can start using the In-app Billing service, you must add the Play Billing Library to your Android project. In addition, you must establish a connection between your app and Google Play.

Note: This training class explains how to integrate the Play Billing Library into a sample app. For a more general introduction to the library, see Play Billing Library.

Download the sample app

All the code discussed in this training class is available as a reference sample app for the Play Billing Library called TrivialDrive_v2. To download the sample app, complete the following steps:

  1. In Android Studio, select File > New > Import Sample.

  2. Type Trivial Drive into the search bar and select the TrivialDrive_v2 sample. Follow the rest of the wizard to import the sample to a directory of your choosing.

Alternatively, you can use Git to manually clone the repository from the Google Samples GitHub site.

Important: You cannot run this sample app as-is. It requires a unique license key from the Google Play Console. For instructions, see the README file at the root of the TrivialDrive_v2 project directory.

Add your app to the Google Play Console

The Google Play Console is where you publish your In-app Billing app and manage the various digital products that are available for purchase from your app. When you create a new app entry in the Play Console, it automatically generates a public license key for your app. You need this key to establish a trusted connection from your app to the Google Play servers. You only have to generate this key once per app, and you don't have to repeat these steps when you update the APK file for your app.

To add your app to the Play Console, follow these steps:

  1. Go to the Google Play Console site and log in. If you have not registered previously, you must register for a new account. To sell in-app products, you also need a Google payments merchant account.

  2. In the All Applications tab, complete these steps to add a new app entry:

    a. Click CREATE APPLICATION.

    b. Enter a name for your new In-app Billing app.

    c. Click CREATE.

  3. Select Services and APIs from the left-hand side menu of the console to find and make a note of the public license key that Google Play generated for your app. This is a Base64 string that you must include in your app code later.

Your app should now appear in the list of apps in Play Console.

Update your app's dependencies

You must update your app's dependencies to add the Play Billing LIbrary to your project. Add the following line to the dependencies section of the build.gradle file in the app module:

dependencies {
    ...
    compile 'com.android.billingclient:billing:1.0'
}

Initiate a connection with Google Play

In this training lesson, you create a BillingManager class and assign it responsibility for interacting with the In-app Billing service using the Play Billing Library. To establish a connection to the In-app Billing service, you must initialize the Play Billing Library client from the constructor of the BillingManager class and call the startConnection() method to initiate a connection.

The startConnection() method runs asynchronously and you must specify a listener to receive confirmation that the connection is complete as illustrated by the following sample code:

public class BillingManager implements PurchasesUpdatedListener {
...
    public BillingManager(Activity activity, final BillingUpdatesListener updatesListener) {
        mActivity = activity;
        mBillingUpdatesListener = updatesListener;
        mBillingClient = new BillingClient.newBuilder(mActivity).setListener(this).build();

        // Start the setup asynchronously.
        // The specified listener is called once setup completes.
        // New purchases are reported through the onPurchasesUpdated() callback
        // of the class specified using the setListener() method above.
        startServiceConnection(new Runnable() {
            @Override
            public void run() {
                // Notify the listener that the billing client is ready.
                mBillingUpdatesListener.onBillingClientSetupFinished();
                // IAB is fully setup. Now get an inventory of stuff the user owns.
                queryPurchases();
            }
        });
    }
    ...
    public void startServiceConnection(final Runnable executeOnSuccess) {
        mBillingClient.startConnection(new BillingClientStateListener() {
            @Override
            public void onBillingSetupFinished(@BillingResponse int billingResponseCode) {
                Log.d(TAG, "Setup finished. Response code: " + billingResponseCode);

                if (billingResponseCode == BillingResponse.OK) {
                    mIsServiceConnected = true;
                    if (executeOnSuccess != null) {
                        executeOnSuccess.run();
                    }
                }
                mBillingClientResponseCode = billingResponseCode;
            }

            @Override
            public void onBillingServiceDisconnected() {
                mIsServiceConnected = false;
            }
        });
    }
}

Handle billing events

You can create listener methods to handle responses from the Play Billing Library. In this training lesson you define an interface called BillingUpdatesListener in the BillingManager class and implement the related methods in a view controller class. Add the BillingUpdatesListener interface to the BillingManager class as illustrated by the following code:

public interface BillingUpdatesListener {
    void onBillingClientSetupFinished();
    void onConsumeFinished(String token, @BillingResponse int result);
    void onPurchasesUpdated(List<Purchase> purchases);
}

You must assign responsibility for the role of the BillingUpdatesListener listener to an appropriate class in your app. In this lesson, you assign responsibility for the role of this listener to a view controller class. You implement the BillingUpdatesListener interface in the view controller and notify an appropriate activity or fragment that the Play Billing Library client is ready, as illustrated by the following sample code:

public class MainViewController {
    ...
    private class UpdateListener implements BillingUpdatesListener {
        @Override
        public void onBillingClientSetupFinished() {
            mActivity.onBillingManagerSetupFinished();
        }
    ...
}

You can then create an instance of the view controller from the onCreate() method of an activity or fragment. You can also create an instance of the BillingManager class and pass it a reference to the view controller as illustrated by the following sample code:

public abstract class BaseGamePlayActivity extends FragmentActivity implements BillingProvider {
    ...
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(getLayoutResId());

        mViewController = new MainViewController(this);
        ...
        mBillingManager = new BillingManager(this, mViewController.getUpdateListener());
    }
    ...
}

Note: If you are not using a view controller architecture, you can create an appropriate listener using an alternative design pattern in your app.

This site uses cookies to store your preferences for site-specific language and display options.

Get the latest Android developer news and tips that will help you find success on Google Play.

* Required Fields

Hooray!

Follow Google Developers on WeChat

Browse this site in ?

You requested a page in , but your language preference for this site is .

Would you like to change your language preference and browse this site in ? If you want to change your language preference later, use the language menu at the bottom of each page.

This class requires API level or higher

This doc is hidden because your selected API level for the documentation is . You can change the documentation API level with the selector above the left navigation.

For more information about specifying the API level your app requires, read Supporting Different Platform Versions.

Take a short survey?
Help us improve the Android developer experience.
(Sep 2017 survey)