Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android check if in app purchase was bought before

I would like to make an in app purchase in my android app. I use for this the google sample: http://developer.android.com/training/in-app-billing/preparing-iab-app.html#GetSample

I implemented this in my android studio project. In the developer console I set the in app purchase and a gmail address as test account.

on my device (not emulator), I logged in with this test account. I start my app and klick on "Buy Premium" and can finish this process.

now I would like to show a Button (Text "Restore) where the user can restore his in app purchase, IF he / she bought the premium function before.

I have this code:

IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
        public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
            Log.e("-->", "Purchase finished: " + result);



            if (mHelper == null) return;

            if (result.isFailure()) {
                Log.e("-->","Error purchasing: " + result);
                return;
            }
            if (!verifyDeveloperPayload(purchase)) {
                Log.e("-->","Error purchasing. Authenticity verification failed.");
                return;
            }



            SharedPreferences prefs = this.getSharedPreferences("xxx", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = prefs.edit();
            editor.putBoolean("Premium", true);
            editor.commit();
            Log.e("-->", "Premium: " + prefs.getBoolean("Premium", false));


}
};

If I press on the "buy" button again and I had bought this before, I get this message in log cat:

-->: Purchase finished: IabResult: Unable to buy item (response: 7:Item Already Owned), purchase: null -->: Error purchasing: IabResult: Unable to buy item (response: 7:Item Already Owned)

My Question is, how can I check if the in app purchase was bought before or not?

like image 1000
SpecialFighter Avatar asked Dec 22 '15 13:12

SpecialFighter


1 Answers

 mIabHelper.queryInventoryAsync(true, "your_sku", mGotInventoryListener);

// Listener that's called when we finish querying the items and subscriptions we own
    IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
        public void onQueryInventoryFinished(IabResult result, Inventory inventory) {
            Log.d("PAY", "Query inventory finished.");

            // Have we been disposed of in the meantime? If so, quit.
            if (mIabHelper == null) return;
                    Purchase purchase = inventory.getPurchase("your_sku");
                    if (purchase != null) {
                        //purchased
                    }                    
            }
like image 158
Denys Vasylenko Avatar answered Nov 22 '22 12:11

Denys Vasylenko