Knowledge base

Custom purchasing integration

Overview

Unity allows you to use its optimized monetization features without implementing Unity IAP. Use Unity Ads 3.0+ to create IAP Promos and leverage Personalized Placements while maintaining your own in-app purchasing solutions, by following these basic steps:

  1. Install Unity Ads SDK 3.0+) for your Project.
  2. Manually configure your Product Catalog on the Developer Dashboard.
  3. Configure an IAP Promo on the dashboard
  4. Implement a purchasing adapter in your game code, using the UnityPurchasing API.
  5. Implement game logic and purchase events within the purchasing adapter.
  6. Initialize the purchasing adapter and Monetization SDK.

Implementation

The following instructions are for Unity developers using C#.

  • If you are an iOS developer using Objective-C, click here.
  • If you are an Android developer using Java, click here.

Installing Unity Ads

To ensure the latest version of Unity Ads, download it from the Asset store. Purchasing integration requires SDK 3.0 or newer to access the Monetization API.

Configuring your Product Catalog on the Developer Dashboard

Before implementing your purchasing adapter, navigate to the Operate tab of the Developer Dashboard, then follow the manual configuration instructions for populating a Product Catalog.

Configuring your Promotion on the Developer Dashboard

From the Operate tab of the Developer Dashboard, follow the instructions for configuring an IAP Promo.

Modifying your code

Implementing the purchasing adapter

A purchasing adapter acts as the hook for the Monetization API to retrieve the information it needs from your custom IAP implementation.

In your game script, include the UnityEngine.Monetization namespace, then create a class that implements a purchasing adapter. You will use two functions, RetrieveProducts and OnPurchase, to define the game logic you want the purchasing adapter to use. These methods require a class using IPurchasingAdapter. You must implement them so the SDK can call them as needed when managing your Product transactions.

using UnityEngine.Monetization;

public class IAPManager: MonoBehaviour, IPurchasingAdapter {
    // Implement RetrieveProducts and OnPurchase functions here
}
Retrieving your Product Catalog

The SDK calls RetrieveProducts to retrieve the list of available Products. The function must convert your IAP products into Monetization.Product objects. This requires at minimum a productID, localizedPriceString, productType, isoCurrencyCode, and localizedTitle string for each Product.

The function takes an IRetrieveProductsListener listener. Call the listener’s OnProductsRetrieved function to send the retrieved Products list back to the SDK.

Processing a purchase

The SDK calls OnPurchase when a user clicks the buy button for a promotional asset. The purchase’s success or failure handling depends on your in-app purchasing implementation.

If the transaction succeeds, call the listener’s OnTransactionComplete function using a TransactionDetails object.

If the transaction fails, call the listener’s OnTransactionError function, using a TransactionErrorDetails object.

Example IPurchasingAdapter implementation:
using UnityEngine.Monetization;

public class IAPAdapter: MonoBehaviour, IPurchasingAdapter {

    // Retrieve and provide your Product Catalog for the SDK:    
    public void RetrieveProducts (IRetrieveProductsListener listener) {    

        // Query your Products here, convert them to Monetization.Products, then populate the Product list with them:        
        List<Product> products = new List<Product> ();
        products.Add (new Product) {
            productId = "100bronzeCoins",
            localizedTitle = "100 Bronze Coins",
            localizedDescription = "Awesome Bronze Coins for a new low price!",
            localizedPriceString = "$1.99",
            isoCurrencyCode = "USD",
            productType = "Consumable",
            localizedPrice = 1.99m
        });

        // provide the retrieved Products list:
        listener.OnProductsRetrieved (products);
    }

    // Define game logic for handling purchases:    
    public void OnPurchase (string productId, ITransactionListener listener, IDictionary<string, object> dict) {
        // Example third-party purchasing function:
        ThirdPartyPurchasing.purchaseProduct (productId);

        // When ThirdPartyPurchasing succeeds:
        listener.OnTransactionComplete (new TransactionDetails {
            currency = "USD",
            price = 1.99m,
            productId = "100bronzeCoins",
            transactionId = ThirdPartyPurchasing.transactionId,
            receipt =
                "{\n\"data\": \"{\\\"Store\\\":\\\"fake\\\",\\\"TransactionID\\\":\\\"ce7bb1ca-bd34-4ffb-bdee-83d2784336d8\\\",\\\"Payload\\\":\\\"{ \\\\\\\"this\\\\\\\": \\\\\\\"is a fake receipt\\\\\\\" }\\\"}\"\n}"
        });

        // When ThirdPartyPurchasing fails:
        listener.OnTransactionError (new TransactionErrorDetails {
            transactionError = TransactionError.NetworkCancelled,
            exceptionMessage = "Test exception message",
            store = Store.GooglePlay,
            storeSpecificErrorCode = "Example: Google Play lost connection",
        });
    }

Initializing the purchasing adapter and SDK

After you’ve implemented the purchasing adapter, you must provide a reference to it using SetPurchasingAdapter. Finally, you must initialize the SDK using your Project’s Game ID for the appropriate platform. You can locate the ID on the Operate tab of the Developer Dashboard by selecting a Project, then selecting Monetization > Platforms from the left navigation bar.

To avoid errors, implement these calls as early as possible in your game’s run-time life cycle. For example:

