question

ktechgames avatar image
ktechgames asked

How Can I get Catalog item by index or item Id ?

Hi i am trying to integrate Unity IAP via Playfab I follow this guid line :

https://api.playfab.com/docs/tutorials/landing-commerce/getting-started-unity-iap-android

evry thing is ok but now i want to purcahse item by my own purcahse button instead of given GUI buttion. I am new So i can't find . please help me.

here is my store screen shot:

here is code :

usingPlayFab;
usingPlayFab.ClientModels;
usingPlayFab.Json;
usingSystem;
usingSystem.Collections.Generic;
usingUnityEngine;
usingUnityEngine.Purchasing;

publicclassUnityIAP_PFB:MonoBehaviour,IStoreListener{

privateList<CatalogItem>Catalog;

// The Unity Purchasing system
privatestaticIStoreControllerm_StoreController;

// Bootstrap the whole thing
publicvoidStart()
{
// Make PlayFab log in
Login();

}

//public void OnGUI()
//{
// // This line just scales the UI up for high-res devices
// // Comment it out if you find the UI too large.
// GUI.matrix = Matrix4x4.TRS(new Vector3(0, 0, 0), Quaternion.identity, new Vector3(3, 3, 3));

// // if we are not initialized, only draw a message 
// if (!IsInitialized)
// {
// GUILayout.Label("Initializing IAP and logging in...");
// return;
// }

// // Draw menu to purchase items
// foreach (var item in Catalog)
// {
// if (GUILayout.Button("Buy " + item.DisplayName))
// {
// // On button click buy a product
// BuyProductID(item.ItemId);
// }
// }
//}

// This is invoked manually on Start to initiate login ops
privatevoidLogin()
{
// Login with Android ID
PlayFabClientAPI.LoginWithAndroidDeviceID(newLoginWithAndroidDeviceIDRequest()
{
CreateAccount=true,
AndroidDeviceId=SystemInfo.deviceUniqueIdentifier
},result=>{
Debug.Log("Logged in");
// Refresh available items 
RefreshIAPItems();
},error=>Debug.LogError(error.GenerateErrorReport()));
}

privatevoidRefreshIAPItems()
{
PlayFabClientAPI.GetCatalogItems(newGetCatalogItemsRequest(),result=>{
Catalog=result.Catalog;

// Make UnityIAP initialize
InitializePurchasing();
},error=>Debug.LogError(error.GenerateErrorReport()));
}

// This is invoked manually on Start to initialize UnityIAP
publicvoidInitializePurchasing()
{
// If IAP is already initialized, return gently
if(IsInitialized)return;

// Create a builder for IAP service
varbuilder=ConfigurationBuilder.Instance(StandardPurchasingModule.Instance(AppStore.GooglePlay));

// Register each item from the catalog
foreach(variteminCatalog)
{
builder.AddProduct(item.ItemId,ProductType.Consumable);
}

// Trigger IAP service initialization
UnityPurchasing.Initialize(this,builder);
}

// We are initialized when StoreController and Extensions are set and we are logged in
publicboolIsInitialized
{
get
{
returnm_StoreController!=null&&Catalog!=null;
}
}

// This is automatically invoked automatically when IAP service is initialized
publicvoidOnInitialized(IStoreControllercontroller,IExtensionProviderextensions)
{
m_StoreController=controller;
}

// This is automatically invoked automatically when IAP service failed to initialized
publicvoidOnInitializeFailed(InitializationFailureReasonerror)
{
Debug.Log("OnInitializeFailed InitializationFailureReason:"+error);
}

// This is automatically invoked automatically when purchase failed
publicvoidOnPurchaseFailed(Productproduct,PurchaseFailureReasonfailureReason)
{
Debug.Log(string.Format("OnPurchaseFailed: FAIL. Product: '{0}', PurchaseFailureReason: {1}",product.definition.storeSpecificId,failureReason));
}

// This is invoked automatically when succesful purchase is ready to be processed
publicPurchaseProcessingResultProcessPurchase(PurchaseEventArgse)
{
// NOTE: this code does not account for purchases that were pending and are
// delivered on application start.
// Production code should account for such case:
// More: https://docs.unity3d.com/ScriptReference/Purchasing.PurchaseProcessingResult.Pending.html

if(!IsInitialized)
{
returnPurchaseProcessingResult.Complete;
}

// Test edge case where product is unknown
if(e.purchasedProduct==null)
{
Debug.LogWarning("Attempted to process purchasewith unknown product. Ignoring");
returnPurchaseProcessingResult.Complete;
}

// Test edge case where purchase has no receipt
if(string.IsNullOrEmpty(e.purchasedProduct.receipt))
{
Debug.LogWarning("Attempted to process purchase with no receipt: ignoring");
returnPurchaseProcessingResult.Complete;
}

Debug.Log("Processing transaction: "+e.purchasedProduct.transactionID);

// Deserialize receipt
vargoogleReceipt=GooglePurchase.FromJson(e.purchasedProduct.receipt);

// Invoke receipt validation
// This will not only validate a receipt, but will also grant player corresponding items
// only if receipt is valid.
PlayFabClientAPI.ValidateGooglePlayPurchase(newValidateGooglePlayPurchaseRequest()
{
// Pass in currency code in ISO format
CurrencyCode=e.purchasedProduct.metadata.isoCurrencyCode,
// Convert and set Purchase price
PurchasePrice=(uint)(e.purchasedProduct.metadata.localizedPrice*100),
// Pass in the receipt
ReceiptJson=googleReceipt.PayloadData.json,
// Pass in the signature
Signature=googleReceipt.PayloadData.signature
},result=>Debug.Log("Validation successful!"),
error=>Debug.Log("Validation failed: "+error.GenerateErrorReport())
);

returnPurchaseProcessingResult.Complete;
}

// This is invvoked manually to initiate purchase
voidBuyProductID(stringproductId)
{
// If IAP service has not been initialized, fail hard
if(!IsInitialized)thrownewException("IAP Service is not initialized!");

// Pass in the product id to initiate purchase
m_StoreController.InitiatePurchase(productId);
}
}

