Wednesday 7 July 2021

In App Purchase Failing with Error Something went wrong on our end. Please try again

My users are unable to make in-app purchase from my lite app.This code was working up until April. In May I followed an API update which resulted in minor code changes in other methods which are working fine, but below method did not change at all.

Am able to load the price of the single in-app item after a successful query. Then when the user clicks on the button, it should show Google Play purchase screen, but instead it shows "Error. Something went wrong on our end. Please try again. Got it". When I press on "Got it" button.

The immediate log shows response code = 0 but when I press on "got it" button it goes to the listener and says response code = 5

I do not see what wrong am doing. Can someone please help?

public void onInAppPurchaseButtonClicked(View mView) {
                    try{
                        JSONObject jsonSkuDetails = new JSONObject();
                        jsonSkuDetails.put("productId", ApplicationDetails.getInAppPurchaseProductID());
                        jsonSkuDetails.put("type", BillingClient.SkuType.INAPP);
                        SkuDetails skuDetails=  new SkuDetails(jsonSkuDetails.toString());
                        BillingFlowParams billingFlowParams=BillingFlowParams.newBuilder().setSkuDetails(skuDetails)
                                .build();

                        Log.i(TAG, "Launching Billing Flow with skuDetails = "+skuDetails);
                        BillingResult billingResult = mBillingClient.launchBillingFlow(this,billingFlowParams);//will call onPurchasesUpdated
                        Log.i(TAG, "Launching Billing Flow responseCode = "+billingResult.getResponseCode());

                    } catch (JSONException e) {
                        Log.i(TAG, "JSONException Launching Billing Flow = "+e.getMessage());
                    }
                }

Manifest does have

<uses-permission android:name="com.android.vending.BILLING" />

Full class code


import android.os.Bundle;
import androidx.annotation.Nullable;
import android.util.Log;
import android.view.View;

import com.android.billingclient.api.AcknowledgePurchaseParams;
import com.android.billingclient.api.AcknowledgePurchaseResponseListener;
import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.BillingClientStateListener;
import com.android.billingclient.api.BillingFlowParams;
import com.android.billingclient.api.BillingResult;
import com.android.billingclient.api.Purchase;
import com.android.billingclient.api.PurchasesUpdatedListener;
import com.android.billingclient.api.SkuDetails;
import com.android.billingclient.api.SkuDetailsParams;
import com.android.billingclient.api.SkuDetailsResponseListener;
import com.webrich.base.R;
import com.webrich.base.layout.BaseInAppPurchaseLayout;
import com.webrich.base.util.Constants;
import com.webrich.base.util.UIUtils;
import com.webrich.base.util.Utils;
import com.webrich.base.vo.ApplicationDetails;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;



public class GoogleInAppPurchaseActivity extends BaseInAppPurchaseActivity implements Constants {
    private String TAG ;
    private boolean mIsServiceConnected;
    public static final int BILLING_MANAGER_NOT_INITIALIZED  = -1;
    private int mBillingClientResponseCode = BILLING_MANAGER_NOT_INITIALIZED;
    private BillingClient mBillingClient;
    private int mNumberofConnectionRetries=3;

    @Override
    protected void onCreation(Bundle savedInstanceState) {
        super.onCreation(savedInstanceState);
        TAG=this.getClass().getName();

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

        mBillingClient.startConnection(mBillingClientStateListener);

        setLayout(new BaseInAppPurchaseLayout());

    }

    private BillingClientStateListener mBillingClientStateListener=new BillingClientStateListener() {
        @Override
        public void onBillingSetupFinished(BillingResult billingResult) {
            Log.d(TAG, "Setup finished. BillingResult: " + billingResult.getResponseCode());

            if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK)
            {
                mIsServiceConnected = true;
                queryPurchases();//checks if already purchased, if so displays relevant screen
                if(!alreadyPurchased)
                {
                    queryInventory();//check the price and display it
                }

            }
            mBillingClientResponseCode = billingResult.getResponseCode();
        }

