130

I am currently testing In-App Billing for a future app, and after I successfully "bought" the test item "android.test.purchased" the first time, I now receive the response code 7 every time I try to buy it again, which means that I already own this item.

12-15 23:02:14.149: E/IabHelper(19829): In-app billing error: Unable to buy item, Error response: 7:Item Already Owned

From what I understand, this purchase is supposed to always be possible, right? So that the developer can test his/her app?

If not, how can I "reset" its state to not owned? I am using the util package from the Google In-App Billing Sample.

Pang
  • 9,564
  • 146
  • 81
  • 122
psykhi
  • 2,981
  • 2
  • 16
  • 22

15 Answers15

110

Add this code to a thread to initiate consume request.

int response = mService.consumePurchase(3, getPackageName(), purchaseToken);

Here for the purchase test, purchaseToken is

purchaseToken = "inapp:" + getPackageName() + ":android.test.purchased";

And

if (response == 0)

then the consumption is successful.

also don't forget to make mService public in

IabHelper.Java

then it would be possible to access like this:

int response = mHelper.mService.consumePurchase(3, getPackageName(), purchaseToken);
Hussnain Hashmi
  • 203
  • 2
  • 9
Aashutosh Sharma
  • 1,483
  • 2
  • 17
  • 29
  • 2
    Legend this works, @psykhi should really have given you the points. I was trying to consume it but couldn't work out the purchase token. Thanks – Blundell Dec 30 '12 at 16:07
  • @pks: you can place this code wherever you need to consume your purchase. On any click action or immediate after purchase, any where as your app needs – Aashutosh Sharma Aug 12 '14 at 17:13
  • 13
    What is mService? mHelper? But I can't find the consumePurchase() – Bagusflyer Aug 18 '14 at 14:45
  • 1
    mService is object of IInAppBillingService.aidl interface which is binded with purchase service initiated for inapp purchase. – Aashutosh Sharma Jan 09 '15 at 18:16
  • 1
    I would also like to point out if your using the IABHelper with the security as well, you may need to update verifyPurchase to return true. In my case, it was failing and just had to return true by default. – Kalel Wade Feb 26 '15 at 17:39
  • @Bhavesh: the purchase token mentioned here is of test purchases make sure you are not using these with real purchases. If you are having trouble with test purchase please explain what exactly the problem you are facing and what response you are getting from google at the time of consumption. Post your JSON response here. – Aashutosh Sharma Apr 11 '16 at 13:30
  • 1
    @ZhouHao mService is the `BillingClient`, and the method is now called `consumeAsync` – Francisco Durdin Garcia Mar 08 '18 at 16:10
101

No need to write any special consumption code. Just use the adb command for clearing the Google Play Store data:

adb shell pm clear com.android.vending
mttmllns
  • 1,740
  • 1
  • 15
  • 13
  • 1
    thanks it did the trick i just had to clear the app also so I made a full answer available. This is the right approach for me. – sivi Jul 01 '15 at 12:04
  • This is the right approach for a lot of people. Adding code to your app and redeploying is more time consuming (pun intended). – Michael Labbé Oct 02 '15 at 23:38
  • I confirm this is the best and easiest way to reset your test purchase ! thanks so much. – satyres Oct 12 '15 at 21:30
  • For me - I ran this command, then cleared the my app's cache (also cleared cache for Google Play Store, *tho not sure if that made a difference*), and then redeployed from Eclipse .. and the payment prompt appeared again. Thanks! – Gene Bo Jan 22 '16 at 21:20
  • 9
    This is a good solution for a test device, but be careful: it will reset all your settings in Google Play Store app. So, I would rather not doing it on my personal device. – racs Jan 26 '16 at 22:21
  • 7
    No! this is bad idea, you lost in-app purchase of your other product and other apps, good one is you have to consume product if you want test your in app purchase, scenario is just create two things one for purchase and another for consume purchased item. – Rahul Mandaliya Feb 18 '16 at 07:55
  • 2
    @RahulMandaliya your app should be resilient against cache clears by using the getPurchases() API to know what has already been purchased. – mttmllns Mar 29 '16 at 17:59
  • Not working for me. I think the purchase information should be managed by Google. – Deqing May 10 '16 at 12:06
69

It turns out that the android.test.purchased item behaves like a regular ID. It means that if you want be able to buy it again, you have to consume it somewhere in your code. I think that the Google documentation is misleading on this matter, and that they should add another static ID that you can buy endlessly for test purposes.

psykhi
  • 2,981
  • 2
  • 16
  • 22
  • 1
    Use the inventory call to fetch the Purchase object and then consume it - its pretty easy once you get your head around it. – slott Dec 03 '14 at 08:34
  • 3
    Look at below answer from @mttmlins, or read http://www.vvse.com/blog/blog/2016/08/26/android-in-app-billing-clear-purchase-state-of-sku-android.test.purchased/ – IgorGanapolsky Feb 01 '17 at 16:42
  • Not completely true, i have a case where there is unconsumed test item, but `billingClient.queryPurchases()` does not return that unconsumed item, so now i can not consume item because i can not get `purchaseToken` of it – Jemshit Jan 22 '19 at 14:52