// The following classes are used to deserialize JSON results provided by IAP Service
// Please, note that Json fields are case-sensetive and should remain fields to support Unity Deserialization via JsonUtilities
publicclassJsonData2
{
// Json Fields, ! Case-sensetive

publicstringorderId;
publicstringpackageName;
publicstringproductId;
publiclongpurchaseTime;
publicintpurchaseState;
publicstringpurchaseToken;
}

publicclassPayloadData
{
publicJsonData2JsonData;

// Json Fields, ! Case-sensetive
publicstringsignature;
publicstringjson;

publicstaticPayloadDataFromJson(stringjson)
{
varpayload=JsonUtility.FromJson<PayloadData>(json);
payload.JsonData=JsonUtility.FromJson<JsonData2>(payload.json);
returnpayload;
}
}

publicclassGooglePurchase
{
publicPayloadDataPayloadData;

// Json Fields, ! Case-sensetive
publicstringStore;
publicstringTransactionID;
publicstringPayload;

publicstaticGooglePurchaseFromJson(stringjson)
{
varpurchase=JsonUtility.FromJson<GooglePurchase>(json);
purchase.PayloadData=PayloadData.FromJson(purchase.Payload);
returnpurchase;
}
}

i want to access item by Clicking Button : Buy 1, Buy 2,Buy 3,Buy 4,Buy 5

please need help thanks in advance

10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

JayZuo avatar image
JayZuo answered

That will depends on how you create your buttons. If you are creating these buttons with hard coding, then you will also hard code the "ItemId" in each button's click event. For example, you have a "Buy1Button" for 1000 coins, then you will hard code like:

Buy1Button.onClick.AddListener(() =>
{
    BuyProductID("pool_1000_coins");
});<br>

And If you are generating your UI buttons dynamically, you will use some code like the tutorial. For example

foreach (var item in Catalog)
{
    GameObject button = (GameObject)Instantiate(buttonPrefab);
    button.transform.SetParent(panelToAttachButtonsTo.transform);
    /*
     ...
     Other code for setting UI
     ...
    */
    button.GetComponent<Button>().onClick.AddListener(() =>
    {
        BuyProductID(item.ItemId);
    });
}

Generally, this will be a Unity GUI problem, if you are not familiar with Unity's UI system, you can refer to https://docs.unity3d.com/Manual/UISystem.html. Also you can seek help from Unity community.

10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Andy avatar image
Andy answered

I'm not sure what you're asking. Do you want to avoid the Android purchase GUI? That's not possible for GooglePlay store purchases.

1 comment
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

ktechgames avatar image ktechgames commented ·
in this code i want some change. this code run and make own button on gui right. but i want my own canvas button to purchase different stuff i have 5 buttons which i already mention so how every button call different item on click..?



public void OnGUI()
{
// This line just scales the UI up for high-res devices
// Comment it out if you find the UI too large.
GUI.matrix = Matrix4x4.TRS(new Vector3(0, 0, 0), Quaternion.identity, new Vector3(3, 3, 3));

// if we are not initialized, only draw a message
if (!IsInitialized)
{
GUILayout.Label("Initializing IAP and logging in...");
return;
}

// Draw menu to purchase items
foreach (var item in Catalog)
{
if (GUILayout.Button("Buy " + item.DisplayName))
{
// On button click buy a product
BuyProductID(item.ItemId);
}
}
}
0 Likes 0 ·

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.