        @Override
        public void onBillingServiceDisconnected() {
            mIsServiceConnected=false;
        }



    };




    private void queryInventory() {
        Runnable queryToExecute = new Runnable() {
            @Override
            public void run() {
                List<String> skuList = new ArrayList<>();
                skuList.add(ApplicationDetails.getInAppPurchaseProductID());
                SkuDetailsParams.Builder params = SkuDetailsParams.newBuilder();
                params.setSkusList(skuList).setType(BillingClient.SkuType.INAPP);
                mBillingClient.querySkuDetailsAsync(params.build(), mSkuDetailsResponseListener);
                Log.i(TAG, "Query Sku ="+ApplicationDetails.getInAppPurchaseProductID());

            }
        };
        executeServiceRequest(queryToExecute);

    }
    private SkuDetailsResponseListener mSkuDetailsResponseListener = new SkuDetailsResponseListener() {
        @Override
        public void onSkuDetailsResponse(BillingResult billingResult, List<SkuDetails> skuDetailsList) {
            if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK
                    && skuDetailsList != null && skuDetailsList.size()>0) {
                String sku = skuDetailsList.get(0).getSku();
                String price = skuDetailsList.get(0).getPrice();
                Log.i(TAG, "Query Sku Details  was successful. Price="+price);
                updateButtonWithPrice(price);
            }
            else {
                complain("Unable to get price, response code = "+billingResult.getResponseCode());
            }
        }
    };


    private void executeServiceRequest(Runnable runnable) {
        if (mIsServiceConnected) {
            Log.i(TAG, "Service Connected, executing purchase request");
            runnable.run();
        } else {
            do {
                complain("Error connecting to billing service, Trying again ");
                mBillingClient.startConnection(mBillingClientStateListener);
            } while(mNumberofConnectionRetries-->0);
        }
    }






    /**
     * Query purchases across various use cases and deliver the result in a formalized way through
     * a listener
     */
    public void queryPurchases() {
        Runnable queryToExecute = new Runnable() {
            @Override
            public void run() {
                Purchase.PurchasesResult purchasesResult = mBillingClient.queryPurchases(BillingClient.SkuType.INAPP);
                if (purchasesResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
                    Log.i(TAG, "Querying Purchases was successful. Updating screen now");
                    if (purchasesResult.getPurchasesList()!=null && purchasesResult.getPurchasesList().size()>0 && purchasesResult.getPurchasesList().get(0).getSku().equals(ApplicationDetails.getInAppPurchaseProductID())) {
                        // you had bought the inapp already in the past!
                        String message = getResources().getString(R.string.already_purchased);
                        alreadyPurchased = true;
                        updateUi(alreadyPurchased);
                        Utils.fullVersionPurchaseSuccess(GoogleInAppPurchaseActivity.this);
                        successAlert(message);
                    }
                } else {
                    complain("Problem querying purchases made in the past if any" + purchasesResult.getResponseCode());

                }
            }
        };

        executeServiceRequest(queryToExecute);
    }


    public void complain(String message) {
        alert("Error: " + message);
    }




    //restore previous purchase
    public void onAlreadyPurchasedButtonClicked(View mView) {
        try {

            if (alreadyPurchased) {
                String message = getResources().getString(R.string.app_restore_successful_msg);
                Utils.fullVersionPurchaseSuccess(GoogleInAppPurchaseActivity.this);
                successAlert(message);
            } else {
                String message = getResources().getString(R.string.application_is_not_purchased);
                UIUtils.toast(this, message);
            }
        } catch (Exception e) {
            UIUtils.toast(this, e.getMessage());
        }

    }

    // User clicked the in app purchase button
    public void onInAppPurchaseButtonClicked(View mView) {
                    try{
                        JSONObject jsonSkuDetails = new JSONObject();
                        jsonSkuDetails.put("productId", ApplicationDetails.getInAppPurchaseProductID());
                        jsonSkuDetails.put("type", BillingClient.SkuType.INAPP);
                        SkuDetails skuDetails=  new SkuDetails(jsonSkuDetails.toString());
                        BillingFlowParams billingFlowParams=BillingFlowParams.newBuilder().setSkuDetails(skuDetails)
                                .build();

                        Log.i(TAG, "Launching Billing Flow with skuDetails = "+skuDetails);
                        BillingResult billingResult = mBillingClient.launchBillingFlow(this,billingFlowParams);//will call onPurchasesUpdated
                        Log.i(TAG, "Launching Billing Flow responseCode = "+billingResult.getResponseCode());

                    } catch (JSONException e) {
                        Log.i(TAG, "JSONException Launching Billing Flow = "+e.getMessage());
                    }
                }

    AcknowledgePurchaseResponseListener acknowledgePurchaseResponseListener = new AcknowledgePurchaseResponseListener() {
        @Override
        public void onAcknowledgePurchaseResponse(BillingResult billingResult) {
            // bought the premium upgrade!
            Log.d(TAG, "onAcknowledgePurchaseResponse: " + billingResult.getResponseCode() );
            String message = getResources().getString(R.string.app_purchase_successful_msg);
            alreadyPurchased = true;
            updateUi(alreadyPurchased);
            Utils.fullVersionPurchaseSuccess(GoogleInAppPurchaseActivity.this);
            successAlert(message);
        }

    };

    //called when user buys the inapp
    private PurchasesUpdatedListener mPurchaseUpdatedListener = new PurchasesUpdatedListener() {
        @Override
        public void onPurchasesUpdated(BillingResult billingResult, @Nullable List<Purchase> purchases) {
            {
                if (billingResult.getResponseCode() != BillingClient.BillingResponseCode.OK && billingResult.getResponseCode()!=BillingClient.BillingResponseCode.USER_CANCELED) {
                    complain("Encountered an error while making the purchase. BillingResponseCode = "+billingResult.getResponseCode() +
                            ", Purchases = "+ purchases);
                }

                if (purchases!=null && purchases.size()>0) {
                    Purchase purchase = purchases.get(0);
                    Log.d(TAG, "Purchase finished: " + billingResult.getResponseCode() + ", purchase order ID: " + purchases.get(0).getOrderId());
                    if (purchase.getSku().equals(ApplicationDetails.getInAppPurchaseProductID())) {

                        AcknowledgePurchaseParams acknowledgePurchaseParams =
                                AcknowledgePurchaseParams.newBuilder()
                                        .setPurchaseToken(purchase.getPurchaseToken())
                                        .build();
                        mBillingClient.acknowledgePurchase(acknowledgePurchaseParams, acknowledgePurchaseResponseListener);
                    }
                }
            }
        }
    };


    @Override
    public void onDestroy()
    {
        super.onDestroy();
        mBillingClient.endConnection();
    }
}



from In App Purchase Failing with Error Something went wrong on our end. Please try again

No comments:

Post a Comment