Start () {
    Monetization.SetPurchasingAdapter (GameObject.Find ("IAPManager").GetComponent<IAPAdapter> ()); 
    Monetization.Initialize ("1234567", false);
}

In this example, ‘IAPManager’ is a GameObject containing a script component ‘IAPAdapter’, which extends the purchasing adapter.

Back to top

Unity API

IPurchasingAdapter

An adapter that you implement and pass back to the SDK.

public interface IPurchasingAdapter {
    void RetrieveProducts (IRetrieveProductsListener listener);
    void Purchase (string productID, ITransactionListener listener, IDictionary<string, object> extras);
}

RetrieveProducts

The SDK calls this to retrieve the list of available Products.

void RetrieveProducts (IRetrieveProductsListener listener);

Use the IRetrieveProductsListener to register your Product list.

IRetrieveProductsListener

An interface for an object that the SDK passes back to you through IPurchasingAdapter.

public interface IRetrieveProductsListener {
    void OnProductsRetrieved (List<Product> availableProducts);
}

OnProductsRetrieved

The function must convert your IAP products into Monetization.Product objects. This requires at minimum a productID, localizedPriceString, productType, isoCurrencyCode, and localizedTitle string for each Product.

See the following example of an implemented retrieveProducts function:

public void RetrieveProducts (IRetrieveProductsListener listener) {

    // Query your Products here, convert them to Monetization.Products, then populate the Product list with them:        
    List<Product> products = new List<Product> ();
    products.Add (new Product) {
        productId = "100bronzeCoins",
        localizedTitle = "100 Bronze Coins",
        localizedDescription = "Awesome Bronze Coins for a new low price!",
        localizedPriceString = "$1.99",
        isoCurrencyCode = "USD",
        productType = "Consumable",
        localizedPrice = 1.99m
    });
    // provide the retrieved Products list:
    listener.OnProductsRetrieved (products);
}
Product

An IAP product converted into an object that the SDK can use for optimizing monetization.

Property Description
string productId An internal reference ID for the Product.
string localizedTitle A consumer-facing name for the Product, for store UI purposes.
string localizedPriceString A consumer-facing price string, including the currency sign, for store UI purposes.
double localizedPrice The internal system value for the Product’s price.
string isoCurrencyCode The ISO code for the Product’s localized currency.
string localizedDescription A consumer-facing Product description, for store UI purposes.
string productType Unity supports "Consumable", “Non-consumable”, and “Subscription” Product Types.

For more details on Product properties, see documentation on Defining Products.

OnPurchase

The SDK calls this when a user clicks the buy button for a promotional asset. Unity passes the purchased Product’s ID to your in-app purchasing system. The purchase’s success or failure handling depends on your in-app purchasing implementation.

public void Purchase (String productID, ITransactionListener listener, Map<String, Object> extras)
ITransactionListener

An interface for an object that the SDK passes back to you through IPurchasingAdapter.

public interface ITransactionListener {
    void onTransactionComplete (TransactionDetails details);
    void onTransactionError (TransactionError error, String message);
}

OnTransactionComplete

Your custom game logic for handling a successful transaction. The function takes a TransactionDetails object, which details the specifics of a transaction.

OnTransactionError

Your custom game logic for handling a failed transaction. The function takes a TransactionErrorDetails object, which identifies the source of transaction failure.

Example OnPurchase implementation
public void OnPurchase (string productId, ITransactionListener listener, IDictionary<string, object> dict) {
    // Example third-party purchasing function:
    ThirdPartyPurchasing.purchaseProduct (productId);

    // When ThirdPartyPurchasing succeeds:
    listener.OnTransactionComplete (new TransactionDetails {
        currency = "USD",
        price = 1.99m,
        productId = "100bronzeCoins",
        transactionId = ThirdPartyPurchasing.transactionId,
        receipt = "{\n\"data\": \"{\\\"Store\\\": \\\"fake\\\", \\\"TransactionID\\\": \\\"ce7bb1ca-bd34-4ffb-bdee-83d2784336d8\\\", \\\"Payload\\\": \\\"{ \\\\\\\"this\\\\\\\": \\\\\\\ "is a fake receipt\\\\\\\" }\\\"}\"\n}"
    });

    // When ThirdPartyPurchasing fails:
    listener.OnTransactionError (new TransactionErrorDetails {
        transactionError = TransactionError.NetworkCancelled,
        exceptionMessage = "Test exception message",
        store = Store.GooglePlay,
        storeSpecificErrorCode = "Example: Google Play lost connection",
    });
}
TransactionDetails

An IAP transaction receipt converted into an object that the SDK can use for optimizing monetization.

Property Description
string productId An internal reference ID for the Product.
string transactionId An internal reference ID for the transaction.
string receipt The JSON fields from the INAPP_PURCHASE_DATA detailing the transaction. Encode the receipt as a JSON object containing Store, TransactionID, and Payload.
decimal price The internal system value for the Product’s price.
string currency The ISO code for the Product’s localized currency.
TransactionErrorDetails

An object containing information about why a transaction failed.

public struct TransactionErrorDetails {
    public TransactionError transactionError;
    public string exceptionMessage;
    public Store store;
    public string storeSpecificErrorCode;
    public IDictionary<string, object> extras;
}

Back to top

Still need help? Get in touch!
Last updated on 16th Nov 2018