How can I show the products that the user has purchased in the billingclient library in Android?

699 Views Asked by At

I am using the com.android.billingclient:billing:3.0.1 library. How can I check if the user has purchased any product when the app is opened. So I want to check before the payment page opens.

The following method returns null:

mBillingClient = BillingClient.newBuilder(getApplicationContext()).enablePendingPurchases().setListener(this).build();

mBillingClient.queryPurchaseHistoryAsync(BillingClient.SkuType.INAPP, new PurchaseHistoryResponseListener() {
    @Override
    public void onPurchaseHistoryResponse(@NonNull BillingResult billingResult, @Nullable List<PurchaseHistoryRecord> list) {
        list.size();
    }
});
1

There are 1 best solutions below

0
On

You can use GetPurchasesHistory method to get purchased items. This is working for me perfectly. So you can use that :)

public void GetPurchasesHistory(String skuType){
      Purchase.PurchasesResult purchasesResult = billingClient.queryPurchases(skuType);
      List<Purchase> purchases = purchasesResult.getPurchasesList();
      List<String> listOfJsons = new ArrayList<>();
      List<String> listOfSkus = new ArrayList<>();
      List<String> orderIds = new ArrayList<>();
      if(purchasesResult.getBillingResult().getResponseCode() == BillingClient.BillingResponseCode.OK){
          if(purchases != null){
              for(Purchase purchase : purchases){
                  listOfJsons.add(purchase.getOriginalJson());
                  listOfSkus.add(purchase.getSkus().get(0));
                  orderIds.add(purchase.getOrderId());
              }
              // You got purchases history, Do what you wanted

          }else{
            // Failed as purchase is null
          }
      }else{
        // FailedToGetPurchasesHistory("Failed, ResponseCode = " + purchasesResult.getBillingResult().getResponseCode());
      }
  }