Hi all,
I’m a noob coder so I’m hoping someone can help me setup two buttons, one that removes ads and one that restores the users non-consumable purchase. I followed @JeffDUnity3D thread regarding setting it up, but I’m still confused and would appreciate if someone can help set it up.
Here is the sample code Jeff gave:
using System;
using UnityEngine;
using UnityEngine.Purchasing;
using UnityEngine.UI;
using UnityEngine.Purchasing.Security;
using Unity.Services.Core;
using Unity.Services.Analytics;
using System.Collections.Generic;
public class MyIAPManager : MonoBehaviour, IStoreListener
{
private static IStoreController m_StoreController; // The Unity Purchasing system.
private static IExtensionProvider m_StoreExtensionProvider; // The store-specific Purchasing subsystems.
private static UnityEngine.Purchasing.Product test_product = null;
IGooglePlayStoreExtensions m_GooglePlayStoreExtensions;
public static string NO_ADS = "noads";
public Text myText;
private Boolean return_complete = true;
async void Start()
{
try
{
await UnityServices.InitializeAsync();
List<string> consentIdentifiers = await AnalyticsService.Instance.CheckForRequiredConsents();
}
catch (ConsentCheckException e)
{
MyDebug("Consent: :" + e.ToString()); // Something went wrong when checking the GeoIP, check the e.Reason and handle appropriately.
}
MyAction += myFunction;
}
public void InitializePurchasing()
{
if (IsInitialized())
{
return;
}
var builder = ConfigurationBuilder.Instance(StandardPurchasingModule.Instance());
builder.Configure<IGooglePlayConfiguration>().SetDeferredPurchaseListener(OnDeferredPurchase);
builder.Configure<IGooglePlayConfiguration>().SetQueryProductDetailsFailedListener(MyAction);
builder.AddProduct(NO_ADS, ProductType.NonConsumable);
UnityPurchasing.Initialize(this, builder);
}
private event Action<int> MyAction;
void myFunction(int myInt)
{
MyDebug("Listener = " + myInt.ToString());
}
private bool IsInitialized()
{
return m_StoreController != null && m_StoreExtensionProvider != null;
}
void OnDeferredPurchase(UnityEngine.Purchasing.Product product)
{
MyDebug($"Purchase of {product.definition.id} is deferred");
}
//public void BuySubscription()
//{
// BuyProductID(NO_ADS);
//}
public void BuyNoAds()
{
BuyProductID(NO_ADS);
}
public void CompletePurchase()
{
if (test_product == null)
MyDebug("Cannot complete purchase, product not initialized.");
else
{
m_StoreController.ConfirmPendingPurchase(test_product);
MyDebug("Completed purchase with " + test_product.transactionID.ToString());
}
}
public void ToggleComplete()
{
return_complete = !return_complete;
MyDebug("Complete = " + return_complete.ToString());
}
public void RestorePurchases()
{
m_StoreExtensionProvider.GetExtension<IAppleExtensions>().RestoreTransactions(result =>
{
if (result)
{
MyDebug("Restore purchases succeeded.");
Dictionary<string, object> parameters = new Dictionary<string, object>()
{
{ "restore_success", true },
};
AnalyticsService.Instance.CustomData("myRestore", parameters);
}
else
{
MyDebug("Restore purchases failed.");
Dictionary<string, object> parameters = new Dictionary<string, object>()
{
{ "restore_success", false },
};
AnalyticsService.Instance.CustomData("myRestore", parameters);
}
AnalyticsService.Instance.Flush();
});
}
void BuyProductID(string productId)
{
if (IsInitialized())
{
UnityEngine.Purchasing.Product product = m_StoreController.products.WithID(NO_ADS);
if (product != null && product.availableToPurchase)
{
MyDebug(string.Format("Purchasing product:" + product.definition.id.ToString()));
m_StoreController.InitiatePurchase(product);
}
else
{
MyDebug("BuyProductID: FAIL. Not purchasing product, either is not found or is not available for purchase");
}
}
else
{
MyDebug("BuyProductID FAIL. Not initialized.");
}
}
public void OnInitialized(IStoreController controller, IExtensionProvider extensions)
{
MyDebug("OnInitialized: PASS");
m_StoreController = controller;
m_StoreExtensionProvider = extensions;
m_GooglePlayStoreExtensions = extensions.GetExtension<IGooglePlayStoreExtensions>();
}
public void OnInitializeFailed(InitializationFailureReason error)
{
// Purchasing set-up has not succeeded. Check error for reason. Consider sharing this reason with the user.
MyDebug("OnInitializeFailed InitializationFailureReason:" + error);
}
public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args)
{
test_product = args.purchasedProduct;
//var validator = new CrossPlatformValidator(GooglePlayTangle.Data(), AppleTangle.Data(), Application.identifier);
//var result = validator.Validate(args.purchasedProduct.receipt);
//MyDebug("Validate = " + result.ToString());
if (m_GooglePlayStoreExtensions.IsPurchasedProductDeferred(test_product))
{
//The purchase is Deferred.
//Therefore, we do not unlock the content or complete the transaction.
//ProcessPurchase will be called again once the purchase is Purchased.
return PurchaseProcessingResult.Pending;
}
if (return_complete)
{
MyDebug(string.Format("ProcessPurchase: Complete. Product:" + args.purchasedProduct.definition.id + " - " + test_product.transactionID.ToString()));
return PurchaseProcessingResult.Complete;
}
else
{
MyDebug(string.Format("ProcessPurchase: Pending. Product:" + args.purchasedProduct.definition.id + " - " + test_product.transactionID.ToString()));
return PurchaseProcessingResult.Pending;
}
}
public void CheckNoAdsPurchase()
{
foreach (UnityEngine.Purchasing.Product item in m_StoreController.products.all)
{
if (String.Equals(item.definition.id, NO_ADS))
{
if (item.hasReceipt)
{
MyDebug("receipt for NO_ADS: " + item.receipt.ToString());
// Unlock content here
}
else
{
MyDebug("No receipt for NO_ADS: " + item.definition.id.ToString());
// This means that the user does NOT have a receipt, so we don't unlock the content
// Do your appropriate actions here
}
}
else
{
// This means that you don't have a product defined as "NO_ADS"
}
}
}
public void OnPurchaseFailed(UnityEngine.Purchasing.Product product, PurchaseFailureReason failureReason)
{
MyDebug(string.Format("OnPurchaseFailed: FAIL. Product: '{0}', PurchaseFailureReason: {1}", product.definition.storeSpecificId, failureReason));
}
public void ListPurchases()
{
foreach (UnityEngine.Purchasing.Product item in m_StoreController.products.all)
{
if (item.hasReceipt)
{
MyDebug("In list for " + item.receipt.ToString());
}
else
MyDebug("No receipt for " + item.definition.id.ToString());
}
}
private void MyDebug(string debug)
{
Debug.Log(debug);
myText.text += "\r\n" + debug;
}
}
Here is my ad code:
using UnityEngine;
using UnityEngine.Advertisements;
public class RewardedAdsButton : MonoBehaviour, IUnityAdsLoadListener, IUnityAdsShowListener
{
[SerializeField] string _androidAdUnitId = "Interstitial_Android";
[SerializeField] string _iOsAdUnitId = "Interstitial_iOS";
string _adUnitId;
void Awake()
{
// Get the Ad Unit ID for the current platform:
_adUnitId = (Application.platform == RuntimePlatform.IPhonePlayer)
? _iOsAdUnitId
: _androidAdUnitId;
}
// Load content to the Ad Unit:
public void LoadAd()
{
// IMPORTANT! Only load content AFTER initialization (in this example, initialization is handled in a different script).
Debug.Log("Loading Ad: ios " + _adUnitId);
Advertisement.Load("Interstitial_iOS", this);
}
// Show the loaded content in the Ad Unit:
public void ShowAd()
{
// Note that if the ad content wasn't previously loaded, this method will fail
Debug.Log("Showing Ad: ios " + _adUnitId);
Advertisement.Show("Interstitial_iOS", this);
Time.timeScale = 0f;
}
// Implement Load Listener and Show Listener interface methods:
public void OnUnityAdsAdLoaded(string adUnitId)
{
ShowAd();
}
public void OnUnityAdsFailedToLoad(string _adUnitId, UnityAdsLoadError error, string message)
{
Debug.Log($"Error loading Ad Unit: {_adUnitId} - {error.ToString()} - {message}");
// Optionally execute code if the Ad Unit fails to load, such as attempting to try again.
}
public void OnUnityAdsShowFailure(string _adUnitId, UnityAdsShowError error, string message)
{
Debug.Log($"Error showing Ad Unit {_adUnitId}: {error.ToString()} - {message}");
// Optionally execute code if the Ad Unit fails to show, such as loading another ad.
}
public void OnUnityAdsShowComplete(string _adUnitId, UnityAdsShowCompletionState showCompletionState)
{
Time.timeScale = 1f;
}
public void OnUnityAdsShowStart(string _adUnitId) { }
public void OnUnityAdsShowClick(string _adUnitId) { }
//public void OnUnityAdsShowComplete(string _adUnitId, UnityAdsShowCompletionState showCompletionState) { }
}
Here is my ad initializer:
using UnityEngine;
using UnityEngine.Advertisements;
public class AdsInitializer : MonoBehaviour, IUnityAdsInitializationListener, IUnityAdsLoadListener
{
[SerializeField] string _androidGameId;
[SerializeField] string _iOSGameId;
[SerializeField] bool _testMode = true;
private string _gameId;
string _adUnitId;
void Awake()
{
InitializeAds();
LoadAd();
}
public void InitializeAds()
{
#if UNITY_IOS
_gameId = _iOSGameId;
#elif UNITY_ANDROID
_gameId = _androidGameId;
#elif UNITY_EDITOR
_gameId = _androidGameId; //Only for testing the functionality in the Editor
#endif
if (!Advertisement.isInitialized && Advertisement.isSupported)
{
Advertisement.Initialize(_gameId, _testMode, this);
}
}
public void LoadAd()
{
// IMPORTANT! Only load content AFTER initialization (in this example, initialization is handled in a different script).
Debug.Log("Loading Ad: ios " + _adUnitId);
Advertisement.Load("Interstitial_iOS", this);
}
public void OnInitializationComplete()
{
Debug.Log("Unity Ads initialization complete.");
}
public void OnInitializationFailed(UnityAdsInitializationError error, string message)
{
Debug.Log($"Unity Ads Initialization Failed: {error.ToString()} - {message}");
}
public void OnUnityAdsAdLoaded(string placementId)
{
throw new System.NotImplementedException();
}
public void OnUnityAdsFailedToLoad(string placementId, UnityAdsLoadError error, string message)
{
throw new System.NotImplementedException();
}
}
All I’m hoping to accomplish is when someone buys the no ads IAP, it turns off my interstitial ads. And if a user restores the purchase, it’ll disable ads once purchase is restored. I don’t know how to initialize the IAP because when I press the button, it said initialize failed, but I also don’t know how or where to write the code that would turn the ads off if the person has purchased the product. I know it needs to check the receipt, but I just don’t know how to do any of that properly so that ads function for people that haven’t purchased, and are disabled for buyers. Also, please don’t point me to unity manuals or documentation. It’s like pointing me to a language I don’t speak. I’d appreciate someone that can actually write the code for me to try and give me guidance so I better understand.