com.android.billingclient.api.BillingClient.BillingResponseCode Java Examples

The following examples show how to use com.android.billingclient.api.BillingClient.BillingResponseCode. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PreferencesBillingHelper.java    From CommonUtils with Apache License 2.0 6 votes vote down vote up
public void onStart(@NonNull Activity activity) {
    billingClient = BillingClient.newBuilder(activity).enablePendingPurchases().setListener(new InternalListener()).build();
    billingClient.startConnection(new BillingClientStateListener() {
        private boolean retried = false;

        @Override
        public void onBillingSetupFinished(@NonNull BillingResult billingResult) {
            if (billingResult.getResponseCode() == BillingResponseCode.OK) {
                synchronized (billingReady) {
                    billingReady.notifyAll();
                }
            } else {
                handleBillingErrors(billingResult.getResponseCode());
            }
        }

        @Override
        public void onBillingServiceDisconnected() {
            if (!retried) {
                retried = true;
                billingClient.startConnection(this);
            } else {
                listener.showToast(Toaster.build().message(R.string.failedBillingConnection));
            }
        }
    });
}
 
Example #2
Source File: PreferencesBillingHelper.java    From CommonUtils with Apache License 2.0 6 votes vote down vote up
private void handleBillingErrors(@BillingResponseCode int code) {
    switch (code) {
        case BillingResponseCode.BILLING_UNAVAILABLE:
        case BillingResponseCode.SERVICE_UNAVAILABLE:
        case BillingResponseCode.SERVICE_DISCONNECTED:
        case BillingResponseCode.SERVICE_TIMEOUT:
            listener.showToast(Toaster.build().message(R.string.failedBillingConnection));
            break;
        case BillingResponseCode.USER_CANCELED:
            listener.showToast(Toaster.build().message(R.string.userCancelled));
            break;
        case BillingResponseCode.DEVELOPER_ERROR:
        case BillingResponseCode.ITEM_UNAVAILABLE:
        case BillingResponseCode.FEATURE_NOT_SUPPORTED:
        case BillingResponseCode.ITEM_ALREADY_OWNED:
        case BillingResponseCode.ITEM_NOT_OWNED:
        case BillingResponseCode.ERROR:
            listener.showToast(Toaster.build().message(R.string.failedBuying));
            break;
        case BillingResponseCode.OK:
            break;
    }
}
 
Example #3
Source File: PreferencesBillingHelper.java    From CommonUtils with Apache License 2.0 6 votes vote down vote up
@Override
public void onPurchasesUpdated(BillingResult br, @Nullable List<Purchase> purchases) {
    if (br.getResponseCode() == BillingResponseCode.OK) {
        listener.showToast(Toaster.build().message(R.string.thankYou).extra(purchases == null ? null : purchases.toString()));
        if (purchases == null || purchases.isEmpty()) return;

        for (Purchase p : purchases) {
            if (p.isAcknowledged()) continue;

            AcknowledgePurchaseParams params = AcknowledgePurchaseParams.newBuilder()
                    .setPurchaseToken(p.getPurchaseToken())
                    .build();
            billingClient.acknowledgePurchase(params, br1 -> {
                if (br1.getResponseCode() != BillingResponseCode.OK)
                    handleBillingErrors(br1.getResponseCode());
            });
        }
    } else {
        handleBillingErrors(br.getResponseCode());
    }
}
 
Example #4
Source File: PreferencesBillingHelper.java    From CommonUtils with Apache License 2.0 5 votes vote down vote up
private void buyProduct(@NonNull Activity activity, @NonNull SkuDetails product) {
    BillingFlowParams flowParams = BillingFlowParams.newBuilder()
            .setSkuDetails(product)
            .build();

    BillingResult result = billingClient.launchBillingFlow(activity, flowParams);
    if (result.getResponseCode() != BillingResponseCode.OK)
        handleBillingErrors(result.getResponseCode());
}
 
Example #5
Source File: PreferencesBillingHelper.java    From CommonUtils with Apache License 2.0 5 votes vote down vote up
public void donate(@NonNull Activity activity, boolean wasWaiting) {
    if (!wasWaiting)
        listener.showDialog(DialogUtils.progressDialog(activity, R.string.connectingBillingService));

    if (billingClient != null && billingClient.isReady()) {
        SkuDetailsParams.Builder params = SkuDetailsParams.newBuilder();
        params.setSkusList(products).setType(BillingClient.SkuType.INAPP);
        billingClient.querySkuDetailsAsync(params.build(), (billingResult, skuDetailsList) -> {
            listener.dismissDialog();

            if (billingResult.getResponseCode() == BillingResponseCode.OK)
                showDonateDialog(activity, skuDetailsList);
            else
                handleBillingErrors(billingResult.getResponseCode());
        });
    } else {
        new Thread() {
            @Override
            public void run() {
                synchronized (billingReady) {
                    try {
                        billingReady.wait();
                        donate(activity, true);
                    } catch (InterruptedException ex) {
                        Log.w(TAG, ex);
                    }
                }
            }
        }.start();
    }
}
 
Example #6
Source File: MainActivity.java    From PixelWatchFace with GNU General Public License v3.0 5 votes vote down vote up
private void checkPurchases() {
  PurchasesResult purchasesResult = billingClient.queryPurchases(SkuType.INAPP);
  if (purchasesResult.getBillingResult().getResponseCode() == BillingResponseCode.OK) {
    boolean advancedPurchasePresent = false;
    for (Purchase purchase : purchasesResult.getPurchasesList()) {
      handlePurchase(purchase);
      if (purchase.getSku().equals("unlock_weather")){
        advancedPurchasePresent = true;
      }
    }
    if (!advancedPurchasePresent && advanced){
      revokeAdvancedPurchase();
    }
  }
}
 
Example #7
Source File: MainActivity.java    From PixelWatchFace with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onPurchasesUpdated(BillingResult billingResult, List<Purchase> purchases) {
  if (billingResult.getResponseCode() == BillingResponseCode.OK
      && purchases != null) {
    for (Purchase purchase : purchases) {
      handlePurchase(purchase);
    }
  } else if (billingResult.getResponseCode() == BillingResponseCode.USER_CANCELED) {
    Snackbar.make(findViewById(android.R.id.content), "Purchase cancelled", Snackbar.LENGTH_SHORT)
        .show();
  } else {
    // Handle any other error codes.
  }
}
 
Example #8
Source File: GoogleBillingHelper.java    From Augendiagnose with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Query SKU details. If no connection available, establish connection.
 *
 * @param listener The listener called when the query is finished.
 */
public void querySkuDetails(final OnInventoryFinishedListener listener) {
	if (mIsConnected) {
		doQuerySkuDetails(listener);
	}
	else {
		mBillingClient.startConnection(new BillingClientStateListener() {
			@Override
			public void onBillingSetupFinished(final BillingResult billingResult) {
				if (billingResult.getResponseCode() == BillingResponseCode.OK) {
					Log.d(TAG, "Google Billing Connection established.");
					mIsConnected = true;
					doQuerySkuDetails(listener);
				}
				else {
					Log.i(TAG, "Google Billing Connection failed - " + billingResult.getDebugMessage());
					mIsConnected = false;
				}
			}

			@Override
			public void onBillingServiceDisconnected() {
				Log.d(TAG, "Google Billing Connection lost.");
				mIsConnected = false;
			}
		});
	}
}
 
Example #9
Source File: GoogleBillingHelper.java    From Augendiagnose with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Launch the purchase flow for a product. If there is no connection, then establish connection before.
 *
 * @param activity   The triggering activity.
 * @param skuDetails The details of the product to be purchased.
 * @param listener   a listener called after the purchase has been completed.
 */
public void launchPurchaseFlow(final Activity activity, final SkuDetails skuDetails, final OnPurchaseSuccessListener listener) {
	if (mIsConnected) {
		doLaunchPurchaseFlow(activity, skuDetails, listener);
	}
	else {
		mBillingClient.startConnection(new BillingClientStateListener() {
			@Override
			public void onBillingSetupFinished(final BillingResult billingResult) {
				if (billingResult.getResponseCode() == BillingResponseCode.OK) {
					Log.d(TAG, "Google Billing Connection established.");
					mIsConnected = true;
					doLaunchPurchaseFlow(activity, skuDetails, listener);
				}
				else {
					Log.i(TAG, "Google Billing Connection failed - " + billingResult.getDebugMessage());
					mIsConnected = false;
				}
			}

			@Override
			public void onBillingServiceDisconnected() {
				Log.d(TAG, "Google Billing Connection lost.");
				mIsConnected = false;
			}
		});
	}
}
 
