1
\$\begingroup\$

What I have

IAP button is working perfectly in unity editor. After purchasing, i'm getting debug message "ProcessPurchase: PASS. Product: 'full_version'" . But the button does nothing when I try to make a purchase on the device.

Don't have any errors when purchasing product in editor

What have i done so far

Automatically initialize UnityPurchasing checkbox is switched ON IAP catalog unity

  1. I've checked that the product ID, and price are the same in unity and Play console
  2. My IAP product is showing active in play console Play console IAP
  3. setup the Codeless IAP like this unity IAP component

LogCat error when I press the button on the device

2022-03-14 20:08:18.244 9293-9334/? E/Unity: Purchase failed because Purchasing was not initialized correctly
    UnityEngine.Purchasing.CodelessIAPStoreListener:InitiatePurchase(String)
    UnityEngine.Events.UnityAction:Invoke()
    UnityEngine.Events.UnityEvent:Invoke()
    UnityEngine.EventSystems.EventFunction`1:Invoke(T1, BaseEventData)
    UnityEngine.EventSystems.ExecuteEvents:Execute(GameObject, BaseEventData, EventFunction`1)
    UnityEngine.EventSystems.StandaloneInputModule:ProcessTouchPress(PointerEventData, Boolean, Boolean)
    UnityEngine.EventSystems.StandaloneInputModule:ProcessTouchEvents()
    UnityEngine.EventSystems.StandaloneInputModule:Process()

IAP script

using System;
using UnityEngine;
using UnityEngine.Purchasing; //библиотека с покупками, будет доступна когда активируем сервисы

public class IAP : MonoBehaviour, IStoreListener //для получения сообщений из Unity Purchasing
{
   

    private static IStoreController m_StoreController;          //доступ к системе Unity Purchasing
    private static IExtensionProvider m_StoreExtensionProvider; // подсистемы закупок для конкретных магазинов

    public static string fullVersion = "full_version";


    void Start()
    {
        if (m_StoreController == null) //если еще не инициализаровали систему Unity Purchasing, тогда инициализируем
        {
            InitializePurchasing();
        }

    }

    public void InitializePurchasing()
    {
        if (IsInitialized()) //если уже подключены к системе - выходим из функции
        {
            return;
        }

        var builder = ConfigurationBuilder.Instance(StandardPurchasingModule.Instance());

        builder.AddProduct(fullVersion, ProductType.NonConsumable);


        UnityPurchasing.Initialize(this, builder);
    }

    public void Buy_full_version()
    {
        BuyProductID(fullVersion);
    }

    

    void BuyProductID(string productId)
    {
        if (IsInitialized()) //если покупка инициализирована 
        {
            Product product = m_StoreController.products.WithID(productId); //находим продукт покупки 

            if (product != null && product.availableToPurchase) //если продукт найдет и готов для продажи
            {
                Debug.Log(string.Format("Purchasing product asychronously: '{0}'", product.definition.id));
                m_StoreController.InitiatePurchase(product); //покупаем
                
            }
            else
            {
                Debug.Log("BuyProductID: FAIL. Not purchasing product, either is not found or is not available for purchase");
            }
        }
        else
        {
            Debug.Log("BuyProductID FAIL. Not initialized.");
        }
    }

    public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args) //контроль покупок
    {
        


        

         if (String.Equals(args.purchasedProduct.definition.id, fullVersion, StringComparison.Ordinal))
        {
            Debug.Log(string.Format("ProcessPurchase: PASS. Product: '{0}'", args.purchasedProduct.definition.id));

            //действия при покупке
            if (PlayerPrefs.HasKey("full_version") == false)
            {
                PlayerPrefs.SetInt("full_version", 1);

            }
            
        }

        else
        {
            Debug.Log(string.Format("ProcessPurchase: FAIL. Unrecognized product: '{0}'", args.purchasedProduct.definition.id));
        }

        return PurchaseProcessingResult.Complete;
    }

    public void RestorePurchases() //Восстановление покупок (только для Apple). У гугл это автоматический процесс.
    {
        if (!IsInitialized())
        {
            Debug.Log("RestorePurchases FAIL. Not initialized.");
            return;
        }

        if (Application.platform == RuntimePlatform.IPhonePlayer ||
            Application.platform == RuntimePlatform.OSXPlayer) //если запущенно на эпл устройстве
        {
            Debug.Log("RestorePurchases started ...");

            var apple = m_StoreExtensionProvider.GetExtension<IAppleExtensions>();

            apple.RestoreTransactions((result) =>
            {
                Debug.Log("RestorePurchases continuing: " + result + ". If no further messages, no purchases available to restore.");
            });
        }
        else
        {
            Debug.Log("RestorePurchases FAIL. Not supported on this platform. Current = " + Application.platform);
        }
    }



    public void OnInitialized(IStoreController controller, IExtensionProvider extensions)
    {
        Debug.Log("OnInitialized: PASS");
        m_StoreController = controller;
        m_StoreExtensionProvider = extensions;
    }

    private bool IsInitialized()
    {
        return m_StoreController != null && m_StoreExtensionProvider != null;
    }

    public void OnInitializeFailed(InitializationFailureReason error)
    {
        Debug.Log("OnInitializeFailed InitializationFailureReason:" + error);
    }

    public void OnPurchaseFailed(Product product, PurchaseFailureReason failureReason)
    {
        Debug.Log(string.Format("OnPurchaseFailed: FAIL. Product: '{0}', PurchaseFailureReason: {1}", product.definition.storeSpecificId, failureReason));
    }



}

The problem is that I don't understand what this error means, and subsequently how to solve it. Hoping for your help

\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

In my case activating/initializing of IAP in Project Settings->Services->In-app purchasing helped me. Hope this will be helpful for you too.

\$\endgroup\$
1
  • \$\begingroup\$ This answer would be even better if it showed the steps for activating and initializing IAP. \$\endgroup\$
    – DMGregory
    Jul 30, 2022 at 18:54
1
\$\begingroup\$

Remove the event trigger added to the button component itself (PlayButtonSound();)

\$\endgroup\$
1
  • 3
    \$\begingroup\$ This answer would be better if it explained how this solves the problem. \$\endgroup\$
    – DMGregory
    Jan 1 at 11:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .