Untitled
unknown
plain_text
10 months ago
3.6 kB
8
Indexable
public async Task<bool> PlayFabPurchaseItemByID(string itemID)
{
if (!IsInitialized) throw new Exception("IAP Service is not initialized!");
Debug.Log("Player buying product " + itemID);
lastAPICallResult = new();
if (string.IsNullOrEmpty(purchaseIdempotencyId))
{
purchaseIdempotencyId = Guid.NewGuid().ToString();
}
Debug.Log("Fetching store item...");
GetItemRequest getSpringStoreRequest = new GetItemRequest()
{
AlternateId = new CatalogAlternateId()
{
Type = "FriendlyId",
Value = "SpringStorePF"
},
};
GetItemResponse getStoreResponse = null;
try
{
getStoreResponse = await economyAPI.GetItemAsync(getSpringStoreRequest); // ✅ Keep this on Unity's main thread
}
catch (Exception ex)
{
Debug.LogError($"GetItemAsync failed: {ex.Message}");
return false;
}
if (getStoreResponse == null || string.IsNullOrEmpty(getStoreResponse?.Item?.Id))
{
Debug.LogError("GetItemAsync response is null or invalid.");
lastAPICallResult.error = "Unable to contact the store. Check your internet connection and try again in a few minutes.";
return false;
}
Debug.Log($"Store item fetched successfully: {JsonUtility.ToJson(getStoreResponse)}");
if (!StorefrontCatalog.ContainsKey(itemID) || StorefrontCatalog[itemID].PriceOptions.Prices.Count == 0)
{
Debug.LogError($"Item {itemID} not found in StorefrontCatalog.");
return false;
}
CatalogPriceAmount price = StorefrontCatalog[itemID].PriceOptions.Prices.FirstOrDefault().Amounts.FirstOrDefault();
Debug.Log($"Price details: Amount={price.Amount}, ItemId={price.ItemId}");
PurchaseInventoryItemsRequest purchaseInventoryItemsRequest = new PurchaseInventoryItemsRequest()
{
Amount = 1,
Item = new InventoryItemReference()
{
Id = itemID
},
PriceAmounts = new List<PurchasePriceAmount>
{
new PurchasePriceAmount()
{
Amount = price.Amount,
ItemId = price.ItemId
}
},
IdempotencyId = purchaseIdempotencyId,
StoreId = getStoreResponse.Item.Id
};
Debug.Log("Attempting purchase...");
PurchaseInventoryItemsResponse purchaseInventoryItemsResponse = null;
try
{
purchaseInventoryItemsResponse = await economyAPI.PurchaseInventoryItemsAsync(purchaseInventoryItemsRequest); // ✅ Keep this on Unity's main thread
}
catch (Exception ex)
{
Debug.LogError($"PurchaseInventoryItemsAsync failed: {ex.Message}");
return false;
}
if (purchaseInventoryItemsResponse == null || purchaseInventoryItemsResponse?.TransactionIds.Count < 1)
{
Debug.LogError("Purchase failed. No transaction ID returned.");
lastAPICallResult.error = "Unable to purchase. Try again in a few minutes.";
return false;
}
Debug.Log($"Purchase successful! Transaction ID: {purchaseInventoryItemsResponse.TransactionIds[0]}");
purchaseIdempotencyId = "";
lastAPICallResult.message = "Purchasing!";
// Execute Unity-specific code on the main thread
MainThreadDispatcher.Enqueue(() =>
{
Debug.Log("Purchase successful!");
// Add any other Unity-specific code here
});
return true;
}Editor is loading...
Leave a Comment