Handling coins, virtual currency, points, beans(?!) etc in the In App Purchasing Plugin

I’ve had a few developers ask me how to handle stuff like virtual currency in my In-App Purchasing plugin. Out of the box it handles ‘Managed’ items like extra game levels, new swords, santa hats of health 😉 etc with ease. However ‘UnManaged’ items that can be purchased multiple times tend to be a little more specific to your game. You probably already have a virtual currency variable, like ‘coins’, somewhere in your code and you just want to increment this by say 100 when someone purchases a productid of ‘coins_100’.

Well luckily this is really simple to do. After a person purchases a productid in your game, the plugin will automatically call ‘OnPurchaseResponse’ on a script attached to the ‘UnityGameObjectReceiver’ gameobject. In the demo scene I use this fact to call ‘UpdatePurchase’ to record when a ‘Managed’ item has been purchased. This can be easily extended to handle your ‘UnManaged’ items in the following way:

public static void UpdatePurchase(PurchaseInfo purchaseInfo){
  if(purchaseInfo==null) return;
  Debug.Log("OrderID:" + purchaseInfo.orderId + " productId:" + purchaseInfo.productId + " purchaseState:" + purchaseInfo.purchaseState);
  if(purchaseInfo.purchaseState == "PURCHASED"){		//If a purchase then add to list of purchased items
    //Put any Unmanaged items here
    if(purchaseInfo.productId == "coins_100"){
      GlobalStuff.coins += 100;
    }
    //Managed Items
    if(!Instance.PurchaseInfos.Contains(purchaseInfo)){//Don't add again if this orderid already exists
      Instance.PurchaseInfos.Add(purchaseInfo);
      Save();//When you purchase an item, immediately save to file
    }
  }
}

Where ‘GlobalStuff.coins’ is your virtual currency variable, for example I tend to stick all my ‘globals’ in a ‘GameStateManager’ static class and expose them as static properties, so mine would actually be ‘GameStateManager.Coins’.

Note that you will probably want to save those precious coins for your players in between game sessions. PlayerPrefs is a good way to do this…

Hope that all makes sense. Of course this post covers the Android version of the plugin, however the iOS version is almost identical so can be amended in a similar way.