Jakub Kuchar
Jakub Kuchar

Reputation: 1665

cordova-plugin-purchase how to call getPurchases?

I have implemented https://github.com/j3k0/cordova-plugin-purchase plugin for iOS and Android. Now I need to know previous purchases of user? Do I need to register events and wrap it in setTimeout or something like?

  store.when("product").updated(function(p) {
    if(p.loaded && p.valid && p.state === store.APPROVED){
      console.log("APPROVED", p)
      p.finish();
    }

    if(p.loaded && p.valid && p.state === store.OWNED){
      console.log('OWNED',p)
      var receipt =  JSON.parse(p.transaction.receipt)
      receipts.push(receipt)  
    }


    // never get here but it should be
    // if(p.loaded && p.valid && p.state === store.FINISHED){
    //   console.log('FINISHED',p)   
    // }

  });

  $timeout(function () {
    deferred.resolve(receipts)
  }, 10000);

Upvotes: 0

Views: 1971

Answers (1)

MegaAppBear
MegaAppBear

Reputation: 1220

First, From the plugin docs

  • When finished, a consumable product will get back to the VALID state, while other will enter the OWNED state.
  • Any error in the purchase process will bring a product back to the VALID state.
  • During application startup, products may go instantly from REGISTERED to APPROVED or OWNED, for example if they are purchased non-consumables or non-expired subscriptions.

And that's what's currently working for me.

//register callbacks 
store.when("hint_points_200").approved(function(product) {            
    //user gets the product and we finish. State goes back to "valid"
    product.finish();
});
store.when("hint_points_500").approved(function(product) {                
    //user gets the product and we finish. State goes to "owned". In my app, this gets called every time
    //the application restarts, the product seems to go back to the "approved" status
    product.finish();
});    


//Register "ready" callback to check the status of the products
store.ready(function(){
    p1 = store.get("200_coins");            
    p2 = store.get("500_coins");            
    console.log("p1.state:"+p1.state);
    console.log("p1.owned:"+p1.owned); //consumable. This should be "valid".
    console.log("p2.state:"+p2.state);
    console.log("p2.owned:"+p2.owned); //non-consumable. This should be "owned". (Doesn't work for me and "approved" callback gets called)

    //you should also have "p1.transactions" and "p2.transactions"
});

store.register({
    id:    "200_coins",     
    type:  store.CONSUMABLE
}); 
store.register({
    id:    "500_coins",
    type:  store.NON_CONSUMABLE
});

//refresh
store.refresh();

As I explained, I found that a non-consumable will trigger the "approved" callback on application restart. I had to handle it as a special case my app. You would need to do some testing to see what works for you.

Upvotes: 1

Related Questions