Android check if in app purchase was bought before

2019-02-15 10:02发布

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?

1条回答
迷人小祖宗
2楼-- · 2019-02-15 10:23
 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
                    }                    
            }
查看更多
登录 后发表回答