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

IAP working in editor but not on mobile

Discussion in 'Scripting' started by wjhbrendan, Dec 11, 2016.

  1. wjhbrendan

    wjhbrendan

    Joined:
    Jul 17, 2016
    Posts:
    15
    Hey guys i've been stumped for the past few days on this IAP problem
    I currently have 4 buttons that purchase gold. They are set up with IAP and i'm getting all the correct console logs when i purchase in my editor. It is also funding the account.

    When I test it on my mobile devices, the button just doesn't do anything. It doesn't pop up the purchase dialogue. I have added the 4 product ids to my apple and google dev accounts as "gold1000","gold2000","gold4000","gold8000"

    Any help is greatly appreciated, thank you so much!!!

    Here is my IAPManager script
    ____________________________
    using System;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.Purchasing;

    //PlacingthePurchaserclassintheCompleteProjectnamespaceallowsittointeractwithScoreManager,
    //oneoftheexistingSurvivalShooterscripts.
    //DerivingthePurchaserclassfromIStoreListenerenablesittoreceivemessagesfromUnityPurchasing.
    public class IAPManager : MonoBehaviour, IStoreListener
    {
    public static IAPManager Instance { set; get;}

    private static IStoreController m_StoreController; //TheUnityPurchasingsystem.
    private static IExtensionProvider m_StoreExtensionProvider; //Thestore-specificPurchasingsubsystems.

    //Productidentifiersforallproductscapableofbeingpurchased:
    //"convenience"generalidentifiersforusewithPurchasing,andtheirstore-specificidentifier
    //counterpartsforusewithandoutsideofUnityPurchasing.Definestore-specificidentifiers
    //alsooneachplatform'spublisherdashboard(iTunesConnect,GooglePlayDeveloperConsole,etc.)

    //Generalproductidentifiersfortheconsumable,non-consumable,andsubscriptionproducts.
    //Usethesehandlesinthecodetoreferencewhichproducttopurchase.Alsousethesevalues
    //whendefiningtheProductIdentifiersonthestore.Except,forillustrationpurposes,the
    //kProductIDSubscription-ithascustomAppleandGoogleidentifiers.Wedeclaretheirstore-
    //specificmappingtoUnityPurchasing'sAddProduct,below.
    public static string PRODUCT_1000_GOLD = "gold1000";
    public static string PRODUCT_2000_GOLD = "gold2000";
    public static string PRODUCT_4000_GOLD = "gold4000";
    public static string PRODUCT_8000_GOLD = "gold8000";
    private DisplayAmountOfCoins displayCoins;

    //AppleAppStore-specificproductidentifierforthesubscriptionproduct.
    private static string kProductNameAppleSubscription = "com.unity3d.subscription.new";

    //GooglePlayStore-specificproductidentifiersubscriptionproduct.
    private static string kProductNameGooglePlaySubscription = "com.unity3d.subscription.original";

    private void Awake()
    {
    Instance = this;
    }
    void Start()
    {
    //Ifwehaven'tsetuptheUnityPurchasing reference
    if (m_StoreController == null)
    {
    //Begintoconfigureourconnectionto Purchasing
    InitializePurchasing();
    }
    }

    public void InitializePurchasing()
    {
    //IfwehavealreadyconnectedtoPurchasing...
    if (IsInitialized())
    {
    //...wearedonehere.
    return;
    }

    //Createabuilder,firstpassinginasuiteofUnityprovidedstores.
    var builder = ConfigurationBuilder.Instance(StandardPurchasingModule.Instance());

    //Addaproducttosell/restorebywayofitsidentifier,associatingthegeneral identifier
    //withitsstore-specificidentifiers.
    builder.AddProduct(PRODUCT_1000_GOLD, ProductType.Consumable);
    builder.AddProduct(PRODUCT_2000_GOLD, ProductType.Consumable);
    builder.AddProduct(PRODUCT_4000_GOLD, ProductType.Consumable);
    builder.AddProduct(PRODUCT_8000_GOLD, ProductType.Consumable);

    //Kickofftheremainderoftheset-upwithanasynchrounouscall,passingtheconfiguration
    //andthisclass'instance.ExpectaresponseeitherinOnInitializedorOnInitializeFailed.
    UnityPurchasing.Initialize(this, builder);
    }


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


    public void Buy1000Gold()
    {
    //Buytheconsumableproductusingitsgeneralidentifier.Expectaresponseeither
    //throughProcessPurchaseorOnPurchaseFailedasynchronously.
    BuyProductID(PRODUCT_1000_GOLD);
    }

    public void Buy2000Gold()
    {
    //Buytheconsumableproductusingitsgeneralidentifier.Expectaresponseeither
    //throughProcessPurchaseorOnPurchaseFailedasynchronously.
    BuyProductID(PRODUCT_2000_GOLD);
    }

    public void Buy4000Gold()
    {
    //Buytheconsumableproductusingitsgeneralidentifier.Expectaresponseeither
    //throughProcessPurchaseorOnPurchaseFailedasynchronously.
    BuyProductID(PRODUCT_4000_GOLD);
    }

    public void Buy8000Gold()
    {
    //Buytheconsumableproductusingitsgeneralidentifier.Expectaresponseeither
    //throughProcessPurchaseorOnPurchaseFailedasynchronously.
    BuyProductID(PRODUCT_8000_GOLD);
    }


    private void BuyProductID(string productId)
    {
    //IfPurchasinghasbeeninitialized...
    if (IsInitialized())
    {
    //...lookuptheProductreferencewiththegeneralproductidentifierandthePurchasing
    //system'sproductscollection.
    Product product = m_StoreController.products.WithID(productId);

    //Ifthelookupfoundaproductforthisdevice'sstoreandthatproductisreadytobesold...
    if (product != null && product.availableToPurchase)
    {
    Debug.Log(string.Format("Purchasingproductasychronously:'{0}'", product.definition.id));
    //...buytheproduct.ExpectaresponseeitherthroughProcessPurchaseorOnPurchaseFailed
    //asynchronously.
    m_StoreController.InitiatePurchase(product);
    }
    //Otherwise...
    else
    {
    //...reporttheproductlook-upfailuresituation
    Debug.Log("BuyProductID:FAIL.Notpurchasingproduct,eitherisnotfoundorisnotavailableforpurchase");
    }
    }
    //Otherwise...
    else
    {
    //...reportthefactPurchasinghasnotsucceededinitializingyet.Considerwaitinglongeror
    //retryinginitiailization.
    Debug.Log("BuyProductIDFAIL.Notinitialized.");
    }
    }


    //Restorepurchasespreviouslymadebythiscustomer.Someplatformsautomaticallyrestorepurchases,likeGoogle.
    //ApplecurrentlyrequiresexplicitpurchaserestorationforIAP,conditionallydisplayingapasswordprompt.
    public void RestorePurchases()
    {
    //IfPurchasinghasnotyetbeensetup...
    if (!IsInitialized())
    {
    //...reportthesituationandstoprestoring.Considereitherwaitinglonger,orretryinginitialization.
    Debug.Log("RestorePurchasesFAIL.Notinitialized.");
    return;
    }

    //IfwearerunningonanAppledevice...
    if (Application.platform == RuntimePlatform.IPhonePlayer ||
    Application.platform == RuntimePlatform.OSXPlayer)
    {
    //...beginrestoring purchases
    Debug.Log("RestorePurchasesstarted...");

    //FetchtheApplestore-specificsubsystem.
    var apple = m_StoreExtensionProvider.GetExtension<IAppleExtensions>();
    //Begintheasynchronousprocessofrestoringpurchases.Expectaconfirmationresponsein
    //theAction<bool>below,andProcessPurchaseiftherearepreviouslypurchasedproductstorestore.
    apple.RestoreTransactions((result) => {
    //Thefirstphaseofrestoration.IfnomoreresponsesarereceivedonProcessPurchasethen
    //nopurchasesareavailabletoberestored.
    Debug.Log("RestorePurchasescontinuing:" + result + ".Ifnofurthermessages,nopurchasesavailabletorestore.");
    });
    }
    //Otherwise...
    else
    {
    //WearenotrunningonanAppledevice.Noworkisnecessarytorestorepurchases.
    Debug.Log("RestorePurchasesFAIL.Notsupportedonthisplatform.Current=" + Application.platform);
    }
    }


    //
    //--- IStoreListener
    //

    public void OnInitialized(IStoreController controller, IExtensionProvider extensions)
    {
    //Purchasinghassucceededinitializing.CollectourPurchasingreferences.
    Debug.Log("OnInitialized:pASS");

    //OverallPurchasingsystem,configuredwithproductsforthisapplication.
    m_StoreController = controller;
    //Storespecificsubsystem,foraccessingdevice-specificstorefeatures.
    m_StoreExtensionProvider = extensions;
    }


    public void OnInitializeFailed(InitializationFailureReason error)
    {
    //Purchasingset-uphasnotsucceeded.Checkerrorforreason.Considersharingthisreasonwiththeuser.
    Debug.Log("OnInitializeFailedInitializationFailureReason:" + error);
    }


    public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args)
    {
    if (String.Equals(args.purchasedProduct.definition.id, PRODUCT_1000_GOLD, StringComparison.Ordinal))
    {
    Debug.Log("Youbought1000Gold!");
    PlayerPrefs.SetInt("Coins", PlayerPrefs.GetInt("Coins") + 1000);
    displayCoins = GameObject.Find("storeCanvas").GetComponent<DisplayAmountOfCoins>();
    displayCoins.SetCoin();
    }

    else if (String.Equals(args.purchasedProduct.definition.id, PRODUCT_2000_GOLD, StringComparison.Ordinal))
    {
    Debug.Log("Youbought2000Gold!");
    PlayerPrefs.SetInt("Coins", PlayerPrefs.GetInt("Coins") + 2000);
    displayCoins = GameObject.Find("storeCanvas").GetComponent<DisplayAmountOfCoins>();
    displayCoins.SetCoin();
    }

    else if (String.Equals(args.purchasedProduct.definition.id, PRODUCT_4000_GOLD, StringComparison.Ordinal))
    {
    Debug.Log("Youbought4000Gold!");
    PlayerPrefs.SetInt("Coins", PlayerPrefs.GetInt("Coins") + 4000);
    displayCoins = GameObject.Find("storeCanvas").GetComponent<DisplayAmountOfCoins>();
    displayCoins.SetCoin();
    }

    else if (String.Equals(args.purchasedProduct.definition.id, PRODUCT_8000_GOLD, StringComparison.Ordinal))
    {
    Debug.Log("Youbought8000Gold!");
    PlayerPrefs.SetInt("Coins", PlayerPrefs.GetInt("Coins") + 8000);
    displayCoins = GameObject.Find("storeCanvas").GetComponent<DisplayAmountOfCoins>();
    displayCoins.SetCoin();
    }

    //Or...anunknownproducthasbeenpurchasedbythisuser.Fillinadditionalproductshere....
    else
    {
    Debug.Log(string.Format("ProcessPurchase:FAIL.Unrecognizedproduct:'{0}'", args.purchasedProduct.definition.id));
    }

    //Returnaflagindicatingwhetherthisproducthascompletelybeenreceived,oriftheapplicationneeds
    //toberemindedofthispurchaseatnextapplaunch.UsePurchaseProcessingResult.Pendingwhenstill
    //savingpurchasedproductstothecloud,andwhenthatsaveisdelayed.
    return PurchaseProcessingResult.Complete;
    }


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

    Attached Files:

  2. wjhbrendan

    wjhbrendan

    Joined:
    Jul 17, 2016
    Posts:
    15
    Bump still trying to fix it...
     
  3. Defero

    Defero

    Joined:
    Jul 9, 2012
    Posts:
    200
  4. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,146
  5. recon0303

    recon0303

    Joined:
    Apr 20, 2014
    Posts:
    1,634