google play billing library 文档备查

来源:互联网 发布:如何利用淘宝赚钱 编辑:程序博客网 时间:2024/05/23 23:58


Play Billing Library

  1. Updating your app's dependencies
  2. Connecting to Google Play
  3. Retrieve existing purchases and subscriptions
  4. Making In-app Billing requests
    1. Querying for items available for purchase
    2. Purchasing an item
    3. Querying for purchased items
    4. Consuming a purchase
    5. Implementing subscriptions

In-app Billing on Google Play provides a straightforward and simple interface for sending In-app Billing requests and managing In-app Billing transactions using Google Play. The information below covers the basics of how to make calls from your app to Google Play using the Play Billing Library.

The Play Billing Library is written in Java and provides convenience classes and features, which you can use to implement in-app billing into your Android apps. The library is a wrapper for the Android Interface Definition Language (AIDL) file that defines the interface to the In-app Billing service. You can use the Play Billing Library to simplify your development process, allowing you to focus your effort on implementing logic specific to your app, such as displaying in-app products and purchasing items.

Note: To see a complete example and learn how to test your app, see the Play Billing Library training class. The training class provides a complete sample In-app Billing app, including convenience classes to handle key tasks that are related to setting up your connection, sending billing requests, processing responses from Google Play, and managing In-app Billing calls from your main activity.

Note: If you are integrating the In-app Billing service in your app using an alternative language such as C++, or you want to interact directly with the AIDL file, see Implementing In-app Billing.

Before you start, read the In-app Billing Overview to familiarize yourself with concepts and terminology that make it easier for you to implement In-app Billing using the Play Billing Library.

Complete the following steps to use the Play Billing Library in your app:

  1. Update the dependencies in your app's build.gradle file.
  2. Create a billing library client.
  3. Connect to Google Play.
  4. Send In-app Billing requests from your app to Google Play.
  5. Handle In-app Billing responses from Google Play.

Updating your app's dependencies


Add the following line to the dependencies section of the build.gradle file for your app:

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

Connecting to Google Play


Before you can use the Play Billing Library client, you must first establish a connection to Google Play using the following steps:

  1. Call the newBuilder() method to create an instance of BillingClient class, the Play Billing Library client. You must also call the setListener()method and pass it a reference to an instance of PurchasesUpdatedListener to receive updates on purchases initiated by your app, as well as those initiated by Google Play Store.
  2. Establish a connection to Google Play. The setup process is asynchronous and you must implement a BillingClientStateListener to receive a callback once the setup of the client is complete and it’s ready to make further requests.
  3. Override the onBillingServiceDisconnected() callback method and implement your own retry policy to handle lost connections to Google Play in the event the client loses connection. For example, the Play Billing Library client may lose connection if the Play Store service is updating in the background. The Play Billing Library client must call the startConnection() method to restart the connection before making further requests.

The following code sample demonstrates how to start a connection and then test that it's ready to use:

private BillingClient mBillingClient;...mBillingClient = BillingClient.newBuilder(mActivity).setListener(this).build();mBillingClient.startConnection(new BillingClientStateListener() {    @Override    public void onBillingSetupFinished(@BillingResponse int billingResponseCode) {        if (billingResponseCode == BillingResponse.OK) {            // The billing client is ready. You can query purchases here.        }    }    @Override    public void onBillingServiceDisconnected() {        // Try to restart the connection on the next request to        // Google Play by calling the startConnection() method.    }});

Important: It's strongly recommended that you implement your own connection retry policy and override the onBillingServiceDisconnected()method. Make sure you maintain the billing client connection when executing any methods. You can see an example of a basic retry policy inside the executeServiceRequest method in the BillingManager class from the Trivial Drive v2 sample app.

Retrieve existing purchases and subscriptions


Google Play calls the onPurchasesUpdated() method to deliver the result of the purchase operation to a listener that implements thePurchasesUpdatedListener interface. You specify this listener using the setListener() method when creating an instance of the Play Billing Library client.

Attention: It is important to process existing purchases when the user launches your app. The user can buy products and subscriptions on different devices, so your app needs to respond to existing purchases even if the current device has not initiated any purchases.

The following code demonstrates how you could override the onPurchasesUpdated() method:

@Overridevoid onPurchasesUpdated(@BillingResponse int responseCode,        List<Purchase> purchases) {    if (responseCode == BillingResponse.OK            && purchases != null) {        for (Purchase purchase : purchases) {            handlePurchase(purchase);        }    } else if (responseCode == BillingResponse.USER_CANCELED) {        // Handle an error caused by a user cancelling the purchase flow.    } else {        // Handle any other error codes.    }}

You can control how the user consumes the item in your app and notify Google Play to make the item available for purchase again. You can also query Google Play to quickly retrieve the list of purchases and subscriptions that the user made. Make sure to perform this check every time your app launches to restore any purchases and subscriptions that a user may have made since your app last stopped.

Making In-app Billing requests


Once the Play Billing Library client connects to Google Play, you can initiate purchase requests for in-app products and subscriptions. Google Play provides a checkout interface for users to enter their payment method, so your app doesn't need to handle payment transactions directly. When a user purchases an item or subscription, Google Play recognizes that the user has ownership of that item and prevents the user from purchasing another item with the same product ID until they have consumed the item, or until the subscription is no longer active.

Querying for items available for purchase

You can use the Play Billing Library in your app to asynchronously query the item details for unique Product IDs from Google Play. To make a request to Google Play, call the querySkuDetailsAsync() method on the Play Billing Library client. Pass this method an instance of SkuDetailsParams that specifies a list of items SKUs (products ID strings) and a SkuType . You can set the purchase type to SkuType.INAPP, for purchases, or SkuType.SUBS, for subscriptions.

Note: You define the product IDs required to perform queries when you create a product list for your app using the Google Play Console. For more information about creating a product list, see Administering In-app Billing.

To handle the result of the asynchronous operation, you must also specify a listener which implements the SkuDetailsResponseListener interface. You can then override the onSkuDetailsResponse() method which notifies the listener when the query finishes, as illustrated by the following sample code:

List<String> skuList = new ArrayList<> ();skuList.add("premium_upgrade");skuList.add("gas");SkuDetailsParams.Builder params = SkuDetailsParams.newBuilder();params.setSkusList(skuList).setType(SkuType.INAPP);mBillingClient.querySkuDetailsAsync(params.build(),    new SkuDetailsResponseListener() {        @Override        public void onSkuDetailsResponse(SkuDetailsResult result) {            // Process the result.        }    });

If the request is successful, the response code is BillingResponse.OK (0). To view all of the possible response codes from Google Play, seeBillingClient.BillingResponse Reference.

The Play Billing Library stores the query results in a List of SkuDetails objects. You can then call a variety of methods on each of the SkuDetailsobjects in the list to view relevant information about an item, such as its price or description. To view the types of product detail information that are available, see the list of methods in the SkuDetails class.

The following example shows how to retrieve the prices for your in-app items from each SkuDetails object returned by the previous code snippet:

if (responseCode == BillingResponse.OK                    && skuDetailsList != null) {   for (SkuDetails skuDetails : skuDetailsList) {       String sku = skuDetails.getSku();       String price = skuDetails.getPrice();       if ("premium_upgrade".equals(sku)) {           mPremiumUpgradePrice = price;       } else if ("gas".equals(sku)) {           mGasPrice = price;       }   }}

Purchasing an item

To start a purchase request from your app, call the launchBillingFlow() method on the Play Billing Library client. You must call thelaunchBillingFlow() method from the UI thread.

Note: Before launching a billing flow, call the isFeatureSupported() method on the Play Billing Library client to check that the device supports purchases with the required type, such as FeatureType.SUBSCRIPTIONS, as well as the specific form factor you are using, such as FeatureType.IN_APP_ITEMS_ON_VR.

Pass the launchBillingFlow() method a reference to a BillingFlowParams object that contains the relevant data to complete the purchase, such as the product ID of the item to purchase and the purchase type, in this case SkuType.INAPP. To get an instance of BillingFlowParams , use theBillingFlowParams.Builder class.

When you call the launchBillingFlow() method, the system displays the Google Play UI purchase screen. The operation returns a response code as illustrated by the following sample code:

BillingFlowParams flowParams = BillingFlowParams.newBuilder()                                                .setSku(skuId)                                                .setType(SkuType.INAPP)                                                .build();int responseCode = mBillingClient.launchBillingFlow(flowParams);

If you initiate a purchase flow by calling launchBillingFlow() from your app and made sure that your client is ready and this item is allowed for purchasing, then Google Play guarantees to call the onPurchasesUpdated() method. Google Play calls the onPurchasesUpdated() method in the same cases that onActivityResult() is called, when you start another activity by calling startActivityForResult(). If the user cancels a billing flow, Google Play calls the onPurchasesUpdated() method with a null list of purchases and the BillingResponse.USER_CANCELED response code.

Security Recommendation: When you receive the purchase response from Google Play, perform a secure validation on your own backend. Don't trust the client, since an Android app could be decompiled and your security checks replaced with stubs. Instead, call the get() method on thePurchases.subscriptions resource (for subscriptions) or the Purchases.products resource (for products) from the Subscriptions and In-App Purchases API, or check the returned data signature.

Attention: It may take some time for Google Play to update the local cache. If your user makes a purchase from one device, any other devices they are using are not updated immediately.

After the purchase is complete, Google Play calls the onPurchasesUpdated(). For more information, see Retrieve Existing Purchases and Subscriptions.

Querying for purchased items

To retrieve information about purchases that a user makes from your app, call the queryPurchases() method on the Play Billing Library client. Pass the purchase type into the method, in this case SkuType.INAPP, as illustrated by the following example:

PurchasesResult purchasesResult = mBillingClient.queryPurchases(SkuType.INAPP);

The Google Play service returns the purchases made by the user account logged in to the device. If the request is successful, the Play Billing Library stores the query results in a List of Purchase objects. To retrieve the list, call the getPurchasesList() method on the PurchasesResult object. You can then call a variety of methods on the Purchase object to view relevant information about the item, such as its purchase state or time. To view the types of product detail information that are available, see the list of methods in the Purchase class.

The queryPurchases() method uses a cache of the Google Play Store app without initiating a network request. If you need to check the most recent purchase made by the user for each SKU, you can use the queryPurchaseHistoryAsync() method and pass the purchase type and a PurchaseHistoryResponseListener to handle the query result.

queryPurchaseHistoryAsync() returns the most recent purchase made by the user for each SKU, even if that purchase is expired, canceled, or consumed. Use the queryPurchases() method whenever possible as it uses the local cache, in preference to the queryPurchaseHistoryAsync() method.

If the request is successful, the response code is BillingResponse.OK (0). To view all of the possible response codes from Google Play, see Play Billing Library Reference. The Play Billing Library stores the query results in a List of Purchase objects. To view the types of purchase detail information that are available, see the list of methods in the Purchase class.

The following code demonstrates how you can override the onPurchaseHistoryResponse() method:

mBillingClient.queryPurchaseHistoryAsync(SkuType.INAPP,                                         new PurchaseHistoryResponseListener() {    @Override    public void onPurchaseHistoryResponse(@BillingResponse int responseCode,                                          List<Purchase> purchasesList) {        if (responseCode == BillingResponse.OK                && purchasesList != null) {            for (Purchase purchase : purchasesList) {                // Process the result.            }         }    }});

Consuming a purchase

You can use the Play Billing Library to track the ownership of purchased in-app products in Google Play. Once a user purchases an in-app product, it's considered to be owned and the user cannot purchase it from Google Play. You must send a consumption request for the in-app product before Google Play makes it available for purchase again.

Important: Managed in-app products are consumable, but subscriptions are not.

The way that you use the consumption mechanism in your app is up to you. It's common to implement consumption for in-app products that provide temporary benefits which users may want to purchase multiple times, such as in-game currency or equipment. You typically don't want to implement consumption for in-app products that a user purchases once and provide a permanent effect, such as a premium upgrade.

To record a purchase consumption, call the consumeAsync() method on the Play Billing Library client and pass in the purchaseToken String value that identifies the purchase that Google Play must remove. You must also pass an object that implements the ConsumeResponseListener interface to handle the result of the consumption operation. You can override the onConsumeResponse() method of the ConsumeResponseListener interface, which the Play Billing Library calls when the operation is complete.

The purchaseToken is part of the data that the Play Billing Library returns for each Purchase object in the list of Purchase objects returned in aPurchasesResult object by the Google Play service following a successful purchase request. You can call the getPurchaseToken() method on a Purchase object to retrieve the token associated with a purchase.

The following example illustrates consuming a product using the associated purchaseToken:

ConsumeResponseListener listener = new ConsumeResponseListener() {    @Override    public void onConsumeResponse(@BillingResponse int responseCode, String outToken) {            if (responseCode == BillingResponse.OK) {                // Handle the success of the consume operation.                // For example, increase the number of coins inside the user's basket.    }};mBillingClient.consumeAsync(purchaseToken, listener);

It's your responsibility to control and track how your app provisions the in-app product to the user. For example, if the user purchased in-game currency, you must update the player's inventory with the amount of currency purchased.

Security Recommendation: Do not provision the benefits of a consumable in-app purchase more than once. Since consumption requests can occasionally fail, you must check your secure backend sever to ensure that each purchase token has not already been used before. Alternatively, you can wait until you receive a successful consumption response from Google Play before you provision the item. If you choose to withhold goods from the user until Google Play sends a successful consumption response, you must be very careful not to lose track of the purchase after the consumption request. If you send a consumption request and fail to deliver the goods, users will not be able to get access to content they have purchased.

Implementing subscriptions

Launching a billing flow to purchase or renew a subscription is similar to launching the purchase flow for a product, with the exception that you must set the product type to SkuType.SUBS.

To start a purchase request from your app, call the launchBillingFlow() method on the Play Billing Library client. Before launching a billing flow, check that the device supports subscriptions by calling the isFeatureSupported() method on the Play Billing Library client. Pass the launchBillingFlow()method a reference to a BillingFlowParams object that contains the relevant data to complete the purchase, such as the product ID of the item to subscribe to, and the product type, in this case SkuType.SUBS. If the user is changing SKUs, which you must do if a user is upgrading or downgrading a subscription, you must also pass the product IDs for the subscription items you are replacing in the BillingFlowParams object using the addOldSku()method. You can create an instance of BillingFlowParams using the BillingFlowParams.Builder class.

Calling the launchBillingFlow() method displays the Google Play UI purchase screen. The operation returns a response code as illustrated by the following sample code:

BillingFlowParams.Builder builder = BillingFlowParams.newBuilder()        .setSku(skuId).setType(SkuType.SUBS);int responseCode = mBillingClient.launchBillingFlow(builder.build());// Make sure to implement a retry policy to handle interrupted connections.

Google Play returns the result of the operation using the onPurchasesUpdated() callback as described in Purchasing an item.



原创粉丝点击