IAP Listeners
Codeless IAP dispatches successful and failed purchase events to an active IAP Button component in the hierarchy. However, there may be times when it is difficult or undesirable to have an active IAP Button when handling a successful purchase. For example, if a purchase is interrupted before completing, Unity IAP attempts to process the purchase again the next time it is initialized. You may want this to happen immediately after the app launches, in which case an IAP Button wouldn't make sense. Codeless IAP includes the IAP Listener component precisely for these cases. An active IAP Listener in the Scene hierarchy receives any purchase events that cannot be dispatched to an IAP Button.
To add an IAP Listener:
- In the Unity Editor, select Services > In-App Purchasing > Create IAP Listener.
- Follow the steps for writing a purchase fulfillment script as a GameObject component.
- Select the IAP Listener in the Scene and locate its IAP Listener (Script) component in the Inspector, then click the plus (+) button to add a function to the On Purchase Complete (Product) list.
- Drag the GameObject with the purchase fulfillment script onto the event field in the component’s Inspector, then select your function from the dropdown menu.
Purchase fulfillment
When your catalog contains at least one Product, you can define IAP Button behavior when the purchase completes or fails.
- Select your IAP Button in the Scene view, then locate its IAP Button (Script) component in the Inspector.
- Select the Product to link to the IAP Button from the Product ID drop-down list.
- Create your own function that provides purchase fulfillment, or import an Asset that does this (see code sample, below).
- Apply your purchase fulfilment script to a GameObject as a component.
- Return to the IAP Button (Script) component in the Inspector, and click the plus (+) button to add a function to the On Purchase Complete (Product) list.
- Drag the GameObject with the purchase fulfillment script onto the On Purchase Complete (Product) event field (illustrated below), then select your function from the dropdown menu.
Fulfillment script code sample:
public void GrantCredits (int credits){
userCredits = userCredits + credits;
Debug.Log(“You received “ + credits “ Credits!”);
}
Run your game to test the IAP Button.