question

contact-18 avatar image
contact-18 asked

Azure Functions Paramters and AddInventoryItems

Hello I have just started to work with Azur Functions.

Currently I have the following problem and it would be great if someone here could help me.

When I call my function, I cannot read out the parameters:

 LogPlayFab: Request: {
     "FunctionName": "HelloWorld",
     "FunctionParameter":
     {
         "name": "Sebi"
     },
     "GeneratePlayStreamEvent": true
 }

 LogPlayFab: Response : {"code":200,"status":"OK","data":{"ExecutionTimeMilliseconds":1022,"FunctionName":"HelloWorld","FunctionResult":"This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."}}

 Function: 
     public static class HelloWorld
     {
         [FunctionName("HelloWorld")]
         public static async Task<dynamic> Run(
             [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
             ILogger log)
         {
             log.LogInformation("C# HTTP trigger function processed a request.");
    
             string name = req.Query["name"];
    
             string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
             dynamic data = JsonConvert.DeserializeObject(requestBody);
             name = name ?? data?.name;
    
             string responseMessage = string.IsNullOrEmpty(name)
                 ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
                 : $"Hello, {name}. This HTTP triggered function executed successfully.";
    
             return new OkObjectResult(responseMessage);
         }
     }

What am I doing wrong here with the request?


I don't quite understand how to call AddInventoryItems for a player in azure. Does anyone have an example for me?

 PlayFab.EconomyModels.AddInventoryItemsRequest
 PlayFab.EconomyModels.AddInventoryItemsResponse
 PlayFab.EconomyModels.AddInventoryItemsOperation

Thank you in advance.

CloudScriptPlayer Inventory
10 |1200

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

Xiao Zha avatar image
Xiao Zha answered

You need to deserialize the req before you can use the FunctionParameter. And Here is a code example about calling AddInventoryItem API in AzureFunction you can refer to:

 public static class Function1
     {
         [FunctionName("Itemtest")]
         public static async Task Run(
             [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
             ILogger log)
         {
             FunctionExecutionContext<dynamic> context = JsonConvert.DeserializeObject<FunctionExecutionContext<dynamic>>(await req.ReadAsStringAsync());
    
             //Get the FunctionParameter Value
             var itemFriendlyName =context.FunctionArgument["FriendlyName"];
    
             var apiSettings = new PlayFabApiSettings
             {
                 TitleId = Environment.GetEnvironmentVariable("PLAYFAB_TITLE_ID", EnvironmentVariableTarget.Process),
                 DeveloperSecretKey = Environment.GetEnvironmentVariable("PLAYFAB_DEV_SECRET_KEY", EnvironmentVariableTarget.Process)
             };
              
             //Normally, it is secure to only call AddInventoryItem with Title Entity Token. 
             var titleAuthContext = new PlayFabAuthenticationContext();
             titleAuthContext.EntityToken = context.TitleAuthenticationContext.EntityToken;
    
             PlayFabEconomyInstanceAPI api = new PlayFabEconomyInstanceAPI(apiSettings,titleAuthContext);
    
             var result = await api.AddInventoryItemsAsync(new PlayFab.EconomyModels.AddInventoryItemsRequest
             {
                 Item = new PlayFab.EconomyModels.InventoryItemReference
                 {                    
                     AlternateId=new PlayFab.EconomyModels.AlternateId
                     {
                         Type= "FriendlyId",
                         Value= itemFriendlyName
                     } 
                 },
                 Amount = 3,
                 Entity = new PlayFab.EconomyModels.EntityKey{
                     Id = context.CallerEntityProfile.Entity.Id,
                     Type=context.CallerEntityProfile.Entity.Type
                 }
             }); ;
         }
     }
3 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.

contact-18 avatar image contact-18 commented ·

hey thanks you helped me a lot. i can now access the parameters.

I get the following error with the AddInventoryItems example:

 Response : {"code":400,"status":"BadRequest","error":"CloudScriptAzureFunctionsHTTPRequestError","errorCode":1473,"errorMessage":"Invocation of cloud script function CMDAzureGetPlayerInventory failed with HTTP status InternalServerError and response body "}

I think the problem lies somewhere in this area:

 var result = await api.AddInventoryItemsAsync(new PlayFab.EconomyModels.AddInventoryItemsRequest
  {
      Item = new PlayFab.EconomyModels.InventoryItemReference
      {                    
          AlternateId=new PlayFab.EconomyModels.AlternateId
          {
              Type= "FriendlyId",
              Value= itemFriendlyName
          } 
      },
      Amount = 3,
      Entity = new PlayFab.EconomyModels.EntityKey{
          Id = context.CallerEntityProfile.Entity.Id,
          Type=context.CallerEntityProfile.Entity.Type
      }
  });
0 Likes 0 ·
Xiao Zha avatar image Xiao Zha contact-18 commented ·

The code works fine in my test. Could you provide your modified Azure Function code and the client code that calls the function? And please also provide the log stream that shows on the Azure portal window when you test your Azure Function locally.

0 Likes 0 ·
contact-18 avatar image contact-18 Xiao Zha commented ·

i posted the logs. however, not directly in response to your answer. sorry.

0 Likes 0 ·
contact-18 avatar image
contact-18 answered

Game Code:

5631-image.png

Azure Function:

 using System;
 using System.IO;
 using System.Threading.Tasks;
 using Microsoft.AspNetCore.Mvc;
 using Microsoft.Azure.WebJobs;
 using Microsoft.Azure.WebJobs.Extensions.Http;
 using Microsoft.AspNetCore.Http;
 using Microsoft.Extensions.Logging;
 using Newtonsoft.Json;
 using PlayFab.EconomyModels;
 using PlayFab.ServerModels;
 using PlayFab.Json;
 using System.Collections.Generic;
 using PlayFab.DataModels;
 using System.Net.Http;
 using System.Net.Http.Headers;
 using PlayFab.CloudScriptModels;
 using PlayFab;
    
 namespace UsurpatorCompany.UsurpatorFunction
 {public static class CMDAzureGetPlayerInventory
      {
          [FunctionName("CMDAzureGetPlayerInventory")]
          public static async Task Run(
              [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
              ILogger log)
          {
              FunctionExecutionContext<dynamic> context = JsonConvert.DeserializeObject<FunctionExecutionContext<dynamic>>(await req.ReadAsStringAsync());
        
              //Get the FunctionParameter Value
              var itemFriendlyName =context.FunctionArgument["FriendlyName"];
              var apiSettings = new PlayFabApiSettings
              {
                  TitleId = Environment.GetEnvironmentVariable("TitleId -> 90TEST", EnvironmentVariableTarget.Process),
                  DeveloperSecretKey = Environment.GetEnvironmentVariable("DeveloperSecretKey", EnvironmentVariableTarget.Process)
              };
                  
              //Normally, it is secure to only call AddInventoryItem with Title Entity Token. 
              var titleAuthContext = new PlayFabAuthenticationContext();
              titleAuthContext.EntityToken = context.TitleAuthenticationContext.EntityToken;
        
             PlayFabEconomyInstanceAPI api = new PlayFabEconomyInstanceAPI(apiSettings,titleAuthContext);
                
             var result = await api.AddInventoryItemsAsync(new PlayFab.EconomyModels.AddInventoryItemsRequest
             {
                 Item = new PlayFab.EconomyModels.InventoryItemReference
                 {                    
                     AlternateId=new PlayFab.EconomyModels.AlternateId
                     {
                         Type= "FriendlyId",
                         Value= itemFriendlyName
                     } 
                 },
                 Amount = 3,
                 Entity = new PlayFab.EconomyModels.EntityKey{
                     Id = context.CallerEntityProfile.Entity.Id,
                     Type=context.CallerEntityProfile.Entity.Type
                 }
             });
          }
      }
 }

Stream Log:

 2023-03-07T08:48:29.977 [Information] Executing 'CMDAzureGetPlayerInventory' (Reason='This function was programmatically called via the host APIs.', Id=5312cc63-2093-43a2-8b40-83b52fec9424)
 2023-03-07T08:48:30.007 [Error] Executed 'CMDAzureGetPlayerInventory' (Failed, Id=5312cc63-2093-43a2-8b40-83b52fec9424, Duration=2ms)
 You must set your titleId before making an api call
 2023-03-07T08:49:40  No new trace in the past 1 min(s).
 2023-03-07T08:50:40  No new trace in the past 2

Request:

 LogPlayFab: Request: {
     "FunctionName": "CMDAzureGetPlayerInventory",
     "FunctionParameter":
     {
         "FriendlyName": "500007"
     },
     "GeneratePlayStreamEvent": true
 }

Response:

 LogPlayFab: Response : {"code":400,"status":"BadRequest","error":"CloudScriptAzureFunctionsHTTPRequestError","errorCode":1473,"errorMessage":"Invocation of cloud script function CMDAzureGetPlayerInventory failed with HTTP status InternalServerError and response body "}

image.png (141.0 KiB)
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.

Xiao Zha avatar image Xiao Zha commented ·

The Stream log indicates that you did not set the TitleId correctly. If you are debugging your function locally, you can refer to Local debugging for Cloudscript using Azure Functions - PlayFab | Microsoft Learn to correctly set your TitleId and SecretKey. If you have published your function, you can refer to this post: Where to set DeveloperSecretKey for Azure PlayFabServerAPI calls - Playfab Community to set your TitleId and SecretKey correctly. Also, the string parameter in the Environment.GetEnvironmentVariable method should be consistent with the string names you set for TitleId and SecretKey so that you can get the TitleId and SecretKey successfully.

0 Likes 0 ·
Xiao Zha avatar image Xiao Zha commented ·

Since the DeveloperSecretKey in your post code is private information, we have deleted it for you. And we recommend that you can disable the previous DeveloperSecretkey and replace it with a new one to prevent your Title from being hacked.

0 Likes 0 ·
Kirk avatar image
Kirk answered

I'm getting a 400 error when attempting to use PlayFabEconomyInstanceAPI api = new PlayFabEconomyInstanceAPI and calling AddInventoryItems from my AF.

Q) Is this the proper way to call EconomyV2 from Azure Functions?

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.