28

In-app version 3:

IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() {

    public void onQueryInventoryFinished(IabResult result, Inventory inventory) {

        .....................

        if (inventory.hasPurchase(SKU_CONTENT)) {

            mHelper.consumeAsync(inventory.getPurchase(SKU_CONTENT), null);
        }
    }
};
embo
  • 8,659
  • 1
  • 25
  • 23
  • As a picture is worth a thousand words, a complete working bare bones code piece is worth a thousand 'Add this code to a thread . . .'. – Androidcoder Dec 13 '18 at 16:34
15

Version 3 - Fastest way to solve : Clearing the cache of Google Play Store will let "android.test.purchased" available again.

Greelings
  • 4,964
  • 7
  • 34
  • 70
9

This is how we can consume the Item

 consume.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Thread t = new Thread(new Runnable() {
                @Override
                public void run() {
                    String purchaseToken = "inapp:" + getPackageName() + ":android.test.purchased";
                    try {
                        Log.d("","Running");
                        int response = mService.consumePurchase(3, getPackageName(), purchaseToken);
                        if(response==0)
                        {
                            Log.d("Consumed","Consumed");
                        }else {
                            Log.d("","No"+response);
                        }
                    }catch (RemoteException e)
                    {
                        Log.d("Errorr",""+e);
                    }

                }
            });
            t.start();
        }
    });
Shivaraj Patil
  • 8,186
  • 4
  • 29
  • 56
  • Worked for me - had used the `android.test.purchase` at some point which was causing issues - inventory task in in-app billing just threw a load of errors and never finished. Running this as a one-off cleared it so I could resume using my to my actual SKU and carry on as I was before. Thanks – Jon Jan 31 '15 at 06:55
  • 1
    Excellent answer. Works with Static Responses = before the apk with In-App Billing enabled is uploaded to Google Play. – infero Feb 23 '15 at 15:01
6

In my opinion if your program is not designed to consume the item you do not need to tweak the code in order to clear the memory of an outside vendor. This will make your code more fragile and you will have then to spend a lot of time to add and remove code that does not belong to your software so it is a bad design to implement a solution like that.

The best solution that worked for me to clear android.test.purchased was

adb uninstall com.yourapp.name

and then

adb shell pm clear com.android.vending

I did not need to clear cash and to browse my apps setting or to change code for that. I did need to add the adb to path variables of windows system which was pretty straight forward. So yes you need to use adb which you probably need anyway so..

You just add your C:\ ...\android-sdk\platform-tools; in windows path in environment variables, and I imagine that it is pretty simple in mac and linux os as well. Hope it helps someone to spend few days less with implementing android in app billings.

sivi
  • 10,654
  • 2
  • 52
  • 51
6

Go to the Google Play Developer Console, open Order Management menu item from the left side and select the order you want to refund. Also make sure to remove the entitlement.

CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
Sai Nadh
  • 81
  • 1
  • 3
  • I concur with this. Per Google, `To perform multiple test purchases for the same non-consumable product, you can refund and revoke purchases using Google Play Console.` More detail at https://developer.android.com/google/play/billing/test. – Bink Jan 06 '21 at 19:53
  • 1
    I guess this should be the accepted answer nowadays. When refunding make sure to also remove the entitlement of the test buyer, otherwise the item will still be owned. See https://stackoverflow.com/a/67633608/5369519. – flauschtrud Jun 14 '21 at 08:56
  • if i forgot to remove entitlement , what should i do – Hussien Fahmy Aug 11 '21 at 17:32
4

The main issue is you have to consume the android.test.purchased item. But this item won't be available in your query inventory, so you can't consume using the normal flow.

So, if you are using IabHelper, in IabHelper class, you can temporarily change the IInAppBillingService mService to public so that it is accessible from your IabHelper.

Then in your class, you can consume like this,

int response = mHelper.mService.consumePurchase(3, getPackageName(), "inapp:"+getPackageName()+":android.test.purchased");

If success, the response is going to be 0.

Hope this helps.

Rohit Sharma
  • 1,271
  • 5
  • 19
  • 37
Tang Tung Ai
  • 151
  • 2
3

For testing purposes I also suggest you to insert a piece of code that will be clearing all the products that you've bought before calling a method that initializes gp purchase flow. That is especially comfortable, when you test just one item at the moment. E.g. like this:

PurchasesResult purchasesResult = mBillingClient.queryPurchases(BillingClient.SkuType.INAPP);
    for (Purchase sourcePurchase : purchasesResult.getPurchasesList()) {
        if(sourcePurchase != null){

            ConsumeResponseListener listener = new ConsumeResponseListener() {
                @Override
                public void onConsumeResponse(String outToken, @BillingResponse int responseCode) {

                    System.out.println("all consumed");
                }
            };
            mBillingClient.consumeAsync(sourcePurchase.getPurchaseToken(), listener);
        }else{
            System.out.println("null");
        }
    }

// and then initiate whole process with clear "shoping basket"

