Monday, December 23, 2013

Code to Set Up Billing and Query Inventory

When enabling in-app purchases,the first step is to set up in app billing, the second should be to check to see what upgrades the user has purchased in the past. Here's code from my own app, which was adapted from the Android TrivialDrive sample code:

Initial set-up, (In on create):

        Log.d(TAG, "Starting setup."); //Log that we will start setting up In App Billing (IAB)
        mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() { //Start setup. This is asynchronous and the specified listener will be called once setup completes.
            public void onIabSetupFinished(IabResult result) {
                Log.d(TAG, "Setup finished.");   
                if (!result.isSuccess()) { //If billing setup not a success
                    Log.d(TAG, "Problem setting up in-app billing: " + result);
                    return;
                }
                if (mHelper == null) return;  // Have we been disposed of in the meantime? If so, quit.
                // if successfullly set up then do this:
                Log.d(TAG, "Setup successful. Querying inventory."); //Log that our setup was successful
                mHelper.queryInventoryAsync(mGotInventoryListener); // Call inventory method of stuff we own
            }
        });



Method for inventory check

    IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
        public void onQueryInventoryFinished(IabResult result, Inventory inventory) {
            Log.d(TAG, "Query inventory started"); //Log that were checking inventory 
            if (mHelper == null) return; // Have we been disposed of in the meantime? If so, quit
            if (result.isFailure()) { // Is inventory query a failure?
                Log.d(TAG, "Failed to query inventory: " + result);           
                Toast query = Toast.makeText(Shoulders.this, "Failed to query inventory: " + result, Toast.LENGTH_LONG);
                query.show();
                return;
            }
            Log.d(TAG, "Query inventory was successful."); //if query not a failure then log success          
            Purchase premiumPurchase = inventory.getPurchase(SKU_SHOULDERS); // Do we already have the premium upgrade?
            mIsPremium = (premiumPurchase != null);//) && verifyDeveloperPayload(premiumPurchase));
            Log.d(TAG, "User is " + (mIsPremium ? "PREMIUM" : "NOT PREMIUM")); //log if premium or not
            if (mIsPremium) updateUi(); //if we are  premium, show premium upgrade
            Log.d(TAG, "Initial inventory query finished; enabling main UI.");
        }
    };

No comments:

Post a Comment