Hi , I tried modifiying the existing project and do. But there is some problem now. When you click on the cancel ads button in my game , the menu to purchase though it appears which asks for the various payments, even if you dont pay anything and click the the back button while purchasing the no ads payment is successful. Here is the code which I have written. Would you mind saying what wrong am I doing here?
using System;
using System.Collections.Generic;
using System.Collections;
using UnityEngine;
using UnityEngine.Purchasing;
using UnityEngine.UI;
using UnityEngine.Analytics;
using UnityEngine.Purchasing.Security;
using UnityEngine.SceneManagement;
public class IAPManager_New : 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;
private IAppleExtensions m_AppleExtensions;
private IGooglePlayStoreExtensions m_GoogleExtensions;
[SerializeField] private Text outputMessage;
public static string CancelAds = "com.chethan.flappybirdsuniverse.cancelads";
private ConfigurationBuilder builder;
[SerializeField] GameObject NoAdsButton;
[SerializeField] GameObject PaidButton;
[SerializeField] private GameObject MessageWindow;
[SerializeField] private float faderTimeforWindow = 0.3f;//see inspector for final values
private Boolean return_complete = true;
// Start is called before the first frame update
void Start()
{
// If we haven't set up the Unity Purchasing reference
if (m_StoreController == null)
{
// Begin to configure our connection to Purchasing
InitializePurchasing();
}
Debug.Log("In Start of IAP Manager new...");
Debug.Log("PlayerPrefs.GetInt(\"Ads\")..."+PlayerPrefs.GetInt("Ads"));
//PlayerPrefs.SetInt("Ads",(int)AdsStatus.NotPurchased);
if (PlayerPrefs.GetInt("Ads")==(int)AdsStatus.SuccessfullyPurchased)
{
Debug.Log("SuccessfullyPurchased executed...................");
NoAdsButton.SetActive(false);
PaidButton.SetActive(true);
}
if (PlayerPrefs.GetInt("Ads")==(int)AdsStatus.NotPurchased)
{
Debug.Log("Not purchased executed...................");
NoAdsButton.SetActive(true);
PaidButton.SetActive(false);
}
}
public void OnClickCancelAdsButton()
{
BuyProductID(CancelAds);
}
void BuyProductID(string productId)
{
if (IsInitialized())
{
UnityEngine.Purchasing.Product product = m_StoreController.products.WithID(productId);
if (product != null && product.availableToPurchase)
{
Debug.Log(string.Format("Purchasing product:" + product.definition.id.ToString()));
m_StoreController.InitiatePurchase(product);
PlayerPrefs.SetInt("Ads", (int)AdsStatus.SuccessfullyPurchased);
NoAdsButton.SetActive(false);
PaidButton.SetActive(true);
SceneManager.LoadScene("Menu");
}
else
{
MessageFormatter("Sorry Purchase Failed. Try again Later");
Debug.Log("BuyProductID: FAIL. Not purchasing product, either is not found or is not available for purchase");
PlayerPrefs.SetInt("Ads", (int)AdsStatus.NotPurchased);
NoAdsButton.SetActive(true);
PaidButton.SetActive(false);
}
}
else
{
MessageFormatter("Sorry Purchase Failed. Try again Later....");
Debug.Log("BuyProductID FAIL. Not initialized.");
PlayerPrefs.SetInt("Ads", (int)AdsStatus.NotPurchased);
NoAdsButton.SetActive(true);
PaidButton.SetActive(false);
}
}
private bool IsInitialized()
{
return m_StoreController != null && m_StoreExtensionProvider != null;
}
public void MyInitialize()
{
InitializePurchasing();
}
public void InitializePurchasing()
{
if (IsInitialized())
{
return;
}
builder = ConfigurationBuilder.Instance(StandardPurchasingModule.Instance());
builder.AddProduct(CancelAds, ProductType.NonConsumable);
// builder.AddProduct(MONTHLY, ProductType.Subscription);
// builder.AddProduct(YEARLY, ProductType.Subscription);
builder.Configure<IGooglePlayConfiguration>().SetObfuscatedAccountId("test1");
builder.Configure<IGooglePlayConfiguration>().SetDeferredPurchaseListener(OnDeferredPurchase);
Debug.Log("Starting Initialized...");
UnityPurchasing.Initialize(this, builder);
//ProductCatalog catalog = ProductCatalog.LoadDefaultCatalog();
//foreach (ProductCatalogItem product in catalog.allProducts)
// {
//MyDebug("Product = " + product.id);
//}
}
void OnDeferredPurchase(Product product)
{
Debug.Log($"Purchase of {product.definition.id} is deferred");
}
private void MessageFormatter(string Message)
{
outputMessage.text = "";//each time u call this function make sure the output is fresh to display
FadeStarterForMessageModal(MessageWindow);
string[] words = Message.Split(' ');
int count = 0;
foreach (string word in words)
{
count = count + 1;
if (count % 3 == 0)
outputMessage.text = outputMessage.text + " " + word + "\n";
else if (count > 15)//not more than 5 line for that message
break;
else
outputMessage.text = outputMessage.text + " " + word;
}
}
private void FadeStarterForMessageModal(GameObject Window)
{
SFXManager.PlaySound("button");
Window.SetActive(true);
LeanTween.scale(Window, Vector3.zero, 0f);//
LeanTween.scale(Window, new Vector3(1, 1, 1), faderTimeforWindow).
setOnComplete(() => Window.SetActive(true)).setIgnoreTimeScale(true);
}
// Update is called once per frame
void Update()
{
}
public void CompletePurchase()
{
if (test_product == null)
Debug.Log("Cannot complete purchase, product not initialized.");
else
{
m_StoreController.ConfirmPendingPurchase(test_product);
//FetchProducts();
Debug.Log("Completed purchase with " + test_product.definition.id.ToString());
}
}
#region IStoreListenerCallBackFunctions
public void OnInitialized(IStoreController controller, IExtensionProvider extensions)
{
Debug.Log("OnInitialized: PASS");
m_StoreController = controller;
m_StoreExtensionProvider = extensions;
m_AppleExtensions = extensions.GetExtension<IAppleExtensions>();
m_GoogleExtensions = extensions.GetExtension<IGooglePlayStoreExtensions>();
Dictionary<string, string> dict = m_AppleExtensions.GetIntroductoryPriceDictionary();
foreach (UnityEngine.Purchasing.Product item in controller.products.all)
{
if (item.receipt != null)
{
string intro_json = (dict == null || !dict.ContainsKey(item.definition.storeSpecificId)) ? null : dict[item.definition.storeSpecificId];
if (item.definition.type == ProductType.Subscription)
{
SubscriptionManager p = new SubscriptionManager(item, null);
SubscriptionInfo info = p.getSubscriptionInfo();
Debug.Log("SubInfo: " + info.getProductId().ToString());
Debug.Log("getExpireDate: " + info.getExpireDate().ToString());
Debug.Log("isSubscribed: " + info.isSubscribed().ToString());
}
}
}
}
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));
}
public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs purchaseEvent)
{
test_product = purchaseEvent.purchasedProduct;
//var validator = new CrossPlatformValidator(GooglePlayTangle.Data(), AppleTangle.Data(), Application.identifier);
// var result = validator.Validate(args.purchasedProduct.receipt);
// foreach (IPurchaseReceipt productReceipt in result)
// {
// MyDebug("Valid receipt for " + productReceipt.productID.ToString());
// }
//MyDebug("Validate = " + result.ToString());
Debug.Log("Receipt:" + test_product.receipt.ToString());
if (return_complete)
{
Debug.Log(string.Format("ProcessPurchase: Complete. Product:" + purchaseEvent.purchasedProduct.definition.id + " - " + test_product.transactionID.ToString()));
return PurchaseProcessingResult.Complete;
}
else
{
Debug.Log(string.Format("ProcessPurchase: Pending. Product:" + purchaseEvent.purchasedProduct.definition.id + " - " + test_product.transactionID.ToString()));
return PurchaseProcessingResult.Pending;
}
}
#endregion
}
I honestly dont understand the code , but I have done my best as to whatever I can do. under the line of the code
if (product != null && product.availableToPurchase)
whatever is under the if codition that part is getting executed.
Would you mind pointing me to some tutorial where without the codeless IAP button the In-App purchase is looked into. Majority of the tutorials use the codeless button, but I have used the normal button as you said not to use the codeless button.