Example #10
Source File: GoogleBillingHelper.java    From Augendiagnose with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void onPurchasesUpdated(final BillingResult billingResult, final @Nullable List<Purchase> purchaseList) {
	Log.i(TAG, "Purchase finished: " + billingResult.getResponseCode());

	if (billingResult.getResponseCode() != BillingResponseCode.OK) {
		Log.e(TAG, "Error purchasing: " + billingResult.getDebugMessage());
		if (mOnPurchaseSuccessListener != null) {
			mOnPurchaseSuccessListener.handleFailure();
		}
		return;
	}

	Log.i(TAG, "Purchase successful.");

	if (mOnPurchaseSuccessListener != null && purchaseList != null) {
		boolean hasPurchase = false;
		boolean isPurchased = false;
		for (Purchase purchase : purchaseList) {
			hasPurchase = true;
			if (purchase.getPurchaseState() == PurchaseState.PURCHASED) {
				Log.i(TAG, "Purchase " + purchase.getSku() + " finished");
				isPurchased = true;
				doAcknowledgePurchaseIfRequired(purchase);
			}
		}
		if (hasPurchase) {
			mOnPurchaseSuccessListener.handlePurchase(!mIsPremium, !isPurchased);
			if (isPurchased) {
				mIsPremium = true;
			}
		}
	}
}
 
Example #11
Source File: MainActivity.java    From PixelWatchFace with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void onAcknowledgePurchaseResponse(BillingResult billingResult) {
  if (billingResult.getResponseCode() != BillingResponseCode.OK) {
    Log.e("acknowledgePurchase", "Error acknowledging purchase, this shouldn't happen");
  }
}
 
Example #12
Source File: GoogleBillingHelper.java    From Augendiagnose with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Handle result of inventory query.
 *
 * @param billingResult  The result flag.
 * @param skuDetailsList The retrieved SKU details.
 * @param isSubscription Flag indicating if this was subscription query.
 * @param listener       The listener called when inventory calls are finished.
 */
private void onSkuDetailsResponse(final BillingResult billingResult, final List<SkuDetails> skuDetailsList, final boolean isSubscription,
								  final OnInventoryFinishedListener listener) {
	Log.d(TAG, "Query inventory finished - " + billingResult.getResponseCode() + " - " + isSubscription);

	if (billingResult.getResponseCode() != BillingResponseCode.OK) {
		Log.e(TAG, "Failed to query inventory: " + billingResult.getDebugMessage());
		return;
	}

	Log.d(TAG, "Query inventory was successful.");

	Map<String, Purchase> purchaseMap = new HashMap<>();
	List<SkuPurchase> skuPurchases = new ArrayList<>();

	PurchasesResult purchasesResult = mBillingClient.queryPurchases(isSubscription ? SkuType.SUBS : SkuType.INAPP);
	if (purchasesResult.getResponseCode() != BillingResponseCode.OK) {
		Log.e(TAG, "Failed to query purchases: " + purchasesResult.getBillingResult().getDebugMessage());
		return;
	}
	for (Purchase purchase : purchasesResult.getPurchasesList()) {
		if (purchase.getPackageName().equals(mContext.getPackageName())) {
			purchaseMap.put(purchase.getSku(), purchase);
			if (purchase.getPurchaseState() == PurchaseState.PURCHASED) {
				doAcknowledgePurchaseIfRequired(purchase);
				mIsPremium = true;
			}
		}
	}

	for (SkuDetails skuDetails : skuDetailsList) {
		if (purchaseMap.containsKey(skuDetails.getSku())) {
			skuPurchases.add(new SkuPurchase(skuDetails, purchaseMap.get(skuDetails.getSku())));
		}
		else {
			skuPurchases.add(new SkuPurchase(skuDetails));
		}
	}

	synchronized (this) {
		if (isSubscription) {
			mSubscriptionSkus = skuPurchases;
		}
		else {
			mInAppSkus = skuPurchases;
		}

		if (listener != null && mSubscriptionSkus != null && mInAppSkus != null) {
			listener.handleProducts(mInAppSkus, mSubscriptionSkus);
		}
	}
}