BillingFlowParams.Builder builder = new BillingFlowParams.Builder()
        .setSku(itemName).setType(BillingClient.SkuType.INAPP);
sodiumnitrat
  • 211
  • 1
  • 11
1

If you are in test environment

1) In the case of android.test.purchased, I can reset the fake payment by restarting android device(consumed the inventory).

2) In InApp util there is a file called Security.java make it as following, for temporary. Since the testing payment(fake) always return false due to security exception.

public static boolean verifyPurchase(String base64PublicKey,
                                     String signedData, String signature) {
    return true; }

Then in your OnIabPurchaseFinishedListener call fechInvForconsumeItem()

IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener
            = new IabHelper.OnIabPurchaseFinishedListener() {
        public void onIabPurchaseFinished(IabResult result,
                                          Purchase purchase)
        {
            if (result.isFailure()) {
                // Handle error
                Log.e("123","Failure");

                return;
            }
            else if (purchase.getSku().equals(ITEM_SKU)) {
                Log.e("123","PURCAsed");
                fechInvForconsumeItem(); // Restart device if not consume

            }

        }
    };

The fechInvForconsumeItem() is

    public void fechInvForconsumeItem() {
    mHelper.queryInventoryAsync(mReceivedInventoryListener);
}
IabHelper.QueryInventoryFinishedListener mReceivedInventoryListener
        = new IabHelper.QueryInventoryFinishedListener() {
    public void onQueryInventoryFinished(IabResult result,
                                         Inventory inventory) {


        if (result.isFailure()) {
            // Handle failure
            Log.e("11","Failure");



        } else {
            Log.e("11","suc");
            mHelper.consumeAsync(inventory.getPurchase(ITEM_SKU),
                    mConsumeFinishedListener);
        }


    }
};

Consume Listener is

    IabHelper.OnConsumeFinishedListener mConsumeFinishedListener =
        new IabHelper.OnConsumeFinishedListener() {
            public void onConsumeFinished(Purchase purchase,
                                          IabResult result) {

                if (result.isSuccess()) {
                } else {
                    // handle error
                    Log.e("11","sucConsume");
                }
            }
        };
Ebin Joy
  • 2,690
  • 5
  • 26
  • 39
0
IabHelper.QueryInventoryFinishedListener 
       mQueryFinishedListener = new IabHelper.QueryInventoryFinishedListener() {
       public void onQueryInventoryFinished(IabResult result, Inventory inventory)   
       {
          if (result.isFailure()) {
             return;
           }          
          try {

                if(inventory.hasPurchase("product_sku_id"))
                {   
                     isItemEnable= true;
                     mHelper.consumeAsync(inventory.getPurchase("product_sku_id"),null);            
                }
                else
                {
                       isItemEnable = false;
                }           

            } catch (Exception e) {
                e.printStackTrace();
            }
       }

    };
Girish Patel
  • 1,270
  • 4
  • 16
  • 30
-1

In my case, it appears that Google does not record a purchase for the item. Rather, the local copy of Google Play Services caches the purchase. That way, when a second request is made on the same device, android.test.purchased already owned appears. However, using another device or resetting the device clears the cache, and allows the purchase to be repeated.

Tad
  • 4,668
  • 34
  • 35
-1

In my case, I just needed to clear the apps cache. After clearing the cache, I was able to initiate the purchase flow again.

From my device (4.4.2), I navigated to "Settings->Application manager". Next, I selected the app from the "DOWNLOADED" tab, and then "Clear cache".

-2

This is the difference between consumable and non-consumable items; non-consumable items (what you seem to be dealing with here) have their state tracked persistently, while consumable items can be purchased multiple times. You'll have to go into your Play management console and cancel/refund the sale to test it again.

addaon
  • 1,097
  • 9
  • 25
  • 1
    But the thing is that I don't have any "power" on these "fake" items, and I don't see where I could change the sale status, since they are not real purchases. The [google doc](http://developer.android.com/google/play/billing/billing_testing.html) says about the android.test.purchased : _When you make an In-app Billing request with this product ID, Google Play responds as though you successfully purchased an item._ So I'm pretty confused :/ – psykhi Dec 15 '12 at 23:06
  • Are you doing static response testing still? If so, you just need to change what static response is sent. It sounds like you're up to "Testing In-app Purchases Using Your Own Product IDs", though, which does real purchases with cancelable orders. – addaon Dec 15 '12 at 23:21
  • I'm still stuck with the static IDs. What I would like is to be able to test an in-app purchase with the android.test.purchased ID. It just worked the first time when it should always work from what I understand from the Google doc. Sorry if I was not clear! – psykhi Dec 15 '12 at 23:30
  • My misinterpretation, sorry. In that case... I don't know. It's definitely supposed to return success each time, I haven't seen the case you're seeing. Sorry. – addaon Dec 15 '12 at 23:42
  • Will try to look again at the problem after a good night of sleep :) Thanks for your help ! – psykhi Dec 16 '12 at 00:01
  • OP was asking specifically about **android.test.purchased**, which has nothing to do with Play Management console. – IgorGanapolsky Feb 01 '17 at 16:59