Do I Have to Buy the App Again on Google Play

This topic describes how to integrate the Google Play Billing Library into your app to start selling products. Before reading this topic, exist certain you've gear up your Google Play configuration beforehand by following the steps in Getting fix.

This topic includes code examples that are based on the official sample apps on GitHub. See additional resources for a complete list of sample apps and other resource that you lot can utilize while integrating.

Life of a purchase

Here's a typical purchase catamenia for a one-time buy or a subscription.

  • Show the user what they can buy.
  • Launch the buy menstruum for the user to accept the purchase.
  • Verify the purchase on your server.
  • Give content to the user, and admit delivery of the content. Optionally, marking the item every bit consumed and then that the user can purchase the detail again.

Subscriptions automatically renew until they are canceled. A subscription can go through the following states:

  • Active: User is in skillful standing and has admission to the subscription.
  • Cancelled: User has cancelled simply nonetheless has access until expiration.
  • In grace menstruation: User experienced a payment upshot, but still has access while Google is retrying the payment method.
  • On agree: User experienced a payment event, and no longer has access while Google is retrying the payment method.
  • Paused: User paused their admission, and does not have admission until they resume.
  • Expired: User has cancelled and lost access to the subscription. The user is considered churned at expiration.

Purchase tokens and Order IDs

Google Play tracks products and transactions using purchase tokens and Order IDs.

  • A buy token is a string that represents a buyer's entitlement to a product on Google Play. It indicates that a Google user is entitled to a specific production that is represented by a SKU. Yous can use the purchase token with the Google Play Developer API.
  • An Order ID is a string that represents a financial transaction on Google Play. This string is included in a receipt that is emailed to the buyer. You can apply the Order ID to manage refunds in the used in sales and payout reports.

Order IDs are created every time a financial transaction occurs. Purchase tokens are generated only when a user completes a purchase menstruation.

  • For one-time products, every purchase creates a new purchase token. Most purchases also generate a new Order ID. The exception to this is when the user is not charged any money, every bit described in Promo codes.
  • For subscriptions, an initial purchase creates a purchase token and an Order ID. For each continuous billing catamenia, the purchase token stays the aforementioned, and a new Order ID is issued. Upgrades, downgrades, replacements, and re-sign-ups all create new purchase tokens and Order IDs.

For subscriptions, note the post-obit:

  • Subscription upgrades, downgrades, and other subscription buy flows generate buy tokens that must supplant a previous purchase token. Yous must invalidate the purchase tokens that appear in the linkedPurchaseToken field of the Google Play Developer API. For more information, see Implementing linkedPurchaseToken correctly to forestall duplicate subscriptions.
  • Order numbers for subscription renewals contain an additional integer that represents a specific renewal case. For example, an initial subscription Order ID might be GPA.1234-5678-9012-34567 with subsequent Order IDs being GPA.1234-5678-9012-34567..0 (first renewal), GPA.1234-5678-9012-34567..1 (second renewal), and so on.

Mistake Treatment

The Google Play Billing Library returns errors in the form of BillingResult. A BillingResult contains a BillingResponseCode, which categorizes possible billing-related errors that your app can run into. For example, if y'all receive a SERVICE_DISCONNECTED error code, your app should reinitialize the connection with Google Play. Additionally, a BillingResult contains a debug message, which is useful during development to diagnose errors.

Connect to Google Play

The first step to integrate with Google Play'due south billing system is to add the library to your app and initialize a connexion.

Add the Google Play Billing Library dependency

Add the Google Play Billing Library dependency to your app'southward build.gradle file as shown:

Bang-up

dependencies {     def billing_version = "4.ane.0"      implementation "com.android.billingclient:billing:$billing_version" }

Kotlin

dependencies {     val billing_version = "4.1.0"      implementation("com.android.billingclient:billing:$billing_version") }

If y'all're using Kotlin, the Play Billing Library KTX module contains Kotlin extensions and coroutines support that enable you to write idiomatic Kotlin when using the Google Play Billing Library. To include these extensions in your projection, add the following dependency to your app's build.gradle file as shown:

Groovy

dependencies {     def billing_version = "four.1.0"      implementation "com.android.billingclient:billing-ktx:$billing_version" }            

Kotlin

dependencies {     val billing_version = "4.1.0"      implementation("com.android.billingclient:billing-ktx:$billing_version") }            

Initialize a BillingClient

In one case you've added a dependency on the Google Play Billing Library, y'all need to initialize a BillingClient case. BillingClient is the principal interface for advice between the Google Play Billing Library and the residue of your app. BillingClient provides convenience methods, both synchronous and asynchronous, for many common billing operations. It's strongly recommended that you take 1 active BillingClient connectedness open up at one time to avoid multiple PurchasesUpdatedListener callbacks for a single event.

