javaandroidin-app-billingplay-billing-library

How to pass a user ID with the Google Play Billing Library?


The documentation reads:

Starting on August 2, 2021, all new apps must use Billing Library version 3 or newer. By November 1, 2021, all updates to existing apps must use Billing Library version 3 or newer.

Which would be this dependency:

implementation "com.android.billingclient:billing:3.0.2"

How to pass something alike a user ID with the billing client?


Solution

  • One can pass along an accountId and profileId with the BillingFlowParams:

    String accountId = "";
    String profileId = "";
    
    BillingFlowParams.Builder builder = BillingFlowParams.newBuilder().setSkuDetails(skuDetail);
    if (this.accountId != null) {builder.setObfuscatedAccountId(accountId);}
    if (this.profileId != null) {builder.setObfuscatedProfileId(profileId);}
    BillingFlowParams billingFlowParams = builder.build();
    

    Then on onPurchasesUpdated() one can be retrieve AccountIdentifiers from a Purchase:

    @Override
    public void onPurchasesUpdated(@NonNull BillingResult billingResult, @Nullable List<Purchase> items) {
        if (items != null) {
            for (Purchase item : items) {
                if (item.getPurchaseState() == Purchase.PurchaseState.PURCHASED) {
                    ...
                    AccountIdentifiers identifiers = item.getAccountIdentifiers();
                    if (identifiers != null) {
                        String accountId = identifiers.getObfuscatedAccountId();
                        String profileId = identifiers.getObfuscatedProfileId();
                        ...
                    }
                }
            }
        }
    }