// An example of how to access Cloud Script methods. void TestCloudScript() { // this will be called after we have an API endpoint UnityAction RunAfterEndpoint = () => { RunCloudScriptRequest request = new RunCloudScriptRequest(); request.ActionId = "helloWorld"; PlayFabClientAPI.RunCloudScript(request, (RunCloudScriptResult result) => { // we are expecting a string,string keyvaluepair, so here we are capturing the kvp with a dictionary due to it being easier to work with. Dictionary<string, string> deserializedResults = new Dictionary<string, string>(); deserializedResults = PlayFab.SimpleJson.DeserializeObject<Dictionary<string, string>>(result.ResultsEncoded); string message = string.Empty; if (deserializedResults.TryGetValue("messageValue", out message)) { cloudScriptResponse.text = string.Format("Cloud Script -- Version: {0}, Revision: {1} \nResponse: {2}", result.Version, result.Revision, message); } else { cloudScriptResponse.text = "Cloud Script call was successful, but there was an error deserializing the messageValue"; } }, OnPlayFabError); }; // we need to supply the SDK with the endpoint before our RunCloudScriptRequests will succeed GetCloudScriptEndpoint(RunAfterEndpoint); }
/// <summary> /// Triggers a particular server action, passing the provided inputs to the hosted Cloud Script. An action in this context is a handler in the JavaScript. NOTE: Before calling this API, you must call GetCloudScriptUrl to be assigned a Cloud Script server URL. When using an official PlayFab SDK, this URL is stored internally in the SDK, but GetCloudScriptUrl must still be manually called. /// </summary> public static void RunCloudScript(RunCloudScriptRequest request, RunCloudScriptCallback resultCallback, ErrorCallback errorCallback) { if (AuthKey == null) throw new Exception ("Must be logged in to call this method"); string serializedJSON = JsonConvert.SerializeObject(request, Util.JsonFormatting, Util.JsonSettings); Action<string,string> callback = delegate(string responseStr, string errorStr) { RunCloudScriptResult result = null; PlayFabError error = null; ResultContainer<RunCloudScriptResult>.HandleResults(responseStr, errorStr, out result, out error); if(error != null && errorCallback != null) { errorCallback(error); } if(result != null) { if(resultCallback != null) { resultCallback(result); } } }; PlayFabHTTP.Post(PlayFabSettings.GetLogicURL()+"/Client/RunCloudScript", serializedJSON, "X-Authorization", AuthKey, callback); }
public void CloudScript() { if (string.IsNullOrEmpty(PlayFabSettings.GetLogicURL())) { var getUrlTask = PlayFabClientAPI.GetCloudScriptUrlAsync(new ClientModels.GetCloudScriptUrlRequest()); getUrlTask.Wait(); UUnitAssert.Null(getUrlTask.Result.Error, "Failed to get LogicServerURL"); UUnitAssert.NotNull(getUrlTask.Result.Result, "Failed to get LogicServerURL"); UUnitAssert.False(string.IsNullOrEmpty(getUrlTask.Result.Result.Url), "Failed to get LogicServerURL"); UUnitAssert.False(string.IsNullOrEmpty(PlayFabSettings.GetLogicURL()), "Failed to get LogicServerURL"); } var request = new ClientModels.RunCloudScriptRequest(); request.ActionId = "helloWorld"; var cloudTask = PlayFabClientAPI.RunCloudScriptAsync(request); cloudTask.Wait(); UUnitAssert.Null(cloudTask.Result.Error, "Failed to Execute CloudScript"); UUnitAssert.NotNull(cloudTask.Result.Result, "Failed to Execute CloudScript"); UUnitAssert.False(string.IsNullOrEmpty(cloudTask.Result.Result.ResultsEncoded), "Failed to Execute CloudScript"); // Get the helloWorld return message JObject jobj = cloudTask.Result.Result.Results as JObject; UUnitAssert.NotNull(jobj); JToken jtok; jobj.TryGetValue("messageValue", out jtok); UUnitAssert.NotNull(jtok); JValue jval = jtok as JValue; UUnitAssert.NotNull(jval); string actualMessage = jval.Value as string; UUnitAssert.Equals("Hello " + playFabId + "!", actualMessage); }
/// <summary> /// Triggers a particular server action, passing the provided inputs to the hosted Cloud Script. An action in this context is a handler in the JavaScript. NOTE: Before calling this API, you must call GetCloudScriptUrl to be assigned a Cloud Script server URL. When using an official PlayFab SDK, this URL is stored internally in the SDK, but GetCloudScriptUrl must still be manually called. /// </summary> public static void RunCloudScript(RunCloudScriptRequest request, ProcessApiCallback<RunCloudScriptResult> resultCallback, ErrorCallback errorCallback, object customData = null) { if (_authKey == null) throw new Exception("Must be logged in to call this method"); string serializedJson = SimpleJson.SerializeObject(request, Util.ApiSerializerStrategy); Action<CallRequestContainer> callback = delegate(CallRequestContainer requestContainer) { ResultContainer<RunCloudScriptResult>.HandleResults(requestContainer, resultCallback, errorCallback, null); }; PlayFabHTTP.Post("/Client/RunCloudScript", serializedJson, "X-Authorization", _authKey, callback, request, customData); }
private void CloudScript() { if (string.IsNullOrEmpty(PlayFabSettings.LogicServerUrl)) { PlayFabClientAPI.GetCloudScriptUrl(new GetCloudScriptUrlRequest(), CloudScriptUrlCallback, SharedErrorCallback); WaitForApiCalls(); UUnitAssert.True(lastReceivedMessage.StartsWith("CloudScript setup complete: "), lastReceivedMessage); } var request = new RunCloudScriptRequest(); request.ActionId = "helloWorld"; PlayFabClientAPI.RunCloudScript(request, CloudScriptHwCallback, SharedErrorCallback); WaitForApiCalls(); UUnitAssert.Equals("Hello " + playFabId + "!", lastReceivedMessage); }
//Get Loot Drop public static void GetLoot(string[] items, GameObject enemy) { var request = new RunCloudScriptRequest() { ActionId = "grantItemsToCharacter", Params = new { playFabId = PlayFabDataStore.playFabId, characterId = PlayFabDataStore.characterId, items = items } }; PlayFabClientAPI.RunCloudScript(request, (result) => { Debug.Log(result.ResultsEncoded.ToString()); string[] splitResult = result.ResultsEncoded.Split('"'); //19th element is the itemInstanceId Debug.Log("Split Result " + splitResult[61]); // 61st element is the itemId of the item granted from the drop table Debug.Log("Split Result " + splitResult[65]); // 65th element is the itemInstanceId of the item granted from the drop table RevokeInventoryItem(null, splitResult[65]); // Remove the item granted from the loot table enemy.GetComponent<DropItem>().dropItemId = splitResult[61]; enemy.GetComponent<DropItem>().isItemReceived = true; }, (error) => { Debug.Log("Item not Granted!"); Debug.Log(error.ErrorMessage); Debug.Log(error.ErrorDetails); }); }
public static void SetCustomDataOnItem(string key, string value, string itemInstanceId) { Dictionary<string, string> customData = new Dictionary<string, string>(); customData.Add(key, value); var request = new RunCloudScriptRequest() { ActionId = "setCustomDataToGrantedItem", Params = new { characterId = PlayFabDataStore.characterId, itemInstanceId = itemInstanceId, data = customData } }; PlayFabClientAPI.RunCloudScript(request, (result) => { Debug.Log("Custom data set!"); }, (error) => { Debug.Log("Cant set custom data"); Debug.Log(error.ErrorMessage); Debug.Log(error.ErrorDetails); }); }
//Removes the specific item from the users inventory public static void RevokeInventoryItem(string itemId, string itemInstanceId) { var request = new RunCloudScriptRequest() { ActionId = "revokeInventoryItem", Params = new { characterId = PlayFabDataStore.characterId, itemId = itemInstanceId } }; PlayFabClientAPI.RunCloudScript(request, (result) => { Debug.Log(result.Results); if(itemId != null) { PlayFabDataStore.playerInventory.Remove(itemId); } }, (error) => { Debug.Log("Item not Revoked!"); Debug.Log(error.ErrorMessage); Debug.Log(error.ErrorDetails); }); }
//Grant character the items in the array public static void GrantItemsToCharacter(string[] items, string customDataTitle, string itemClass) { var request = new RunCloudScriptRequest() { ActionId = "grantItemsToCharacter", Params = new { playFabId = PlayFabDataStore.playFabId, characterId = PlayFabDataStore.characterId, items = items } }; PlayFabClientAPI.RunCloudScript(request, (result) => { string[] splitResult = result.ResultsEncoded.Split('"'); //19th element is the itemInstanceId //Debug.Log("Split Result " + splitResult[59]); // 63th element is the itemId of the item granted from the drop table //Debug.Log("Split Result " + splitResult[63]); // 63th element is the itemInstanceId of the item granted from the drop table //Debug.Log("Split Result " + splitResult[67]); // 67st element is the item class if (itemClass == "Quest") { foreach (var quest in items) { if (PlayFabDataStore.catalogQuests[quest].currencies != null) { foreach (var currency in PlayFabDataStore.catalogQuests[quest].currencies) { AddUserCurrency(int.Parse(currency.Value.ToString())); } } } if (splitResult[67] == "Skill" || splitResult[67] == "Modifier") { if (!PlayFabDataStore.playerAllRunes.ContainsKey(splitResult[59])) { Debug.Log("Quest 1"); PlayFabDataStore.playerAllRunes.Add(splitResult[59], new PlayerRune(splitResult[59], splitResult[63], splitResult[67], PlayFabDataStore.catalogRunes[splitResult[59]].displayName, "0")); Debug.Log("Quest 2"); SetCustomDataOnItem("Active", "0", splitResult[63]); Debug.Log("Quest 3"); RuneWindow.SortAllRunes(); Debug.Log("Quest 4"); } } else if(splitResult[67] == "Item") { List<PlayerItemInfo> itemInfoList = new List<PlayerItemInfo>(); SetCustomDataOnItem("IsEquipped", "0", splitResult[63]); PlayFabDataStore.playerInventory.Add(splitResult[59]); PlayerItemInfo itemInfo = new PlayerItemInfo(splitResult[59], splitResult[63], "0"); if (PlayFabDataStore.playerInventoryInfo.ContainsKey(splitResult[59])) { PlayFabDataStore.playerInventoryInfo[splitResult[59]].Add(itemInfo); } else { PlayFabDataStore.playerInventoryInfo.Add(splitResult[59], itemInfoList); PlayFabDataStore.playerInventoryInfo[splitResult[59]].Add(itemInfo); } } } if (itemClass == "Skill" || itemClass == "Modifier") { SetCustomDataOnItem(customDataTitle, "0", splitResult[19]); foreach (var item in items) { if (!PlayFabDataStore.playerAllRunes.ContainsKey(item)) { PlayFabDataStore.playerAllRunes.Add(item, new PlayerRune(item, splitResult[19], itemClass, PlayFabDataStore.catalogRunes[item].displayName, "0")); } } RuneWindow.SortAllRunes(); } if (itemClass == "Item") { List<PlayerItemInfo> itemInfoList = new List<PlayerItemInfo>(); SetCustomDataOnItem(customDataTitle, "0", splitResult[19]); Debug.Log("Item 1"); foreach (var item in items) { Debug.Log("Item 2"); Debug.Log("Item " + item); PlayFabDataStore.playerInventory.Add(item); PlayerItemInfo itemInfo = new PlayerItemInfo(item, splitResult[19], "0"); Debug.Log("Item 3"); if (PlayFabDataStore.playerInventoryInfo.ContainsKey(item)) { PlayFabDataStore.playerInventoryInfo[item].Add(itemInfo); } else { PlayFabDataStore.playerInventoryInfo.Add(item, itemInfoList); PlayFabDataStore.playerInventoryInfo[item].Add(itemInfo); } Debug.Log("Item 4"); foreach (var slot in UIItemSlot_Assign.inventorySlots) { if (slot.assignItem == PlayFabDataStore.playerInventory.Count) { slot.SetItemToSlotInstant(); } } } } }, (error) => { Debug.Log("Item not Granted!"); Debug.Log(error.ErrorMessage); Debug.Log(error.ErrorDetails); }); }
//Remove character public static void RemoveCharacter(string Id) { var request = new RunCloudScriptRequest() { ActionId = "removeCharacter", Params = new { characterId = Id, saveInventorycharacter = false } }; PlayFabClientAPI.RunCloudScript(request, (result) => { Debug.Log("Character Removed!"); PlayFabMainMenu.playfabMainMenu.ListCharacters(); }, (error) => { Debug.Log("Character cannot Removed!"); Debug.Log(error.ErrorMessage); Debug.Log(error.ErrorDetails); }); }
//Create new character public static void CreateNewCharacter(string name) { var request = new RunCloudScriptRequest() { ActionId = "newCharacter", Params = new { characterName = name, characterType = "Player" }//set to whatever default class is }; PlayFabClientAPI.RunCloudScript(request, (result) => { string[] splitResult = result.ResultsEncoded.Split('"'); SetCharacterInitialData(splitResult[3]); }, (error) => { PlayFabCreateCharacter.playFabCreateCharacter.errorText.text = error.ErrorMessage; Debug.Log("Character not created!"); Debug.Log(error.ErrorMessage); Debug.Log(error.ErrorDetails); }); }
/// <summary> /// Triggers a particular server action, passing the provided inputs to the hosted Cloud Script. An action in this context is a handler in the JavaScript. NOTE: Before calling this API, you must call GetCloudScriptUrl to be assigned a Cloud Script server URL. When using an official PlayFab SDK, this URL is stored internally in the SDK, but GetCloudScriptUrl must still be manually called. /// </summary> public static async Task<PlayFabResult<RunCloudScriptResult>> RunCloudScriptAsync(RunCloudScriptRequest request) { if (AuthKey == null) throw new Exception ("Must be logged in to call this method"); object httpResult = await PlayFabHTTP.DoPost(PlayFabSettings.GetLogicURL() + "/Client/RunCloudScript", request, "X-Authorization", AuthKey); if(httpResult is PlayFabError) { PlayFabError error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<RunCloudScriptResult> { Error = error, }; } string resultRawJson = (string)httpResult; var serializer = JsonSerializer.Create(PlayFabSettings.JsonSettings); var resultData = serializer.Deserialize<PlayFabJsonSuccess<RunCloudScriptResult>>(new JsonTextReader(new StringReader(resultRawJson))); RunCloudScriptResult result = resultData.data; return new PlayFabResult<RunCloudScriptResult> { Result = result }; }