question

shawnryanbruno avatar image
shawnryanbruno asked

Cannot AddInventoryItems via azure function

It seems this script is running correctly through the playstream when the player account is created: however the currency is not being added/updated at all.

Any suggestions?

 namespace My.Function
 {
     public static class FSKAzureServerGrantCurrencyToPlayer
     {
         [FunctionName("FSKAzureServerGrantCurrencyToPlayer")]
         public static async Task<IActionResult> Run(
             [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
             ILogger log)
         {
             try
             {
                 // Parse the request body to get 'result'
                 string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
                 dynamic data = JsonConvert.DeserializeObject(requestBody);
                 string entityId = data?.EntityId;
                 string entityType = data?.EntityType;
    
                 // Validate entityId and entityType
                 if (string.IsNullOrEmpty(entityId) || string.IsNullOrEmpty(entityType))
                 {
                     return new BadRequestObjectResult("EntityId and EntityType are required.");
                 }
    
                 // Initialize PlayFab SDK
                 PlayFabSettings.staticSettings.TitleId = "E4875";
                 PlayFabSettings.staticSettings.DeveloperSecretKey = "REDACTED";
    
                 // Create an EntityKey for the entity
                 EntityKey entityKey = new EntityKey { Id = entityId, Type = entityType };
    
                 // Create an AddInventoryItemsRequest and call the PlayFab Economy API to add inventory items asynchronously
                 var addItemsRequest = new AddInventoryItemsRequest
                 {
                     Amount = 1000,
                     Entity = entityKey,
                     Item = new InventoryItemReference
                     {
                         Id = "269f32a7-9bc7-41a5-b4f9-6c805e0a27c5",
                     }
                 };
    
                 // Call PlayFab Economy API to add inventory items asynchronously
                 PlayFabResult<AddInventoryItemsResponse> response = await PlayFabEconomyAPI.AddInventoryItemsAsync(addItemsRequest);
    
                 // Handle the response here, e.g., log the IdempotencyId
                 if (response.Result != null)
                 {
                     log.LogInformation($"IdempotencyId: {response.Result.IdempotencyId}");
                 }
    
                 // Return an OkObjectResult or any appropriate response
                 return new OkObjectResult("Inventory items added successfully.");
             }
             catch (Exception ex)
             {
                 // Handle any exceptions, e.g., log the error
                 log.LogError(ex, "Error adding inventory items.");
                 return new StatusCodeResult(StatusCodes.Status500InternalServerError);
             }
         }
     }
 }
CloudScript
10 |1200

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

Neils Shi avatar image
Neils Shi answered

PlayFab executes cloud scripts through several mechanisms, and different mechanisms require different contexts. In your case, it looks like you use the player_added_title event to trigger the Azure Function in Rules, so, you need to use “var context=JsonConvert.DeserializeObject(await req.ReadAsStringAsync());” And then you can obtain player’s MasterPlayerAccountId via it. For more info, you can refer to https://learn.microsoft.com/en-us/gaming/playfab/features/automation/cloudscript-af/cloudscript-af-context#use-the-context-model-when-executing-in-the-context-of-a-player . Also, since you want to use the API AddInventoryItems to grant the Economy items to players, since this API needs title player account id, so, you need to use GetTitlePlayersFromMasterPlayerAccountIds API to retrieve the entity of the title player account from the MasterPlayerAccountId. In addition, if you are not familiar with Azure Function, you can refer to the example code provided in our documentation : https://learn.microsoft.com/en-us/gaming/playfab/features/automation/cloudscript-af/quickstart#playfab-cloudscript-context-variables-and-server-sdks- .

2 comments
10 |1200

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

shawnryanbruno avatar image shawnryanbruno commented ·

Is there not a way to do this within cloudscript and NOT azure functions? I am so stressed having to learn a whole new concept of this backend, and its slowing down our production. Thanks. We will need to add currency in the economy v2. Thanks.

0 Likes 0 ·
shawnryanbruno avatar image shawnryanbruno commented ·

I am absolutely losing my mind with this system. I understand and appreciate you directing me to samples for help, but I cannot get it working. In fact, this is going to push me away from Playfab, because quite frankly, I am not in the mood to learn a whole new backend system with HTTP requests. I am spending countless hours trying to get this to work. Can you point me in the right direction besides quoting material from your documentation that is really NOT helping.

0 Likes 0 ·
shawnryanbruno avatar image
shawnryanbruno answered

Is there not a way to do this within cloudscript and NOT azure functions? I am so stressed having to learn a whole new concept of this backend, and its slowing down our production. Thanks. We will need to add currency in the economy v2. Thanks.

10 |1200

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

shawnryanbruno avatar image
shawnryanbruno answered

I figured out how to do this in cloudscript, instead of azure functions. If anyone is interested. This will add a v2 currency to the player when they create a player account. Make sure you run it as a task in the playstream.

     handlers.AddCurrencyWhenPlayerCreated = function (args, context) {
         try {
             // Add inventory items to the player
             var entity = server.GetUserAccountInfo({ PlayFabId: currentPlayerId }).UserInfo.TitleInfo.TitlePlayerAccount;
             var addItemRequest = {
                 Amount: 1000, // Specify the amount of currency to add
                 //Entity: server.GetUserAccountInfo({ PlayFabId: currentPlayerId }).UserInfo.TitleInfo.TitlePlayerAccount,
                 Entity: entity,
                 Item: {
                     Id: "269f32a7-9bc7-41a5-b4f9-6c805e0a27c5" // Specify the item ID to add
                 }
             };
        
             var addItemResult = economy.AddInventoryItems(addItemRequest);
             log.info("Currency added successfully.");
             return { result: "Success" };
         } catch (ex) {
             log.error("Error adding currency: " + ex.message);
             return { error: "Error adding currency", details: ex };
         }
     };
10 |1200

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

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.