콘텐츠로 건너뛰기

자주 방문한 페이지

최근 방문한 페이지

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 = 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.

이 사이트는 쿠키를 사용하여 사이트별 언어 및 표시 옵션에 대한 환경설정을 저장합니다.

Google Play에서 성공을 거두는 데 도움이 되는 최신 Android 개발자 뉴스 및 도움말을 받아 보세요.

* 필수 입력란

완료되었습니다.

WeChat에서 Google Developers 팔로우하기

이 사이트를 (으)로 탐색할까요?

페이지를 요청했지만 이 사이트의 언어 환경설정은 입니다.

언어 환경설정을 변경하고 이 사이트를 (으)로 탐색할까요? 언어 환경설정을 나중에 변경하려면 각 페이지 하단의 언어 메뉴를 사용하세요.

이 클래스를 사용하려면 API 수준 이상이 필요합니다.

문서에 대해 선택한 API 수준이 이므로 이 문서가 표시되지 않습니다. 왼쪽 탐색 메뉴의 선택기로 문서 API 수준을 변경할 수 있습니다.

앱에 필요한 API 수준 지정에 관한 자세한 내용은 다양한 플랫폼 버전 지원을 참조하세요.

Take a short survey?
Help us improve the Android developer experience. (April 2018 — Developer Survey)