In-App Purchasing: Advanced Scripting

This section describes the methods to accomplish tasks beyond the basic ones such as making or restoring purchases. These tasks include retrieving product localized data, reading product receipts, refreshing receipts, etc.

Most of the methods described in this section are only available once Easy Mobile's IAP module and Unity IAP service are enabled, which is indicated by the definition of the symbol EM_UIAP. Therefore, you should always wrap the use of these methods inside a check for the existing of this symbol.

Also, the types exposed in these methods are only available when the Unity IAP package is imported, and you should include the UnityEngine.Purchasing and UnityEngine.Purchasing.Security namespaces at the top of your script for these types to be recognized.

Getting Unity IAP's Product Object

The in-app products are represented in Unity IAP by the Product class, which is different from Easy Mobile's IAPProduct class, whose main purpose is for settings and displaying. This Product class is the entry point to access product-related data including its metadata and receipt, which is populated automatically by Unity IAP. To obtain the Product object of an in-app product, call the GetProduct method with the product name.

#if EM_UIAP
using UnityEngine.Purchasing;
#endif



// Obtain the Product object of the sample product and print its data
public void GetSampleProduct()
{
    #if EM_UIAP
    // EM_IAPConstants.Sample_Product is the generated name constant of a product named "Sample Product"
    Product sampleProduct = InAppPurchasing.GetProduct(EM_IAPConstants.Sample_Product);

    if (sampleProduct != null)
    {
        Debug.Log("Available To Purchase: " + sampleProduct.availableToPurchase.ToString());
        if (sampleProduct.hasReceipt)
        {
            Debug.Log("Receipt: " + sampleProduct.receipt);
        }
    }            
    #endif
}

Getting Product Localized Data

You can get a product's metadata retrieved from targeted app stores, e.g. localized title, description and price. This information is particularly useful when building a storefront in your game for displaying the in-app products. To get the localized data of a product, call the GetProductLocalizedData and specify the product name. The following example iterates through the product list and retrieve the localized data of each item.

#if EM_UIAP
using UnityEngine.Purchasing;
#endif



// Iterate through the product list and get the localized data retrieved from the targeted app store.
// Note the check for the EM_UIAP symbol.
void PrintProductsMetadata()
{
    #if EM_UIAP
    // Get all products created in the In-App Purchasing module settings
    IAPProduct[] products = EM_Settings.InAppPurchasing.Products;

    foreach (IAPProduct prod in products)
    {
        // Get product localized data.
        ProductMetadata data = InAppPurchasing.GetProductLocalizedData(prod.Name);

        if (data != null)
        {
            Debug.Log("Localized title: " + data.localizedTitle);
            Debug.Log("Localized description: " + data.localizedDescription);
            Debug.Log("Localized price string: " + data.localizedPriceString);
        }  
    }
    #endif
}

Getting Subscription Info

You can get a subscription product's information such as expire date using the GetSubscriptionInfo method. Internally, this method uses Unity IAP's SubscriptionManager class to retrieve the subscription data. The following example iterates through the product list and prints the information of each subscription product.

#if EM_UIAP
using UnityEngine.Purchasing;
#endif


// Iterates through all available products and prints the data of subscriptions.
public void PrintSubscriptionInfo()
{
    #if EM_UIAP    
    // Get all products created in the In-App Purchasing module settings.
    IAPProduct[] products = EM_Settings.InAppPurchasing.Products;

    foreach (IAPProduct p in products)
    {
        // If this is a subscription product.
        if (p.Type == IAPProductType.Subscription)
        {
            // Get the subscription information of the current product,
            // note that this method takes the product name as input.
            SubscriptionInfo info = InAppPurchasing.GetSubscriptionInfo(p.Name);

            if (info == null)
            {
                Debug.Log("The subscription information of this product could not be retrieved.");
                continue;
            }

            // Prints subscription info.
            Debug.Log("Product ID: " + info.getProductId());
            Debug.Log("Purchase Date: " + info.getPurchaseDate());
            Debug.Log("Is Subscribed: " + info.isSubscribed());
            Debug.Log("Is Expired: " + info.isExpired());
            Debug.Log("Is Cancelled: " + info.isCancelled());
            Debug.Log("Is FreeTrial: " + info.isFreeTrial());
            Debug.Log("Is Auto Renewing: " + info.isAutoRenewing());
            Debug.Log("Remaining Time: " + info.getRemainingTime().ToString());
            Debug.Log("Is Introductory Price Period: " + info.isIntroductoryPricePeriod());
            Debug.Log("Introductory Price Period: " + info.getIntroductoryPricePeriod().ToString());
            Debug.Log("Introductory Price Period Cycles: " + info.getIntroductoryPricePeriodCycles());
            Debug.Log("Introductory Price: " + info.getIntroductoryPrice());
            Debug.Log("Expire Date: " + info.getExpireDate());
        }
    }
    #endif
}

Working with Receipts

This sections describes methods to work with receipts. Currently, Unity IAP only supports parsing receipts from Apple stores and Google Play store.

Note that for the receipt reading methods to work, you need to enable receipt validation feature (see the Receipt Validation section).

Apple App Receipt

On iOS, you can get the parsed Apple App Receipt for your app using the GetAppleAppReceipt method.

#if EM_UIAP
using UnityEngine.Purchasing;
using UnityEngine.Purchasing.Security;
#endif



// Read the App Receipt on iOS. Receipt validation is required.
void ReadAppleAppReceipt()
{
    #if EM_UIAP
    if (Application.platform == RuntimePlatform.IPhonePlayer)
    {
        AppleReceipt appReceipt = InAppPurchasing.GetAppleAppReceipt();

        // Print the receipt content.
        if (appReceipt != null)
        {
            Debug.Log("App Version: " + appReceipt.appVersion);
            Debug.Log("Bundle ID: " + appReceipt.bundleID);
            Debug.Log("Number of purchased products: " + appReceipt.inAppPurchaseReceipts.Length);
        }
    }
    #endif
}

Apple InAppPurchase Receipt

On iOS, you can get the parsed Apple InAppPurchase receipt for a particular product, using the GetAppleIAPReceipt method with the name of the product.

#if EM_UIAP
using UnityEngine.Purchasing;
using UnityEngine.Purchasing.Security;
#endif



// Read the InAppPurchase receipt of the sample product on iOS.
// Receipt validation is required.
void ReadAppleInAppPurchaseReceipt()
{
    #if EM_UIAP
    if (Application.platform == RuntimePlatform.IPhonePlayer)
    {
        // EM_IAPConstants.Sample_Product is the generated name constant of a product named "Sample Product".
        AppleInAppPurchaseReceipt receipt = InAppPurchasing.GetAppleIAPReceipt(EM_IAPConstants.Sample_Product);

        // Print the receipt content.
        if (receipt != null)
        {
            Debug.Log("Product ID: " + receipt.productID);
            Debug.Log("Original Purchase Date: " + receipt.originalPurchaseDate.ToShortDateString());
            Debug.Log("Original Transaction ID: " + receipt.originalTransactionIdentifier);
            Debug.Log("Purchase Date: " + receipt.purchaseDate.ToShortDateString());
            Debug.Log("Transaction ID: " + receipt.transactionID);
            Debug.Log("Quantity: " + receipt.quantity);
            Debug.Log("Cancellation Date: " + receipt.cancellationDate.ToShortDateString());
            Debug.Log("Subscription Expiration Date: " + receipt.subscriptionExpirationDate.ToShortDateString());
        }
    }
    #endif
}

Google Play Receipt

On Android, you can get the parse GooglePlay receipt for a particular product, using the GetGooglePlayReceipt method with the name of the product.

#if EM_UIAP
using UnityEngine.Purchasing;
using UnityEngine.Purchasing.Security;
#endif



// Read the GooglePlay receipt of the sample product on Android.
// Receipt validation is required.
void ReadGooglePlayReceipt()
{
    #if EM_UIAP
    if (Application.platform == RuntimePlatform.Android)
    {
        // EM_IAPConstants.Sample_Product is the generated name constant of a product named "Sample Product".
        GooglePlayReceipt receipt = InAppPurchasing.GetGooglePlayReceipt(EM_IAPConstants.Sample_Product);

        if (receipt != null)
        {
            Debug.Log("Package Name: " + receipt.packageName);
            Debug.Log("Product ID: " + receipt.productID);
            Debug.Log("Purchase Date: " + receipt.purchaseDate.ToShortDateString());
            Debug.Log("Purchase State: " + receipt.purchaseState.ToString());
            Debug.Log("Transaction ID: " + receipt.transactionID);
            Debug.Log("Purchase Token: " + receipt.purchaseToken);
        }
    }
    #endif
}

Refreshing Apple App Receipt

Apple provides a mechanism to fetch a new App Receipt from their servers, typically used when no receipt is currently cached in local storage SKReceiptRefreshRequest. You can refresh the App Receipt on iOS using the RefreshAppleAppReceipt method. Note that this will prompt the user for their password.

// Fetch a new Apple App Receipt on iOS. This will prompt the user for their password.
void RefreshAppleAppReceipt()
{
    if (Application.platform == RuntimePlatform.IPhonePlayer)
    {
        InAppPurchasing.RefreshAppleAppReceipt(SuccessCallback, ErrorCallback);
    }
}

void SuccessCallback(string receipt)
{
    Debug.Log("App Receipt refreshed successfully. New receipt: " + receipt);
}

void ErrorCallback()
{
    Debug.Log("App Receipt refreshing failed.");
}

results matching ""

    No results matching ""