To create a BillingClient, use newBuilder(). You can pass whatsoever context to newBuilder(), and BillingClient uses it to get an application context. That ways you don't need to worry about memory leaks. To receive updates on purchases, y'all must also call setListener(), passing a reference to a PurchasesUpdatedListener. This listener receives updates for all purchases in your app.

Kotlin

private val purchasesUpdatedListener =    PurchasesUpdatedListener { billingResult, purchases ->        // To be implemented in a later department.    }  private var billingClient = BillingClient.newBuilder(context)    .setListener(purchasesUpdatedListener)    .enablePendingPurchases()    .build()            

Java

private PurchasesUpdatedListener purchasesUpdatedListener = new PurchasesUpdatedListener() {     @Override     public void onPurchasesUpdated(BillingResult billingResult, List<Purchase> purchases) {         // To be implemented in a later section.     } };  individual BillingClient billingClient = BillingClient.newBuilder(context)     .setListener(purchasesUpdatedListener)     .enablePendingPurchases()     .build();            

Establish a connectedness to Google Play

After you accept created a BillingClient, y'all demand to establish a connection to Google Play.

To connect to Google Play, telephone call startConnection(). The connexion procedure is asynchronous, and you must implement a BillingClientStateListener to receive a callback once the setup of the client is consummate and it's set to make further requests.

Yous must also implement retry logic to handle lost connections to Google Play. To implement retry logic, override the onBillingServiceDisconnected() callback method, and make certain that the BillingClient calls the startConnection() method to reconnect to Google Play before making further requests.

The post-obit instance demonstrates how to start a connection and exam that it'southward fix to use:

Kotlin

billingClient.startConnection(object : BillingClientStateListener {     override fun onBillingSetupFinished(billingResult: BillingResult) {         if (billingResult.responseCode ==  BillingResponseCode.OK) {             // The BillingClient is prepare. Y'all tin can query purchases here.         }     }     override fun onBillingServiceDisconnected() {         // Try to restart the connection on the next request to         // Google Play by calling the startConnection() method.     } })            

Java

billingClient.startConnection(new BillingClientStateListener() {     @Override     public void onBillingSetupFinished(BillingResult billingResult) {         if (billingResult.getResponseCode() ==  BillingResponseCode.OK) {             // The BillingClient is set. You tin can query purchases hither.         }     }     @Override     public void onBillingServiceDisconnected() {         // Endeavor to restart the connection on the next request to         // Google Play by calling the startConnection() method.     } });            

Show products available to purchase

Afterward you take established a connectedness to Google Play, you are set to query for your available products and display them to your users. To query Google Play for in-app production details, call querySkuDetailsAsync(). Querying for SKU details is an important step before displaying your products to your users, equally it returns localized product information. For subscriptions, ensure your product display follows all Play policies.

When calling querySkuDetailsAsync(), laissez passer an instance of SkuDetailsParams that specifies a list of product ID strings created in Google Play Console along with a SkuType. The SkuType tin exist either SkuType.INAPP for one-fourth dimension products or SkuType.SUBS for subscriptions.

To handle the upshot of the asynchronous functioning, y'all must also specify a listener which implements the SkuDetailsResponseListener interface. You can and then override onSkuDetailsResponse(), which notifies the listener when the query finishes, as shown in the following example:

Kotlin

append fun querySkuDetails() {     val skuList = ArrayList<String>()     skuList.add("premium_upgrade")     skuList.add("gas")     val params = SkuDetailsParams.newBuilder()     params.setSkusList(skuList).setType(SkuType.INAPP)      // leverage querySkuDetails Kotlin extension function     val skuDetailsResult = withContext(Dispatchers.IO) {         billingClient.querySkuDetails(params.build())     }      // Process the event. }            

Java

List<Cord> skuList = new ArrayList<> (); skuList.add("premium_upgrade"); skuList.add("gas"); SkuDetailsParams.Architect params = SkuDetailsParams.newBuilder(); params.setSkusList(skuList).setType(SkuType.INAPP); billingClient.querySkuDetailsAsync(params.build(),     new SkuDetailsResponseListener() {         @Override         public void onSkuDetailsResponse(BillingResult billingResult,                 List<SkuDetails> skuDetailsList) {             // Process the event.         }     });            

The Google Play Billing Library stores the query results in a List of SkuDetails objects. Y'all tin and so call a diverseness of methods on each SkuDetails object in the list to view relevant data about an in-app product, such equally its price or description. To view the available product detail information, run into the listing of methods in the SkuDetails class.

Before offering an detail for sale, bank check that the user does non already own the item. If the user has a consumable that is nevertheless in their item library, they must consume the item before they tin can buy information technology again.

Before offer a subscription, verify that the user is not already subscribed.

Launch the purchase flow

To start a purchase request from your app, call the launchBillingFlow() method from your app's primary thread. This method takes a reference to a BillingFlowParams object that contains the relevant SkuDetails object obtained from calling querySkuDetailsAsync(). To create a BillingFlowParams object, utilise the BillingFlowParams.Builder course.

Kotlin

// An activeness reference from which the billing flow will be launched. val activeness : Activity = ...;  // Retrieve a value for "skuDetails" by calling querySkuDetailsAsync(). val flowParams = BillingFlowParams.newBuilder()         .setSkuDetails(skuDetails)         .build() val responseCode = billingClient.launchBillingFlow(action, flowParams).responseCode            

Java

// An activeness reference from which the billing flow will be launched. Activity activity = ...;  // Recall a value for "skuDetails" by calling querySkuDetailsAsync(). BillingFlowParams billingFlowParams = BillingFlowParams.newBuilder()         .setSkuDetails(skuDetails)         .build(); int responseCode = billingClient.launchBillingFlow(activity, billingFlowParams).getResponseCode();  // Handle the outcome.            

The launchBillingFlow() method returns one of several response codes listed in BillingClient.BillingResponseCode. Be certain to bank check this result to ensure there were no errors launching the purchase flow. A BillingResponseCode of OK indicates a successful launch.

On a successful telephone call to launchBillingFlow(), the system displays the Google Play purchase screen. Figure 1 shows a purchase screen for a subscription:

the google play purchase screen shows a subscription that is              available for purchase
Figure ane. The Google Play purchase screen shows a subscription that is available for purchase.

Google Play calls onPurchasesUpdated() to deliver the result of the purchase performance to a listener that implements the PurchasesUpdatedListener interface. The listener is specified using the setListener() method when you initialized your client.

You must implement onPurchasesUpdated() to handle possible response codes. The post-obit instance shows how to override onPurchasesUpdated():

Kotlin

override fun onPurchasesUpdated(billingResult: BillingResult, purchases: List<Purchase>?) {    if (billingResult.responseCode == BillingResponseCode.OK && purchases != nil) {        for (buy in purchases) {            handlePurchase(purchase)        }    } else if (billingResult.responseCode == BillingResponseCode.USER_CANCELED) {        // Handle an fault acquired past a user cancelling the purchase menstruum.    } else {        // Handle any other fault codes.    } }            

Java

@Override void onPurchasesUpdated(BillingResult billingResult, List<Purchase> purchases) {     if (billingResult.getResponseCode() == BillingResponseCode.OK         && purchases != null) {         for (Purchase purchase : purchases) {             handlePurchase(buy);         }     } else if (billingResult.getResponseCode() == BillingResponseCode.USER_CANCELED) {         // Handle an error caused by a user cancelling the buy menses.     } else {         // Handle any other error codes.     } }            

A successful purchase generates a Google Play purchase success screen similar to figure 2.

google play's purchase success screen
Figure 2. Google Play'due south purchase success screen.

A successful purchase too generates a buy token, which is a unique identifier that represents the user and the product ID for the in-app product they purchased. Your apps tin can store the purchase token locally, though nosotros recommend passing the token to your secure backend server where yous can so verify the purchase and protect against fraud. This process is further described in the post-obit section.

The user is besides emailed a receipt of the transaction containing an Order ID or a unique ID of the transaction. Users receive an electronic mail with a unique Order ID for each sometime production purchase, and besides for the initial subscription purchase and subsequent recurring automatic renewals. You lot can use the Gild ID to manage refunds in the Google Play Console.

Processing purchases

Once a user completes a purchase, your app so needs to process that purchase. In most cases, your app is notified of purchases through your PurchasesUpdatedListener. just at that place are cases where your app is made enlightened of calling BillingClient.queryPurchasesAsync() as described in Fetching purchases.

Your app should process a purchase in the following mode:

  1. Verify the buy.
  2. Give content to the user, and acknowledge delivery of the content. Optionally, mark the item as consumed so that the user can buy the item again.

To verify a buy, beginning check that the purchase country is PURCHASED. If the purchase is Pending, so you lot should procedure the purchase as described in Handling awaiting transactions. For purchases received from onPurchasesUpdated() or queryPurchasesAsync, you should further verify the purchase to ensure legitimacy before your app grants entitlement. To learn how to properly verify a buy, run into Verify purchases before granting entitlements.

In one case y'all've verified the buy, your app is ready to grant entitlement to the user. Subsequently granting entitlement, your app must then acknowledge the purchase. This acknowledgement communicates to Google Play that you have granted entitlement for the purchase.

The process to grant entitlement and acknowledge the purchase depends on whether the buy is a non-consumable, a consumable, or a subscription.

For consumables, the consumeAsync() method fulfills the acknowledgement requirement and indicates that your app has granted entitlement to the user. This method also enables your app to make the one-time product bachelor for purchase again.

To bespeak that a ane-time product has been consumed, phone call consumeAsync() and include the buy token that Google Play should make available for repurchase. You must also pass an object that implements the ConsumeResponseListener interface. This object handles the result of the consumption functioning. You tin can override the onConsumeResponse() method, which the Google Play Billing Library calls when the functioning is complete.

The following case illustrates consuming a product using the associated buy token:

Kotlin

suspend fun handlePurchase(buy: Buy) {     // Purchase retrieved from BillingClient#queryPurchasesAsync or your PurchasesUpdatedListener.     val purchase : Purchase = ...;      // Verify the buy.     // Ensure entitlement was not already granted for this purchaseToken.     // Grant entitlement to the user.      val consumeParams =         ConsumeParams.newBuilder()             .setPurchaseToken(buy.getPurchaseToken())             .build()     val consumeResult = withContext(Dispatchers.IO) {         client.consumePurchase(consumeParams)     } }            

Java

void handlePurchase(Buy buy) {     // Purchase retrieved from BillingClient#queryPurchasesAsync or your PurchasesUpdatedListener.     Purchase buy = ...;      // Verify the purchase.     // Ensure entitlement was not already granted for this purchaseToken.     // Grant entitlement to the user.      ConsumeParams consumeParams =         ConsumeParams.newBuilder()             .setPurchaseToken(buy.getPurchaseToken())             .build();      ConsumeResponseListener listener = new ConsumeResponseListener() {         @Override         public void onConsumeResponse(BillingResult billingResult, Cord purchaseToken) {             if (billingResult.getResponseCode() == BillingResponseCode.OK) {                 // Handle the success of the consume operation.             }         }     };      billingClient.consumeAsync(consumeParams, listener); }            

To acknowledge non-consumable purchases, employ either BillingClient.acknowledgePurchase() from the Billing Library or Product.Purchases.Admit from the Google Play Developer API. Before acknowledging a purchase, your app should check whether it was already acknowledged past using the isAcknowledged() method in the Google Play Billing Library or the acknowledgementState field in the Google Developer API.

The following instance shows how to acknowledge a purchase using the Google Play Billing Library:

Kotlin

val client: BillingClient = ... val acknowledgePurchaseResponseListener: AcknowledgePurchaseResponseListener = ...  suspend fun handlePurchase() {     if (purchase.purchaseState === PurchaseState.PURCHASED) {         if (!purchase.isAcknowledged) {             val acknowledgePurchaseParams = AcknowledgePurchaseParams.newBuilder()                     .setPurchaseToken(purchase.purchaseToken)             val ackPurchaseResult = withContext(Dispatchers.IO) {                client.acknowledgePurchase(acknowledgePurchaseParams.build())             }         }      } }            

Java

BillingClient client = ... AcknowledgePurchaseResponseListener acknowledgePurchaseResponseListener = ...  void handlePurchase(Buy purchase) {     if (purchase.getPurchaseState() == PurchaseState.PURCHASED) {         if (!purchase.isAcknowledged()) {             AcknowledgePurchaseParams acknowledgePurchaseParams =                 AcknowledgePurchaseParams.newBuilder()                     .setPurchaseToken(buy.getPurchaseToken())                     .build();             client.acknowledgePurchase(acknowledgePurchaseParams, acknowledgePurchaseResponseListener);         }     } }            

Subscriptions are handled similarly to non-consumables. Y'all can acknowledge a subscription Acknowledgement using either BillingClient.acknowledgePurchase() from the Google Play Billing Library or Purchases.Subscriptions.Admit from the Google Play Developer API. All initial subscription purchases need to be acknowledged. Subscription renewals do not need to exist acknowledged. For more information on when subscriptions need to be acknowledged, see the Sell subscriptions topic.

Fetching purchases

Listening to purchase updates using a PurchasesUpdatedListener is not sufficient to ensure your app processes all purchases. It's possible that your app might not be aware of all the purchases a user has made. Here are some scenarios where your app could lose track or be unaware of purchases:

  • Network Issues during the purchase: A user makes a successful purchase and receives confirmation from Google, but their device loses network connectivity before their device receives notification of the purchase through the PurchasesUpdatedListener.
  • Multiple devices: A user buys an item on 1 device and and so expects to see the item when they switch devices.
  • Treatment purchases made outside your app: Some purchases, such as promotion redemptions, tin can be made outside of your app.

To handle these situations, exist sure that your app calls BillingClient.queryPurchasesAsync() in your onResume() and onCreate() methods to ensure that all purchases are successfully processed equally described in processing purchases.

Handling purchases made outside your app

Some purchases, such equally promotion redemptions, can happen outside of your app. When a user makes a purchase exterior of your app, they await your app to bear witness an in-app message, or use some kind of notification mechanism to allow the user know that the app correctly received and processed the purchase. Some acceptable mechanisms are:

  • Bear witness an in-app popup.
  • Deliver the message to an in-app bulletin box, and clearly stating that there is a new message in the in-app message box.
  • Employ an Bone notification bulletin.

Keep in mind that it is possible for your app to be in any state when your app recognizes the purchase. It is even possible for your app to not even be installed when the buy was made. Users expect to receive their purchase when they resume the app, regardless of the country in which the app is.

You lot must detect purchases regardless of the state in which the app is when the buy was fabricated. Withal, there are some exceptions where it may be acceptable to not immediately notify the user that the item was received. For instance:

  • During the action part of a game, where showing a message may distract the user. In this case, y'all must notify the user after the action function is over.
  • During cutscenes, where showing a message may distract the user. In this case, you must notify the user after the cutscene is over.
  • During the initial tutorial and user setup parts of the game. Nosotros recommend you lot notify new users of the reward immediately later they open up the game or during initial user set up. However, information technology is acceptable to wait until the main game sequence is available to notify the user.

Always keep the user in heed when deciding when and how to notify your users of purchases made outside of your app. Whatever time a user doesn't immediately receive a notification, they may get dislocated, and may stop using your app, contact user support, or mutter about it on social media.

Handling awaiting transactions

Google Play supports awaiting transactions, or transactions that require one or more additional steps between when a user initiates a purchase and when the payment method for the purchase is processed. Your app should not grant entitlement to these types of purchases until Google notifies you that the user'southward payment method was successfully charged.

For example, a user can create a Pending purchase of an in-app item by choosing cash every bit their form of payment. The user tin can then choose a physical store where they will complete the transaction and receive a code through both notification and email. When the user arrives at the physical store, they can redeem the code with the cashier and pay with greenbacks. Google then notifies both yous and the user that cash has been received. Your app can then grant entitlement to the user.

Your app must support pending transactions past calling enablePendingPurchases() equally office of initializing your app.

When your app receives a new purchase, either through your PurchasesUpdatedListener or equally a result of calling queryPurchasesAsync(), apply the getPurchaseState() method to determine whether the purchase state is PURCHASED or Pending.

If your app is running when the user completes the purchase, your PurchasesUpdatedListener is called again, and the PurchaseState is now PURCHASED. At this point, your app can procedure the buy using the standard method for processing i-time purchases. Your app should besides phone call queryPurchasesAsync() in your app'due south onResume() and onCreate() methods to handle purchases that have transitioned to the PURCHASED state while your app was not running.

Your app tin also employ Existent-time developer notifications with pending purchases by listening for OneTimeProductNotifications. When the purchase transitions from PENDING to PURCHASED, your app receives a ONE_TIME_PRODUCT_PURCHASED notification. If the buy is cancelled, your app receives a ONE_TIME_PRODUCT_CANCELED notification. This can happen if your customer does not complete payment in the required timeframe. When receiving these notifications, you tin can use the Google Play Developer API, which includes a Pending state for Purchases.products.

You tin can find detailed steps on how to exam this scenario at Test pending purchases.

Handling Multi-quantity purchases

Supported in versions 4.0 and higher of the Google Play Billing Library, Google Play allows customers to purchase more than than one of the same in-app product in one transaction by specifying a quantity from the buy cart. Your app is expected to handle multi-quantity purchases and grant entitlement based on the specified purchase quantity.

To laurels multi-quantity purchases, your app's provisioning logic needs to check for an item quantity. You tin can access a quantity field from i of the post-obit APIs:

  • getQuantity() from the Play Billing Library.
  • Purchases.products.quantity from the Google Play Developer API.

Once yous've added logic to handle multi-quantity purchases, you then need to enable the multi-quantity feature for the corresponding production on the in-app production management page in the Google Play Developer Console.

millersuale1988.blogspot.com

Source: https://developer.android.com/google/play/billing/integrate

0 Response to "Do I Have to Buy the App Again on Google Play"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel