Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Android IAP not initialized and OnInitializeFailed is not triggered..

Discussion in 'Scripting' started by Prismatecs, Jun 17, 2016.

  1. Prismatecs

    Prismatecs

    Joined:
    May 20, 2016
    Posts:
    19
    Hello Everyone,

    I was trying to implement IAP for my app and I got everything in place, however on testing debugger prints ("BuyProductID FAIL. Not initialized.") and OnInitializeFailed function is not triggered so I can see the failure reason.

    I'm using a similar code as the code from this tutorial:
    https://unity3d.com/learn/tutorials/topics/analytics/integrating-unity-iap-your-game

    Code (CSharp):
    1. using System;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.Purchasing;
    5.     // Deriving the Purchaser class from IStoreListener enables it to receive messages from Unity Purchasing.
    6.     public class Purchaser : MonoBehaviour, IStoreListener
    7.     {
    8.         public GameObject mCode;
    9.        
    10.         private static IStoreController m_StoreController; // Reference to the Purchasing system.
    11.         private static IExtensionProvider m_StoreExtensionProvider; // Reference to store-specific Purchasing
    12.         private static string kItems = "full_version"; // General handle for the consumable product.
    13.        
    14.         private static string kGooglePlayItems = "full_version"; // Google Play Store identifier for the consumable product.
    15.  
    16.         void Start()
    17.         {
    18.             //Debug.Log("Starting.............");
    19.             // If we haven't set up the Unity Purchasing reference
    20.             if (m_StoreController == null)
    21.             {
    22.                 // Begin to configure our connection to Purchasing
    23.                 InitializePurchasing();
    24.                 //Debug.Log("Intializing.............");
    25.             }
    26.            
    27.         }
    28.  
    29.         public void InitializePurchasing()
    30.         {
    31.             // If we have already connected to Purchasing ...
    32.             if (IsInitialized())
    33.             {
    34.                 // ... we are done here.
    35.                 Debug.Log("Already initialized.");
    36.                 return;
    37.             }
    38.      
    39.             // Create a builder, first passing in a suite of Unity provided stores.
    40.             var builder = ConfigurationBuilder.Instance(StandardPurchasingModule.Instance());
    41.      
    42.             // Add a product to sell / restore by way of its identifier, associating the general identifier with its store-specific identifiers.
    43.             builder.AddProduct(kItems, ProductType.NonConsumable, new IDs(){ {kGooglePlayItems,  GooglePlay.Name} });// Continue adding the non-consumable product.
    44.      
    45.             UnityPurchasing.Initialize(this, builder);
    46.         }
    47.  
    48.  
    49.         private bool IsInitialized()
    50.         {
    51.             // Only say we are initialized if both the Purchasing references are set.
    52.             return m_StoreController != null && m_StoreExtensionProvider != null;
    53.         }
    54.  
    55.         public void BuyNonConsumable()
    56.         {
    57.             // Buy the non-consumable product using its general identifier. Expect a response either through ProcessPurchase or OnPurchaseFailed asynchronously.
    58.             BuyProductID(kItems);
    59.         }
    60.  
    61.  
    62.         void BuyProductID(string productId)
    63.         {
    64.             // If the stores throw an unexpected exception, use try..catch to protect my logic here.
    65.             try
    66.             {
    67.                 // If Purchasing has been initialized ...
    68.                 if (IsInitialized())
    69.                 {
    70.                     // ... look up the Product reference with the general product identifier and the Purchasing system's products collection.
    71.                     Product product = m_StoreController.products.WithID(productId);
    72.              
    73.                     // If the look up found a product for this device's store and that product is ready to be sold ...
    74.                     if (product != null && product.availableToPurchase)
    75.                     {
    76.                         Debug.Log (string.Format("Purchasing product asychronously: '{0}'", product.definition.id));// ... buy the product. Expect a response either through ProcessPurchase or OnPurchaseFailed asynchronously.
    77.                         m_StoreController.InitiatePurchase(product);
    78.                     }
    79.                     // Otherwise ...
    80.                     else
    81.                     {
    82.                         // ... report the product look-up failure situation
    83.                         Debug.Log ("BuyProductID: FAIL. Not purchasing product, either is not found or is not available for purchase");
    84.                     }
    85.                 }
    86.                 // Otherwise ...
    87.                 else
    88.                 {
    89.                     // ... report the fact Purchasing has not succeeded initializing yet. Consider waiting longer or retrying initiailization.
    90.                     Debug.Log("BuyProductID FAIL. Not initialized.");
    91.                 }
    92.             }
    93.             // Complete the unexpected exception handling ...
    94.             catch (Exception e)
    95.             {
    96.                 // ... by reporting any unexpected exception for later diagnosis.
    97.                 Debug.Log ("BuyProductID: FAIL. Exception during purchase. " + e);
    98.             }
    99.         }
    100.  
    101.  
    102.         // Restore purchases previously made by this customer. Some platforms automatically restore purchases. Apple currently requires explicit purchase restoration for IAP.
    103.         public void RestorePurchases()
    104.         {
    105.             // If Purchasing has not yet been set up ...
    106.             if (!IsInitialized())
    107.             {
    108.                 // ... report the situation and stop restoring. Consider either waiting longer, or retrying initialization.
    109.                 Debug.Log("RestorePurchases FAIL. Not initialized.");
    110.                 return;
    111.             }
    112.      
    113.             // If we are running on an Apple device ...
    114.             if (Application.platform == RuntimePlatform.IPhonePlayer ||
    115.                 Application.platform == RuntimePlatform.OSXPlayer)
    116.             {
    117.                 // ... begin restoring purchases
    118.                 Debug.Log("RestorePurchases started ...");
    119.          
    120.                 // Fetch the Apple store-specific subsystem.
    121.                 var apple = m_StoreExtensionProvider.GetExtension<IAppleExtensions>();
    122.                 // Begin the asynchronous process of restoring purchases. Expect a confirmation response in the Action<bool> below, and ProcessPurchase if there are previously purchased products to restore.
    123.                 apple.RestoreTransactions((result) => {
    124.                     // The first phase of restoration. If no more responses are received on ProcessPurchase then no purchases are available to be restored.
    125.                     Debug.Log("RestorePurchases continuing: " + result + ". If no further messages, no purchases available to restore.");
    126.                 });
    127.             }
    128.             // Otherwise ...
    129.             else
    130.             {
    131.                 // We are not running on an Apple device. No work is necessary to restore purchases.
    132.                 Debug.Log("RestorePurchases FAIL. Not supported on this platform. Current = " + Application.platform);
    133.             }
    134.         }
    135.  
    136.  
    137.         //
    138.         // --- IStoreListener
    139.         //
    140.  
    141.         public void OnInitialized(IStoreController controller, IExtensionProvider extensions)
    142.         {
    143.             // Purchasing has succeeded initializing. Collect our Purchasing references.
    144.             Debug.Log("OnInitialized: PASS");
    145.      
    146.             // Overall Purchasing system, configured with products for this application.
    147.             m_StoreController = controller;
    148.             // Store specific subsystem, for accessing device-specific store features.
    149.             m_StoreExtensionProvider = extensions;
    150.         }
    151.  
    152.  
    153.         public void OnInitializeFailed(InitializationFailureReason error)
    154.         {
    155.             // Purchasing set-up has not succeeded. Check error for reason. Consider sharing this reason with the user.
    156.             Debug.Log("OnInitializeFailed InitializationFailureReason:" + error);
    157.         }
    158.  
    159.  
    160.         public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args)
    161.         {
    162.             // A consumable product has been purchased by this user.
    163.             if (String.Equals(args.purchasedProduct.definition.id, kItems, StringComparison.Ordinal))
    164.             {
    165.                 Debug.Log(string.Format("ProcessPurchase: PASS. Product: '{0}'", args.purchasedProduct.definition.id));
    166.                 //If the item has been successfully purchased, store the item for later use!
    167.                 //PlayerPrefs.SetInt("Items_All", 1);
    168.                 //_Main.Invoke("Got_Items", 0); //Call a function in another script to play some effects.
    169.                 //WRITR LICENSE
    170.                 mCode.GetComponent<VersionChecker>().WriteLicense();
    171.                 mCode.GetComponent<VersionChecker>().HideBuyPanel();
    172.             }
    173.             else
    174.             {
    175.                 Debug.Log(string.Format("ProcessPurchase: FAIL. Unrecognized product: '{0}'", args.purchasedProduct.definition.id));
    176.                 PlayerPrefs.SetInt("Itemss_All", 0);
    177.             }
    178.             // Return a flag indicating wither this product has completely been received, or if the application needs to be reminded of this purchase at next app launch. Is useful when saving purchased products to the cloud, and when that save is delayed.
    179.             return PurchaseProcessingResult.Complete;
    180.         }
    181.  
    182.  
    183.         public void OnPurchaseFailed(Product product, PurchaseFailureReason failureReason)
    184.         {
    185.             // A product purchase attempt did not succeed. Check failureReason for more detail. Consider sharing this reason with the user.
    186.             Debug.Log(string.Format("OnPurchaseFailed: FAIL. Product: '{0}', PurchaseFailureReason: {1}",product.definition.storeSpecificId, failureReason));}
    187.     }
    - I have published the app on Google Play
    - I'm sure product is available under the same id i'm using and it's active (full_version)
    - I've set the Google Play Key in unity google analytics

    What could I be doing wrong?

    Thank You,
     
  2. Prismatecs

    Prismatecs

    Joined:
    May 20, 2016
    Posts:
    19
    Notes:
    It's initialized just fine on PC Editor
    Running unity 5.3.0f4
     
  3. _watcher_

    _watcher_

    Joined:
    Nov 7, 2014
    Posts:
    259
    Same problem here. (Unity 5.3.4f1)

    Sometimes when testing offline, OnInitialized does not trigger. Thus i cant get list of available purchases. Is this a known bug?
     
  4. vinicioslc

    vinicioslc

    Joined:
    Oct 8, 2014
    Posts:
    1
    I have the same issue some body can help ???????
     
  5. ramon_delmondo

    ramon_delmondo

    Joined:
    Aug 19, 2015
    Posts:
    22
    Same problem here. (Unity 5.4.0)
    It works on editor.

    Testing on android:

    08-10 14:03:10.478: I/Unity(30468): BuyProductID FAIL. Not initialized.
    08-10 14:03:10.478: I/Unity(30468): UnityEngine.DebugLogHandler:Internal_Log(LogType, String, Object)
    08-10 14:03:10.478: I/Unity(30468): UnityEngine.DebugLogHandler:LogFormat(LogType, Object, String, Object[])
    08-10 14:03:10.478: I/Unity(30468): UnityEngine.Logger:Log(LogType, Object)
    08-10 14:03:10.478: I/Unity(30468): UnityEngine.Debug:Log(Object)
    08-10 14:03:10.478: I/Unity(30468): CompleteProject.PurchaseController:BuyProductID(String) (at C:\Users\Cliente\Desktop\Coobo Repository 2\Assets\Scripts\PurchaseController.cs:225)
    08-10 14:03:10.478: I/Unity(30468): CompleteProject.PurchaseController:Buy1700coins() (at C:\Users\Cliente\Desktop\Coobo Repository 2\Assets\Scripts\PurchaseController.cs:154)
    08-10 14:03:10.478: I/Unity(30468): UnityEngine.Events.InvokableCall:Invoke(Object[]) (at /Users/builduser/buildslave/unity/build/Runtime/Export/UnityEvent.cs:153)
    08-10 14:03:10.478: I/Unity(30468): UnityEngine.Events.InvokableCallList:Invoke(Object[]) (at /Users/builduser/buildslave/unity/build/Runtime/Export/UnityEvent.cs:630)
    08-10 14:03:10.478: I/Unity(30468): UnityEngine.Events.UnityEventBase:Invoke(Object[]) (at /Users/builduser/buildslave/unity/build/Runtime/Export/UnityEvent.cs:765)
    08-10 14:03:10.478: I/Unity(30468): UnityEngine.Events.UnityEvent:Invoke() (at /Users/builduser/buildslave/unity/build/Runtime/Export/Unity

    Someone can help?