question

anudeep avatar image
anudeep asked

Invocation of Cloud Script Function Failed

I have followed the documentation properly after few days of figuring out. Even calling the function through playstream events through rules fails and i get:

"ExecutionResult": {
        "ExecutionResult": {
            "Error": {
                "code": 400,
                "status": "BadRequest",
                "error": "CloudScriptAzureFunctionsHTTPRequestError",
                "errorCode": 1473,
                "errorMessage": "Invocation of cloud script function Premium Choices Reward failed with HTTP status InternalServerError and response body "
            },
            "Status": 400
        }

I am adding pics of my current Function.

using System;
using System.IO;
using System.Threading.Tasks;
using System.Net.Http.Headers; 
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 System.Net.Http;
using PlayFab;
using PlayFab.Json;
using PlayFab.DataModels;
using PlayFab.ServerModels;
using PlayFab.AdminModels;
using PlayFab.Plugins.CloudScript;
using PlayFab.Samples;
using PlayFab.BuffbaerMuses.Util;
using PlayFab.BuffbaerMuses.Models;
//using PlayFab.CloudScriptModel; 
namespace Buffbaer.RewardSystem
{
    public static class PremiumChoiceRewards
    {
        [FunctionName("PremiumChoiceRewards")]
        public static async Task Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequestMessage req,
            ILogger log)
        {
            //FunctionExecutionContext<dynamic> context = JsonConvert.DeserializeObject<FunctionExecutionContext<dynamic>>(await req.ReadAsStringAsync());
            var context = await FunctionContext<dynamic>.Create(req);
            var playFabId = context.FunctionArgument.PlayFabId;
            string statName = "Paid Choices";
            await StatisticUtil.UpdateStatValue(playFabId, statName, 70);
            
           
        }
            
    }
}

Below is StatisticUtil, which expands on this function.

using PlayFab.ServerModels;
using PlayFab.BuffbaerMuses.Models;
using System;

using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace PlayFab.BuffbaerMuses.Util{
    public class StatisticUtil{
        public static async Task UpdateStatValue(string playFabId, string statName, int deltaValue){
            var apiSettings = new PlayFabApiSettings
            {
                TitleId = Environment.GetEnvironmentVariable(Constants.PLAYFAB_TITLE_ID, EnvironmentVariableTarget.Process),
                DeveloperSecretKey = Environment.GetEnvironmentVariable(Constants.PLAYFAB_DEV_SECRET_KEY, EnvironmentVariableTarget.Process)
            };

            var serverApi = new PlayFabServerInstanceAPI(apiSettings);

            var currentStatResult = await serverApi.GetPlayerStatisticsAsync(
                new GetPlayerStatisticsRequest{
                    PlayFabId = playFabId,
                }
            );
            
            var newValue = deltaValue;

            var updateStatResult = await serverApi.UpdatePlayerStatisticsAsync(
                new UpdatePlayerStatisticsRequest{
                    Statistics = new List<StatisticUpdate>{
                        new StatisticUpdate{
                            StatisticName = statName,
                            Value = newValue
                        }
                    },
                    PlayFabId = playFabId
                });
        }
    }
}


This is the script in Unity that executes this function.

using System.Collections;
using PlayFab.CloudScriptModels;
using PlayFab.BuffbaerMuses.Models;
using UnityEngine;
using PlayFab.Samples;
using Naninovel;
using System;
using PlayFab;

namespace PlayFab.BuffbaerRewardSystem.Handlers
{
    public class AzureFunctionHandler: RequestHandler
    {
        public AzureFunctionHandler(PlayerInfo Player) : base(Player) { }

        public override IEnumerator ExecuteRequest()
        {
            var request = new ExecuteFunctionRequest
            {
                FunctionName = "Premium Choices Reward",
                FunctionParameter = new PlayFabIdRequest
                {
                    PlayFabId = Player.PlayFabId
                },
                AuthenticationContext = new PlayFabAuthenticationContext
                {
                    EntityToken = Player.EntityToken
                },
                GeneratePlayStreamEvent = true
            };

            PlayFabCloudScriptAPI.ExecuteFunction(request, (result) =>
            {
                ExecutionCompleted = true;
                Debug.Log($"The {result.FunctionName} function took {result.ExecutionTimeMilliseconds} to complete");
            },
                (error) =>
                {
                    throw new Exception($"Premium Free Choice TEST Function failed. Message: {error.ErrorMessage}, Code: {error.HttpCode}");
                });
            yield return WaitForExecution();
        }
    }
}
using System.Collections;
using UnityEngine;
using PlayFab.BuffbaerRewardSystem.Handlers;

namespace PlayFab.BuffbaerRewardSystem
{
    public class RewardSystem : MonoBehaviour
    {

        // Start is called before the first frame update
        void Start()
        {
            StartCoroutine(AzureFunction());
        }
        

        private IEnumerator AzureFunction()
        {
            var azureHandler = new AzureFunctionHandler(PlayFabAuthService.CurrentPlayer);
            yield return StartCoroutine(azureHandler.ExecuteRequest());
            Debug.Log("Azure function runn!");
        }
    }
}

The error I am getting on Unity Log:

The Log Stream from Azure Portal Shows this:




Not sure where I am going wrong or what I am missing. But I have added application settings and also have written it locally.

apisPlayer DataCloudScript
unitylog.png (13.2 KiB)
azure-log.png (25.2 KiB)
10 |1200

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

1 Answer

·
Xiao Zha avatar image
Xiao Zha answered

According to the error message, it seems that your Developer Secret Key is not set properly. You can refer to Where to set DeveloperSecretKey for Azure PlayFabServerAPI calls - Playfab Community to correctly set your Developer Secret Key. Also, the PlayFab CloudScript Plugin is outdated. You can refer to PlayFab CloudScript using Azure Functions Quickstart Guide - PlayFab | Microsoft Learn and use CS2AFHelperClasses.cs to obtain the context. And you should specify the type of playFabId since your static method UpdateStateValue needs a string.

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.