In-App Purchasing: Scripting
This section provides a guide to work with the In-App Purchasing module scripting API.
You can access the In-App Purchasing module API via the InAppPurchasing class under the EasyMobile namespace.
Initialization
If auto-initialization is enabled, the module will automatically initialize Unity IAP at start without you having to do anything. Otherwise you have to initialize manually:
// Initialize the IAP module
InAppPurchasing.InitializePurchasing();
All further API calls can only be made after the initialization has finished. You can check if the module has been initialized:
// Check if the IAP module has been initialized
bool isInitialized = InAppPurchasing.IsInitialized();
Obtaining Product List
You can obtain the array of all products created in the module settings interface:
// Get the array of all products created in the In-App Purchasing module settings
// IAPProduct is the class representing a product as declared in the module settings
IAPProduct[] products = InAppPurchasing.GetAllIAPProducts();
// Print all product names
foreach (IAPProduct prod in products)
{
Debug.Log("Product name: " + prod.Name);
}
Making Purchases
You can purchase a product using its name.
It is strongly recommended that you use the constants of product names in the generated EM_IAPConstants class (see IAP Constants Generation section) instead of typing the names directly in order to prevent runtime errors due to typos and the likes.
// Purchase a product using its name
// EM_IAPConstants.Sample_Product is the generated name constant of a product named "Sample Product"
InAppPurchasing.Purchase(EM_IAPConstants.Sample_Product);
A PurchaseCompleted event will be fired if the purchase is successful, otherwise, a PurchaseFailed event will be fired instead. You can listen to these events and take appropriate actions, e.g. grant the user digital goods if the purchase has succeeded.
// Subscribe to IAP purchase events
void OnEnable()
{
InAppPurchasing.PurchaseCompleted += PurchaseCompletedHandler;
InAppPurchasing.PurchaseFailed += PurchaseFailedHandler;
}
// Unsubscribe when the game object is disabled
void OnDisable()
{
InAppPurchasing.PurchaseCompleted -= PurchaseCompletedHandler;
InAppPurchasing.PurchaseFailed -= PurchaseFailedHandler;
}
// Purchase the sample product
public void PurchaseSampleProduct()
{
// EM_IAPConstants.Sample_Product is the generated name constant of a product named "Sample Product"
InAppPurchasing.Purchase(EM_IAPConstants.Sample_Product);
}
// Successful purchase handler
void PurchaseCompletedHandler(IAPProduct product)
{
// Compare product name to the generated name constants to determine which product was bought
switch (product.Name)
{
case EM_IAPConstants.Sample_Product:
Debug.Log("Sample_Product was purchased. The user should be granted it now.");
break;
case EM_IAPConstants.Another_Sample_Product:
Debug.Log("Another_Sample_Product was purchased. The user should be granted it now.");
break;
// More products here...
}
}
// Failed purchase handler
void PurchaseFailedHandler(IAPProduct product, string failureReason)
{
Debug.Log("The purchase of product " + product.Name + " has failed with reason: " + failureReason);
}
Checking Ownership
You can check if a product is owned by specifying its name. A product is considered "owned" if its receipt exists and passes the receipt validation (if enabled).
// Check if the product is owned by the user
// EM_IAPConstants.Sample_Product is the generated name constant of a product named "Sample Product"
bool isOwned = InAppPurchasing.IsProductOwned(EM_IAPConstants.Sample_Product);
Consumable products' receipts are not persisted between app restarts, therefore this method only returns true for those products in the session they're purchased.
In the case of subscription products, this method simply checks if a product has been bought (subscribed) before and has a receipt. It doesn't check if the subscription is expired or not.
Restoring Purchases
Non-consumable and subscription products are restorable. App stores maintain a permanent record of each user's non-consumable and subscription products, so that he or she can be granted these products again when reinstalling your game.
Apple normally requires a Restore Purchases button to exist in your game, so that the users can explicitly initiate the purchase restoration process. On other platforms, e.g. Google Play, the restoration is done automatically during the first initialization after reinstallation.
During the restoration process, a PurchaseCompleted event will be fired for each owned product, as if the user has just purchased them again. Therefore you can reuse the same handler to grant the user their products as normal purchases.
On iOS, you can initiate a purchase restoration as below.
// Restore purchases. This method only has effect on iOS.
InAppPurchasing.RestorePurchases();
A RestoreCompleted event will be fired if the restoration is successful, otherwise, a RestoreFailed event will be fired instead. Note that these events only mean the success or failure of the restoration itself, while the PurchaseCompleted event will be fired for each restored product, as noted earlier. You can listen to these events and take appropriate actions, e.g. inform the user the restoration result.
The RestoreCompleted and RestoreFailed events are only raised on iOS.
// Subscribe to IAP restore events, these events are fired on iOS only.
void OnEnable()
{
InAppPurchasing.RestoreCompleted += RestoreCompletedHandler;
InAppPurchasing.RestoreFailed += RestoreFailedHandler;
}
// Successful restoration handler
void RestoreCompletedHandler()
{
Debug.Log("All purchases have been restored successfully.");
}
// Failed restoration handler
void RestoreFailedHandler()
{
Debug.Log("The purchase restoration has failed.");
}
// Unsubscribe
void OnDisable()
{
InAppPurchasing.RestoreCompleted -= RestoreCompletedHandler;
InAppPurchasing.RestoreFailed -= RestoreFailedHandler;
}
Apple Ask-To-Buy
On iOS 8.0 or newer, Ask To Buy purchases will defer for parental approval. You can subscribe to the PurchaseDeferred event to acknowledge when this occurs, and perform relevant actions such as updating UI to reflect the deferred state of the purchase. When the purchase is approved or rejected, the normal PurchaseCompleted or PurchaseFailed events will be fired.
// Subscribe to Ask To Buy purchases deferred event, this event is fired on iOS only.
void OnEnable()
{
InAppPurchasing.PurchaseDeferred += PurchaseDeferredHandler;
}
// Unsubscribe.
void OnDisable()
{
InAppPurchasing.PurchaseDeferred -= PurchaseDeferredHandler;
}
// This handler is invoked once an Ask To Buy purchase is deferred for parental approval.
void PurchaseDeferredHandler(IAPProduct product)
{
Debug.Log("Purchase of product " + product.Name + " has been deferred.");
// Perform necessary actions, e.g. updating UI to inform user that
// the purchase has been deferred...
}
You can simulate Ask To Buy feature in the sandbox app store for testing during development, see Settings/Apple Ask-To-Buy.
Apple Promotional Purchases
If you have enabled the Intercept Promotional Purchases option in the In-App Purchasing module settings, the PromotionalPurchaseIntercepted event will be fired every time a promotional purchase is intercepted. In the handler of this event you can perform relevant actions such as presenting parental gates, sending analytics events, etc. After that you must call the ContinueApplePromotionalPurchases method to continue the normal processing of the purchase. This will initiate any queued-up payments. Once the transaction is done, the normal PurchaseCompleted or PurchaseFailed event will be fired according to the purchase result.
If the Intercept Promotional Purchases option is disabled, the PromotionalPurchaseIntercepted event will never occur.
// Subscribe to promotional purchase intercepted event, this event is fired on iOS only.
void OnEnable()
{
InAppPurchasing.PromotionalPurchaseIntercepted += PromotionalPurchaseInterceptedHandler;
}
// Unsubscribe.
void OnDisable()
{
InAppPurchasing.PromotionalPurchaseIntercepted -= PromotionalPurchaseInterceptedHandler;
}
// This handler is invoked once a promotional purchase is intercepted.
void PromotionalPurchaseInterceptedHandler(IAPProduct product)
{
Debug.Log("Promotional purchase of product " + product.Name + " has been intercepted.");
// Here you can perform necessary actions, e.g. presenting parental gates,
// sending analytics events, etc.
// Finally, you must call the ContinueApplePromotionalPurchases method
// to continue the normal processing of the purchase!
InAppPurchasing.ContinueApplePromotionalPurchases();
}
You can also use the SetAppleStorePromotionVisibility and SetAppleStorePromotionOrder methods to respectively set the visibility of a promotional product and the order of visible promotional products on the Apple app store of the current device.