Search code examples
androidin-app-purchaseandroid-inapp-purchase

Google Play Billing Library 3.0+ - Restore purchase


With Google Play Billing Library v3.0+ we have a new purchase flow and everything is perfectly explained here: Google Play Billing

On older versions of the library we would restore something like this:

bp = new BillingProcessor(this, MERCHANT_ID, new BillingProcessor.IBillingHandler() {
        @Override
        public void onProductPurchased(@NonNull String productId, @Nullable TransactionDetails details) {
            String orderId = details.purchaseInfo.purchaseData.productId;
  // we then compare the orderID with the SKU and see if the user purchased the item,
  // however in the new version of the library there is nothing about restore

However, there is nothing in the documentation about restoring purchases ?

Eg, we have a use case you have a valid subscription and one IAP product that you purchased. You delete the app and reinstall it. How do you restore the subscription and that IAP product ?


Solution

  • Basically queryPurchaseHistoryAsync does the job, just be careful to pass the SKU TYPE (inapp or subs).

    My implementation:

    fun restorePurchaseInApp() {
        bp.queryPurchaseHistoryAsync("inapp", this)
    }
    
    fun restorePurchaseInSubs() {
        bp.queryPurchaseHistoryAsync("subs", this)
    }
    
    // bp is BillingClient
    // the class should implement PurchaseHistoryResponseListener
    
    override fun onPurchaseHistoryResponse(
        p0: BillingResult,
        p1: MutableList<PurchaseHistoryRecord>?
    ) {
        if (p1 != null) {
            Log.d("TMS", "onPurchaseHistoryResponse: " + p1.size)
        }
    
        if (p1 != null) {
            for (item in p1) {
                Log.d("TMS", "onPurchaseHistoryResponse sku: " + item.sku)
                Log.d("TMS", "onPurchaseHistoryResponse signature: " + item.signature)
                Log.d("TMS", "onPurchaseHistoryResponse purchaseToken: " + item.purchaseToken)
                Log.d("TMS", "onPurchaseHistoryResponse purchaseTime: " + item.purchaseTime)
            }
        }
    }
    

    There you get the items that are purchased and that`s it :). I hope this will help because I lost a lot of time figuring out something so simple and the docs implementation have no mention about this.