### Entity File Example Setup - C# Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/live-service-management/game-configuration/entities/quickstart.md This C# code sets up an example class for managing entity files, including necessary using statements and class members for tracking file operations and entity information. ```csharp #if !DISABLE_PLAYFABENTITY_API && !DISABLE_PLAYFABCLIENT_API using PlayFab; using PlayFab.Internal; using System; using System.Collections.Generic; using System.Text; using UnityEngine; public class EntityFileExample : MonoBehaviour { public string entityId; // Id representing the logged in player public string entityType; // entityType representing the logged in player private readonly Dictionary _entityFileJson = new Dictionary(); private readonly Dictionary _tempUpdates = new Dictionary(); public string ActiveUploadFileName; public string NewFileName; // GlobalFileLock provides is a simplistic way to avoid file collisions, specifically designed for this example. public int GlobalFileLock = 0; void OnSharedFailure(PlayFabError error) { Debug.LogError(error.GenerateErrorReport()); GlobalFileLock -= 1; } ``` -------------------------------- ### Authenticate and Create Leaderboard via C# SDK Source: https://context7.com/microsoftdocs/playfab-docs/llms.txt This C# example shows the initial steps for setting up authentication and creating a leaderboard. It first authenticates as a title entity to get an entity token, then logs in a player using a custom ID to obtain player credentials. Finally, it sets the player's display name. This setup is necessary before creating leaderboard definitions. ```csharp // C# — authenticate then create leaderboard via C# SDK PlayFabSettings.staticSettings.TitleId = "YOUR_TITLE_ID"; PlayFabSettings.staticSettings.DeveloperSecretKey = "YOUR_SECRET_KEY"; // 1. Authenticate as title entity var tokenResult = await PlayFabAuthenticationAPI.GetEntityTokenAsync( new GetEntityTokenRequest { Entity = new PlayFab.AuthenticationModels.EntityKey { Id = PlayFabSettings.staticSettings.TitleId, Type = "title" } }); PlayFabAuthenticationContext authCtx = new PlayFabAuthenticationContext { EntityToken = tokenResult.Result.EntityToken }; // 2. Create player login to get entity ID var loginResult = await PlayFabClientAPI.LoginWithCustomIDAsync( new LoginWithCustomIDRequest { CustomId = "GettingStartedGuide", CreateAccount = true }); PlayFabAuthenticationContext playerCtx = loginResult.Result.AuthenticationContext; // 3. Set display name for the player entity await PlayFabProfilesAPI.SetDisplayNameAsync(new SetDisplayNameRequest { AuthenticationContext = playerCtx, DisplayName = "AwesomePlayer", Entity = new PlayFab.ProfilesModels.EntityKey { Id = playerCtx.EntityId, Type = playerCtx.EntityType } }); ``` -------------------------------- ### Client LoginWithCustomID Example Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/api-references/index.md This example demonstrates how to make a POST request to the LoginWithCustomID endpoint. ```APIDOC ## POST /Client/LoginWithCustomID ### Description This endpoint is used for logging in a player with a custom ID. ### Method POST ### Endpoint https://[titleId].playfabapi.com/Client/LoginWithCustomID ### Request Body - **customId** (string) - Required - The custom ID of the player. - **createAccount** (boolean) - Optional - Whether to create an account if one doesn't exist. ### Request Example { "customId": "your_custom_id", "createAccount": true } ### Response #### Success Response (200) - **LoginResult** (object) - Contains the result of the login operation. #### Response Example { "data": { "SessionTicket": "your_session_ticket", "PlayFabId": "player_id", "NewlyCreated": true } } ``` -------------------------------- ### Install http-server using npm Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/identity/player-identity/platform-specific-authentication/running-an-http-server-for-testing.md Installs the http-server package globally on your system. This is a prerequisite for serving files locally. ```bash npm install -g http-server ``` -------------------------------- ### Install PlayFab Client Plugin Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/sdks/lua/quickstart-corona.md Configure your build.settings file to include the PlayFab Client plugin. This ensures the plugin is downloaded and installed in your project. ```lua plugins = { ["plugin.playfab.client"] = { publisherId = "com.playfab" } } ``` -------------------------------- ### Install PlayFab Python SDK Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/sdks/python/quickstart.md Installs the PlayFab Python SDK using pip. Use the second command if pip is not in your system's PATH. ```cmd pip install playfab ``` ```cmd python -m pip install playfab ``` -------------------------------- ### CreateBuildWithCustomContainerAsync Example Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/multiplayer/servers/manage-secrets.md This C# example demonstrates how to reference secrets when creating a new build using the CreateBuildWithCustomContainer API. ```csharp var request = new CreateBuildWithCustomContainerRequest() { ContainerImageReference = new ContainerImageReference() { ImageName = "testimagename", Tag = "0.1" }, ContainerFlavor = ContainerFlavor.CustomLinux, BuildName = "testbuildwithvmstartupscript", VmSize = AzureVmSize.Standard_D2as_v4, MultiplayerServerCountPerVm = 3, Ports = new List() { new Port() { Name = "port", Num = 123, Protocol = ProtocolType.TCP } }, RegionConfigurations = new List() { new BuildRegionParams() { Region = "EastUs", StandbyServers = 3, MaxServers = 6 } }, GameSecretReferences = new[] { new GameSecretReferenceParams { Name = "SecretName" } } }; var result = await PlayFabMultiplayerAPI.CreateBuildWithCustomContainerAsync(request); ``` -------------------------------- ### Start http-server Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/identity/player-identity/platform-specific-authentication/running-an-http-server-for-testing.md Starts the http-server from the current directory. The server will print IP endpoints that can be used to access the served files via a browser. ```bash http-server ``` -------------------------------- ### GUI Button to Execute Example Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/live-service-management/service-gateway/add-ons/photon/quickstart.md Adds a button to the GUI to trigger the example code execution. This is for testing purposes within the Unity editor. ```csharp public void OnGUI() { if (GUILayout.Button("Execute Example ")) ExecuteExample(); } ``` -------------------------------- ### SearchItems API Request Example Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/economy-monetization/economy-v2/catalog/search.md This example demonstrates how to construct a request to the SearchItems API, including parameters for search, filtering, ordering, continuation, count, and language. ```APIDOC ## SearchItems API Request ### Description Executes a search against the public Catalog using the provided search parameters and returns a paged list of items. ### Method POST (or relevant HTTP method if specified, otherwise assumed based on context) ### Endpoint /Catalog/SearchItems (or relevant endpoint) ### Parameters #### Request Body - **Search** (string) - Optional - Plain-text fuzzy search against Title, Description, Keywords, and Searchable String Display Properties. - **Filter** (string) - Optional - OData Query additions to filter search results. Supports logical operators (eq, ne, gt, ge, lt, le, and, or, not) and array filtering with `any()`. - **OrderBy** (string) - Optional - OData Query additions to order search results by any field in the search document (barring Title and Description). - **ContinuationToken** (string) - Optional - Token returned from a previous search response to paginate through results. - **Count** (integer) - Optional - The number of results to return per page. - **Language** (string) - Optional - The language of the search results to return (e.g., "en-GB"). ### Request Example ```json { "Search": "Pirates", "Filter": "Tags/any(t: t eq 'desert') and ContentType eq 'map'", "OrderBy": "lastModifiedDate asc", "ContinuationToken": "abc=", "Count": 2, "Language": "en-GB" } ``` ### Response #### Success Response (200 OK) - **Items** (array) - A list of catalog items matching the search criteria. - **ContinuationToken** (string) - A token to retrieve the next page of results. #### Response Example ```json { "code": 200, "status": "OK", "data": { "Items": [ { } ], "ContinuationToken": "MTA=" } } ``` ``` -------------------------------- ### Create Build with VM Startup Script - C# Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/multiplayer/servers/vmstartupscript.md This C# code example demonstrates how to create a new PlayFab build with a custom Linux container and specifies a VM startup script to customize the virtual machine. Ensure the VmStartupScriptAssetReference.FileName matches your uploaded asset file. ```csharp var request = new CreateBuildWithCustomContainerRequest() { ContainerImageReference = new ContainerImageReference() { ImageName= "testimagename", Tag= "0.1" }, ContainerFlavor = ContainerFlavor.CustomLinux, BuildName = "testbuildwithvmstartupscript", VmSize = AzureVmSize.Standard_D2as_v4, MultiplayerServerCountPerVm = 3, Ports= new List() { new Port() { Name= "port", Num= 123, Protocol = ProtocolType.TCP } }, RegionConfigurations = new List { new BuildRegionParams() { Region = "EastUs", StandbyServers = 3, MaxServers = 6 } }, VmStartupScriptConfiguration = new VmStartupScriptParams() { VmStartupScriptAssetReference = new AssetReferenceParams() { FileName = "vmstartupscriptassets.zip" } } }; var result = await PlayFabMultiplayerAPI.CreateBuildWithCustomContainerAsync(request); ``` -------------------------------- ### GetUserReadOnlyData Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/player-progression/player-data/how-to-get-read-only-player-data.md This C# code example uses the PlayFab server API to get all of the player read-only data. ```APIDOC ## GetUserReadOnlyData ### Description Retrieves all read-only data for a specific player. ### Method PlayFabServerAPI.GetUserReadOnlyData ### Parameters #### Request Body - **PlayFabId** (string) - Required - The PlayFab ID of the player whose data is to be retrieved. ### Request Example ```csharp PlayFabServerAPI.GetUserReadOnlyData(new GetUserDataRequest() { PlayFabId = "user PlayFabId here - obtained from any successful LoginResult", }, result => { // Handle success }, error => { // Handle error }); ``` ### Response #### Success Response - **Data** (object) - A dictionary containing the player's read-only data. #### Response Example ```json { "Data": { "Sister": { "Value": "someValue" } } } ``` ``` -------------------------------- ### Add Starting Inventory Items via Purchase (C#) Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/economy-monetization/economy-v2/tutorials/craftingGame/crafting-game-coding.md Use ExecuteInventoryOperationsAsync to add starting items by performing free purchases. Ensure items have 'FriendlyId' configured in Game Manager. ```csharp var purchasePrice = new List { new PurchasePriceAmount { ItemId = freeItemId, Amount = 0 } }; var request = new ExecuteInventoryOperationsRequest { Entity = new PlayFab.EconomyModels.EntityKey { Id = entityKey.Id, Type = entityKey.Type }, Operations = new List { new InventoryOperation { Purchase = new PurchaseInventoryItemsOperation { Item = new InventoryItemReference {AlternateId = new AlternateId { Type = "FriendlyId", Value = "Stone" } }, Amount = 3, PriceAmounts = purchasePrice } }, new InventoryOperation { Purchase = new PurchaseInventoryItemsOperation { Item = new InventoryItemReference { AlternateId = new AlternateId { Type = "FriendlyId", Value = "Gold" } }, Amount = 1, PriceAmounts = purchasePrice } }, new InventoryOperation { Purchase = new PurchaseInventoryItemsOperation { Item = new InventoryItemReference {AlternateId = new AlternateId { Type = "FriendlyId", Value = "Cream" }}, Amount = 1, PriceAmounts = purchasePrice } } } }; await PlayFabEconomyAPI.ExecuteInventoryOperationsAsync(request); ``` -------------------------------- ### Start Experiment Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/live-service-management/game-configuration/experiments/experimentation-apis.md Allows a client to request the start of an existing experiment for the title based on the experiment ID. The client code gets orchestrated for the change in experience as per the treatment assignment given for the experimental study on the target audience. ```APIDOC ## Start Experiment ### Description Allows a client to request the start of an existing experiment for the title based on the experiment ID. The client code gets orchestrated for the change in experience as per the treatment assignment given for the experimental study on the target audience. ### Method POST ### Endpoint /Experimentation/StartExperiment ``` -------------------------------- ### Basic GSDK Integration in Java Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/multiplayer/servers/integrating-game-servers-with-gsdk.md Implement `start` during game initialization to send heartbeats and set the server state to Initializing. Call `readyForPlayers` when the game is ready for connections; this is a blocking call that returns when the server is allocated or terminated. ```java public static void main(String[] args) { // Call this while your game is initializing; it will start sending a heartbeat to our agent and put the game server in an Initializing state GameserverSDK.start(); /* Add any other initializion code your game server needs before players can connect */ // Call this when your game is done initializing and players can connect // Note: This is a blocking call, and will return when this game server is either allocated or terminated if (GameserverSDK.readyForPlayers()) { // readyForPlayers returns true when an allocation call has been done, a player is about to connect! } else { // readyForPlayers returns false when the server is being terminated } } ``` -------------------------------- ### Get Inventory Collection IDs Response Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/economy-monetization/economy-v2/inventory/collections.md This is an example response from the GetInventoryCollectionIds API, showing a list of available CollectionIds for a player. ```json { "data": { "CollectionIds": [ "default". "main_character" ] } } ``` -------------------------------- ### Basic GSDK Integration in C# Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/multiplayer/servers/integrating-game-servers-with-gsdk.md Implement `Start` during game initialization to send heartbeats and set the server state to Initializing. Call `ReadyForPlayers` when the game is ready for connections; this is a blocking call that returns when the server is allocated or terminated. ```csharp static void Main(string[] args) { // Call this while your game is initializing; it will start sending a heartbeat to our agent and put the game server in an Initializing state GameserverSDK.Start(); /* Add any other initializion code your game server needs before players can connect */ // Call this when your game is done initializing and players can connect // Note: This is a blocking call, and will return when this game server is either allocated or terminated if (GameserverSDK.ReadyForPlayers()) { // readyForPlayers returns true when an allocation call has been done, a player is about to connect! } else { // readyForPlayers returns false when the server is being terminated } } ``` -------------------------------- ### Get Title Data from the game server Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/live-service-management/game-configuration/titledata/quickstart.md Use GetTitleData from the PlayFabServerAPI to retrieve title-wide configuration variables. This example retrieves and logs the value of 'MonsterName'. ```APIDOC ## GetTitleData (Server) ### Description Retrieves the title-wide data for the current title. ### Method POST ### Endpoint /Server/GetTitleData ### Parameters #### Request Body - **Keys** (String[]) - Optional - If not specified, the server returns all title data. ### Request Example ```json { "Keys": [] } ``` ### Response #### Success Response (200) - **Data** (object) - A dictionary object, available only in the server or title data layers, of title-specific keys and values. #### Response Example ```json { "Data": { "MonsterName": "Dorf" } } ``` ``` -------------------------------- ### Get Title Data from the game client Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/live-service-management/game-configuration/titledata/quickstart.md Use GetTitleData from the PlayFabClientAPI to retrieve title-wide configuration variables. This example retrieves and logs the value of 'MonsterName'. ```APIDOC ## GetTitleData (Client) ### Description Retrieves the title-wide data for the current title. ### Method POST ### Endpoint /Client/GetTitleData ### Parameters #### Request Body - **Keys** (String[]) - Optional - If not specified, the server returns all title data. ### Request Example ```json { "Keys": [] } ``` ### Response #### Success Response (200) - **Data** (object) - A dictionary object, available only in the server or title data layers, of title-specific keys and values. #### Response Example ```json { "Data": { "MonsterName": "Dorf" } } ``` ``` -------------------------------- ### PFMultiplayerServerBuildSummary Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/api-references/c/pfmultiplayerservertypes/pfmultiplayerservertypes_members.md Summary information for a multiplayer server build. ```APIDOC ## PFMultiplayerServerBuildSummary ### Description Summary information for a multiplayer server build. ### Structure ```c typedef struct PFMultiplayerServerBuildSummary { const char* buildId; const char* buildName; const char* creationTime; PFMultiplayerServerDynamicStandbySettings* dynamicStandbySettings; PFMultiplayerServerBuildRegion* regions; uint32_t regionsCount; PFMultiplayerServerBuildSelectionCriterion* defaultBuildSelectionCriteria; uint32_t defaultBuildSelectionCriteriaCount; PFMultiplayerServerScheduledStandbySettings* scheduledStandbySettings; PFMultiplayerServerPort* ports; uint32_t portsCount; bool deletionProtection; } PFMultiplayerServerBuildSummary; ``` ``` -------------------------------- ### Get Entity Handle with PFAuthenticationReLoginWithXUserAsync Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/sdks/c/event-pipeline/eventpipeline-tutorial.md Obtain a PFEntityHandle by calling PFAuthenticationReLoginWithXUserAsync. This requires a valid XUserHandle. The example demonstrates a blocking wait for completion using XAsyncGetStatus. ```cpp PFEntityHandle entityHandle; PFAuthenticationLoginWithXUserRequest request{}; request.createAccount = true; request.user = userHandle; // An XUserHandle obtained from XUserAddAsync XAsyncBlock async{}; HRESULT hr = PFAuthenticationReLoginWithXUserAsync(entityHandle, &request, &async); if (FAILED(hr)) { printf("Failed PFAuthenticationReLoginWithXUserAsync: 0x%x\r\n", hr); return; } hr = XAsyncGetStatus(&async, true); // This is doing a blocking wait for completion, but you can use the XAsyncBlock to set a callback instead for async style usage if (FAILED(hr)) { printf("Failed XAsyncGetStatus: 0x%x\r\n", hr); return; } ``` -------------------------------- ### Create a Store using CreateDraftItem API Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/economy-monetization/economy-v2/catalog/stores.md This example demonstrates how to create a new store by using the `CreateDraftItem` API call. The store is configured with specific items and their overridden prices. ```APIDOC ## Create a Store ### Description Use the `CreateDraftItem` API to create a store. This involves defining the store's properties, including the items it will contain and their prices, which can override the base catalog prices. ### Method POST ### Endpoint /Economy/CreateDraftItem ### Request Body - **Item** (object) - Required - The item to be created, with `Type` set to "store". - **Type** (string) - Required - Must be "store". - **Title** (object) - Required - A localized title for the store. - **NEUTRAL** (string) - Required - The neutral language title. - **StartDate** (string) - Required - The date and time the store becomes active. - **ItemReferences** (array) - Required - A list of items available in the store. - **Id** (string) - Required - The ID of the catalog item. - **Amount** (integer) - Optional - The amount of the item. - **PriceOptions** (object) - Optional - Defines the pricing for the item within the store. - **Prices** (array) - Required - A list of price definitions. - **Amounts** (array) - Required - A list of currency amounts for the price. - **ItemId** (string) - Required - The ID of the currency item. - **Amount** (integer) - Required - The amount of currency. - **Publish** (boolean) - Required - Whether to publish the store immediately. ### Request Example ```json { "Item": { "Type": "store", "Title": { "NEUTRAL": "My First Store" }, "StartDate": "2022-09-07T00:00:00.00000000Z", "ItemReferences":[ { "Id":"LaserSword", "Amount": 1, "PriceOptions": { "Prices": [{ "Amounts": [{ "ItemId": "Diamond", "Amount": 1 }] }] } }, { "Id":"WeaponBundle", "PriceOptions": { "Prices": [{ "Amounts": [{ "ItemId": "Gold", "Amount": 10 }, { "ItemId": "Silver", "Amount": 10 }] }], } }] }, "Publish": true } } ``` ### Response #### Success Response (202 Accepted) - **code** (integer) - The HTTP status code. - **status** (string) - The status message. - **Item** (object) - The created store item details. - **Type** (string) - The item type, will be "store". - **Id** (string) - The unique identifier for the store. - **Title** (object) - The localized title of the store. - **NEUTRAL** (string) - The neutral language title. #### Response Example ```json { "code": 202, "status": "Accepted", "Item": { "Type": "store", "Id": "{{StoreID}}", "Title": { "NEUTRAL": "My First Store" }, ... } } ``` ``` -------------------------------- ### Start Game Server Command (Windows) Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/multiplayer/servers/basics-of-a-playFab-game-server.md This command is used to start the game server executable on Windows. The application must use the PlayFab Game Server SDK to call ReadyForPlayers when it is ready to serve clients. The container will be terminated if the process exits. ```cmd C:\GameCoreApp\GameServer.exe -mode RETAIL ``` -------------------------------- ### Get Player Objects Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/live-service-management/service-gateway/automation/cloudscript-af/quickstart.md This is an example of how to retrieve objects associated with a player entity using the PlayFab API. This can be used to verify data attached by an Azure Function. ```http # @name GetObjects POST {{baseUrl}}/Object/GetObjects Accept-Encoding: gzip Content-Type: application/json X-EntityToken: {{entityToken}} { "Entity": {{entity}}, "Objects": ["obj1"] } ``` -------------------------------- ### Get an Entity Token Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/economy-monetization/economy-v2/ugc/quickstart.md To interact with UGC, you first need an entity token. This is obtained by calling the LoginWithCustomID API. The example shows the request body for this service call. ```APIDOC ## Get an Entity Token ### Description Obtain an entity token required for UGC operations by calling the `LoginWithCustomID` API. ### Method POST ### Endpoint /Client/LoginWithCustomID ### Request Body - **CustomId** (string) - Required - The custom ID for the player. - **CreateAccount** (boolean) - Required - Whether to create an account if one doesn't exist. - **TitleId** (string) - Required - The title ID of your PlayFab game. ### Request Example ```json { "CustomId": "exampleUser", "CreateAccount": true, "TitleId": "DC7B" } ``` ``` -------------------------------- ### Windows Container Start Command and Image Details Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/multiplayer/servers/LocalMultiplayerAgent/run-container-gameserver.md Configure the start game command and image details for running a game server in a Windows container. The StartGameCommand specifies how to launch your game server after assets are extracted. ```json "ContainerStartParameters": { "StartGameCommand": "C:\\Assets\\wrapper.exe -g C:\\Assets\\fakegame.exe arg1 arg2", // Your game assets will be extracted under C:\\Assets (default mount path for Windows Container) and LMA will run your game server with StartGameCommand argument. // Make sure the StartGameCommand provided above is an example of the Wrapper sample. "ImageDetails": { "Registry": "mcr.microsoft.com", "ImageName": "playfab/multiplayer", "ImageTag": "wsc-10.0.17763.973.1", "Username": "", "Password": "" // username and password are not required to use MCR image. } // LMA will package an existing game sample (path defined in LocalFilePath) as a Windows container. } ``` -------------------------------- ### Basic GSDK Integration in C++ Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/multiplayer/servers/integrating-game-servers-with-gsdk.md Implement `start` during game initialization to send heartbeats and set the server state to Initializing. Call `readyForPlayers` when the game is ready for connections; this is a blocking call that returns when the server is allocated or terminated. ```cpp int main() { // Call this while your game is initializing; it will start sending a heartbeat to our agent and put the game server in an Initializing state Microsoft::Azure::Gaming::GSDK::start(); /* Add any other initialization code your game server needs before players can connect */ // Call this when your game is done initializing and players can connect // Note: This is a blocking call, and will return when this game server is either allocated or terminated if (Microsoft::Azure::Gaming::GSDK::readyForPlayers()) { // readyForPlayers returns true when an allocation call has been done, a player is about to connect! } else { // readyForPlayers returns false when the server is being terminated } } ``` -------------------------------- ### StartOrRecoverSessionRequest JSON Example Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/multiplayer/real-time-notifications/types/start-or-recover-session-request.md This JSON object represents a request to start or recover a session. It includes an optional `oldConnectionHandle` for session recovery and a required `traceParent` for distributed tracing. ```json { "oldConnectionHandle": "1.Y2VudHJhbC11c35sb2NhbGhvc3R+QkxVV1pYSEwwZkF0b1o5WUR2MV9vQQ==", "traceParent": "00-84678fd69ae13e41fce1333289bcf482-22d157fb94ea4827-01" } ``` -------------------------------- ### Getting User Publisher Data Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/live-service-management/game-configuration/titledata/using-publisher-data.md Provides C# code examples for retrieving regular, read-only, and internal user publisher data using PlayFab Client and Server APIs. ```APIDOC ## Getting user Publisher data The following snippet demonstrates how to get all 3 kinds of Publisher data using Client and Server APIs. ```csharp // Use Client API to get Regular User Publisher Data for selected user public void ClientGetUserPublisherData() { PlayFabClientAPI.GetUserPublisherData(new GetUserDataRequest() { PlayFabId = "" }, result => { if (result.Data == null || !result.Data.ContainsKey("SomeKey")) Debug.Log("No SomeKey"); else Debug.Log("SomeKey: " + result.Data["SomeKey"]); }, error => { Debug.Log("Got error getting Regular Publisher Data:"); Debug.Log(error.GenerateErrorReport()); }); } // Use Client API to get Read-Only User Publisher Data for selected user public void ClientGetUserPublisherReadOnlyData() { PlayFabClientAPI.GetUserPublisherReadOnlyData(new GetUserDataRequest() { PlayFabId = "" }, result => { if (result.Data == null || !result.Data.ContainsKey("SomeKey")) Debug.Log("No SomeKey"); else Debug.Log("SomeKey: " + result.Data["SomeKey"]); }, error => { Debug.Log("Got error getting Read-Only Publisher Data:"); Debug.Log(error.GenerateErrorReport()); }); } // Use Server API to get Internal User Publisher Data for selected user public void ServerGetUserPublisherInternalData() { PlayFabServerAPI.GetUserPublisherInternalData(new GetUserDataRequest() { PlayFabId = "" }, result => { if (result.Data == null || !result.Data.ContainsKey("SomeKey")) Debug.Log("No SomeKey"); else Debug.Log("SomeKey: " + result.Data["SomeKey"]); }, error => { Debug.Log("Got error getting Internal Publisher Data:"); Debug.Log(error.GenerateErrorReport()); }); } ``` ``` -------------------------------- ### PFMultiplayerInitialize Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/multiplayer/lobby/playfabmultiplayerreference-cpp/pfmultiplayer/pfmultiplayer_members.md Initializes an instance of the PlayFab Multiplayer library. ```APIDOC ## PFMultiplayerInitialize ### Description Initializes an instance of the PlayFab Multiplayer library. ### Method (Not specified, likely a function call) ### Parameters (Not specified) ### Response (Not specified) ``` -------------------------------- ### Get Player Statistics Server Response JSON Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/community/leaderboards/tournaments-leaderboards/using-resettable-statistics-and-leaderboards.md Example JSON response for a server-side GetPlayerStatistics call, showing the player's ID, statistic name, value, and version. ```json { "code": 200, "status": "OK", "data": { "PlayFabId": {{PlayFabId}}, "Statistics": [ { "StatisticName": "Headshots", "Value": 10, "Version": "3" }] } } ``` -------------------------------- ### Get Player Statistic Versions Response JSON Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/community/leaderboards/tournaments-leaderboards/using-resettable-statistics-and-leaderboards.md Example JSON response for GetPlayerStatisticVersions, detailing statistic names, versions, activation/deactivation times, archival status, and download URLs. ```json { "code": 200, "status": "OK", "data": { "StatisticVersions": [ { "StatisticName": "Headshots", "Version": 0, "ActivationTime": "2015-01-20T05:47:27.17Z", "DeactivationTime": "2016-01-25T00:00:00.000Z", "ArchivalStatus": "Complete", "ArchiveDownloadUrl": {{URL}} }, { "StatisticName": "Headshots", "Version": 1, "ActivationTime": "2016-01-25T00:00:00.000Z", "DeactivationTime": "2016-01-25T00:00:00.000Z", "ArchivalStatus": "Complete", "ArchiveDownloadUrl": {{URL}} }, { "StatisticName": "Headshots", "Version": 2, "ActivationTime": "2016-01-25T00:00:00.000Z", "DeactivationTime": "2016-02-03T08:02:29.864Z", "ArchivalStatus": "InProgress" }, { "StatisticName": "Headshots", "Version": 3, "ActivationTime": "2016-02-03T08:02:29.864Z", "ArchivalStatus": "NotScheduled" }] } } ``` -------------------------------- ### Photon Authentication Setup Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/live-service-management/service-gateway/add-ons/photon/quickstart.md Sets up custom authentication values for Photon. Ensure this is called before connecting to Photon. ```csharp PhotonNetwork.AuthValues = customAuth; ``` -------------------------------- ### Get Player Profile via Login Operation (C#) Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/player-progression/player-data/getting-player-profiles.md Combine a login request with retrieving player profile data in a single call. This example uses LoginWithCustomID and requests AvatarUrl and LastLogin. ```csharp void CreatePlayerAndUpdateDisplayName(string customId) { PlayFabClientAPI.LoginWithCustomID( new LoginWithCustomIDRequest() { CustomId = customId, // Define info request parameters InfoRequestParameters = new GetPlayerCombinedInfoRequestParams() { // And make sure PlayerProfile is included GetPlayerProfile = true, // Define rules for PlayerProfile request ProfileConstraints = new PlayerProfileViewConstraints() { // And make sure that both AvatarUrl and LastLogin are included. ShowAvatarUrl = true, ShowLastLogin = true, } } }, result => { // Extract the data you have requested var avatarUrl = result.InfoResultPayload.PlayerProfile.AvatarUrl; }, error => Debug.LogError(error.GenerateErrorReport())); } ``` -------------------------------- ### Process Purchase Callback in Unity Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/economy-monetization/economy-v2/tutorials/getting-started-with-unity-and-android.md Callback for handling completed purchases. It checks if the IAP service is initialized and returns the processing result. Note: This example does not handle pending purchases delivered on app start. ```csharp public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs purchaseEvent) { if (!IsInitialized) { Debug.LogWarning("Not initialized. Ignoring."); return PurchaseProcessingResult.Complete; } ``` -------------------------------- ### PlayFabMultiplayerServer Constructor Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/multiplayer/lobby/unity-multiplayer-api-reference/PlayFab.Multiplayer/PlayFabMultiplayer.PlayFabMultiplayerServer/PlayFabMultiplayerServer.md Initializes a new instance of the PlayFabMultiplayerServer class with default settings. ```APIDOC ## PlayFabMultiplayerServer() ### Description The default constructor for the PlayFabMultiplayerServer class. ### Method `public PlayFabMultiplayerServer()` ### Parameters This constructor does not take any parameters. ### Response Initializes a new instance of the PlayFabMultiplayerServer class. ``` -------------------------------- ### Authenticate Title Entity with Secret Key Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/sdks/c/server.md Use this to get a title entity handle. Ensure you have a valid `PFServiceConfigHandle` and the title-specific secret key. Error handling for `HRESULT` is crucial. The example shows a blocking wait for completion, but asynchronous callbacks are also supported. ```cpp PFAuthenticationGetEntityRequest request{}; XAsyncBlock async{}; // Add your own error handling when FAILED(hr) == true HRESULT hr = PFAuthenticationGetEntityWithSecretKeyAsync( serviceConfigHandle, secretKey, // title specific secret key &request, &async ); hr = XAsyncGetStatus(&async, true); // This is doing a blocking wait for completion, but you can use the XAsyncBlock to set a callback instead for async style usage PFEntityHandle entityHandle; hr = PFAuthenticationGetEntityWithSecretKeyGetResult( &async, &entityHandle ); ``` -------------------------------- ### Create Experiment Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/live-service-management/game-configuration/experiments/experimentation-apis.md Allows a client to request the creation of an experiment for the title. The experiment configuration gets defined as part of it, containing the experiment details, like target audience, start date, variant groups, and associated variables for orchestrating the change in experience (or treatment assignment). The treatment assignment can include virtually anything on the client or PlayFab services. ```APIDOC ## Create Experiment ### Description Allows a client to request the creation of an experiment for the title. The experiment configuration gets defined as part of it, containing the experiment details, like target audience, start date, variant groups, and associated variables for orchestrating the change in experience (or treatment assignment). The treatment assignment can include virtually anything on the client or PlayFab services. ### Method POST ### Endpoint /Experimentation/CreateExperiment ``` -------------------------------- ### Initialize Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/multiplayer/lobby/unity-multiplayer-api-reference/PlayFab.Multiplayer/PlayFabMultiplayer.md Initializes an instance of the PlayFab Multiplayer library. ```APIDOC ## Initialize ### Description Initializes an instance of the PlayFab Multiplayer library. ### Method Signature static Initialize() ``` -------------------------------- ### Get Result of Server Get Player Combined Info Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/api-references/c/pfaccountmanagement/pfaccountmanagement_members.md Gets the result of a successful PFAccountManagementServerGetPlayerCombinedInfoAsync call. ```APIDOC ## PFAccountManagementServerGetPlayerCombinedInfoGetResult ### Description Gets the result of a successful PFAccountManagementServerGetPlayerCombinedInfoAsync call. ### Method PFAccountManagementServerGetPlayerCombinedInfoGetResult ### Parameters This function does not take any parameters. ### Request Example ```json { "example": "No request body for this operation." } ``` ### Response #### Success Response (200) This operation does not return a value in the success response. #### Response Example ```json { "example": "No response body for this operation." } ``` ``` -------------------------------- ### Set Start Command for Windows Container Mode Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/multiplayer/servers/server-sdks/unreal-gsdk/third-person-mp-example-project-cloud-deployment.md For Windows Container Mode, the start command must be a full path relative to the specified Mount Path. Include the Mount Path and the executable name, optionally with '-log'. Sub-folder paths are also supported. ```text {MountPath}\{ProjectName}Server.exe ``` ```text {MountPath}\{ProjectName}Server.exe -log ``` ```text {MountPath}\WindowsServer\{ProjectName}Server.exe ``` -------------------------------- ### Get Result of Get Title Players From Xbox Live IDs Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/api-references/c/pfaccountmanagement/pfaccountmanagement_members.md Gets the result of a successful PFAccountManagementGetTitlePlayersFromXboxLiveIDsAsync call. ```APIDOC ## PFAccountManagementGetTitlePlayersFromXboxLiveIDsGetResult ### Description Gets the result of a successful PFAccountManagementGetTitlePlayersFromXboxLiveIDsAsync call. ### Method PFAccountManagementGetTitlePlayersFromXboxLiveIDsGetResult ### Parameters This function does not take any parameters. ### Request Example ```json { "example": "No request body for this operation." } ``` ### Response #### Success Response (200) This operation does not return a value in the success response. #### Response Example ```json { "example": "No response body for this operation." } ``` ``` -------------------------------- ### Get Group Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/pricing/Meters/profile-reads.md Gets information about a group and its roles. ```APIDOC ## Get Group ### Description Gets information about a group and its roles. ### Method GET ### Endpoint /rest/api/playfab/groups/groups/get-group ``` -------------------------------- ### Login with Windows Hello Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/identity/player-identity/platform-specific-authentication/uwp-integration.md This section details the steps required to log in a player using their Windows Hello credentials. It involves obtaining a challenge, signing it with the user's key, and then using that signature to log in via PlayFab. ```APIDOC ## Logging in the Player via Windows Hello Once you have linked Windows Hello credentials to a PlayFab account, you can log in with those credentials. You will need the public key hint, and the Windows username. Follow these steps: 1. Call `PlayFabClientAPI.GetWindowsHelloChallengeAsync` to create a signing challenge. 2. Use `CryptographicBuffer.DecodeFromBase64String` to create an IBuffer for the `KeyCredentialManager` to have the user sign. 3. Call `KeyCredentialManager.OpenAsync(userId)` to create a key signing service. 4. Get the credential for this user: `var userCredential = retrieveResult.Credential`. 5. Call `userCredential.RequestSignAsync(challengeBuffer)` to have Windows request that the user sign the server's challenge for this user. 6. Finally, call `PlayFabClientAPI.LoginWithWindowsHello` to complete the process and log in the player. 7. Assuming the login was successful, the player is now logged in. You will get back a session token that you can use to authenticate the player with all other PlayFab APIs. ``` -------------------------------- ### Create a basic index.html file Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/identity/player-identity/platform-specific-authentication/running-an-http-server-for-testing.md A simple HTML file to serve as content for the local HTTP server. This file should be placed in the directory you intend to serve. ```html My Page

Hello world!

``` -------------------------------- ### Get Size of Get Title Players From Xbox Live IDs Result Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/api-references/c/pfaccountmanagement/pfaccountmanagement_members.md Get the size in bytes needed to store the result of a GetTitlePlayersFromXboxLiveIDs call. ```APIDOC ## PFAccountManagementGetTitlePlayersFromXboxLiveIDsGetResultSize ### Description Get the size in bytes needed to store the result of a GetTitlePlayersFromXboxLiveIDs call. ### Method PFAccountManagementGetTitlePlayersFromXboxLiveIDsGetResultSize ### Parameters This function does not take any parameters. ### Request Example ```json { "example": "No request body for this operation." } ``` ### Response #### Success Response (200) This operation does not return a value in the success response. #### Response Example ```json { "example": "No response body for this operation." } ``` ``` -------------------------------- ### Get Global Policy Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/pricing/Meters/profile-reads.md Gets the global title access policy. ```APIDOC ## Get Global Policy ### Description Gets the global title access policy. ### Method GET ### Endpoint /rest/api/playfab/profiles/account-management/get-global-policy ``` -------------------------------- ### Create and Join a Lobby (C++) Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/multiplayer/lobby/lobby-getting-started.md Demonstrates how to create a new lobby and join it. It configures lobby settings like max members, owner migration, and access policy. The code includes synchronous polling for the asynchronous operation completion, which should be handled asynchronously in a production environment. ```cpp PFLobbyCreateConfiguration lobbyConfiguration{}; lobbyConfiguration.maxMemberCount = 16; lobbyConfiguration.ownerMigrationPolicy = PFLobbyOwnerMigrationPolicy::Automatic; lobbyConfiguration.accessPolicy = PFLobbyAccessPolicy::Public; PFLobbyJoinConfiguration memberConfiguration{}; PFLobbyHandle lobby; HRESULT hr = PFMultiplayerCreateAndJoinLobby(g_pfmHandle, localUserEntity, &lobbyConfiguration, &memberConfiguration, nullptr, &lobby); if (FAILED(hr)) { // handle immediate create failure printf("PFMultiplayerCreateAndJoinLobby failed! %s\n", PFMultiplayerGetErrorMessage(hr)); return hr; } // NOTE: to simplify this quickstart, we'll synchronously block waiting waiting for the CreateAndJoinLobby operation // to finish. In a real implementation, this polling would be done asynchronously on a background thread/worker. bool createAndJoinLobbyFinished = false; while (!createAndJoinLobbyFinished) { uint32_t lobbyStateChangeCount; const PFLobbyStateChange * const * lobbyStateChanges; HRESULT hr = PFMultiplayerStartProcessingLobbyStateChanges(m_pfmHandle, &lobbyStateChangeCount, &lobbyStateChanges); if (FAILED(hr)) { // handle the failure printf("PFMultiplayerStartProcessingLobbyStateChanges failed! %s\n", PFMultiplayerGetErrorMessage(hr)); return hr; } for (uint32_t i = 0; i < lobbyStateChangeCount; ++i) { const PFLobbyStateChange* stateChange = lobbyStateChanges[i]; switch (stateChange->stateChangeType) { case PFLobbyStateChangeType::CreateAndJoinLobbyCompleted: { auto createAndJoinStateChange = static_cast(stateChange); if (SUCCEEDED(createAndJoinStateChange->result)) { // lobby successfully created! printf("Lobby 0x%p successfully created!\n", createAndJoinStateChange->lobby); } else { // report asynchronous failure printf("Failed to create lobby 0x%p! %s\n", createAndJoinStateChange->lobby, PFMultiplayerGetErrorMessage(createAndJoinStateChange->result)); } createAndJoinLobbyFinished = true; break; } } } hr = PFMultiplayerFinishProcessingLobbyStateChanges(m_pfmHandle, lobbyStateChangeCount, lobbyStateChanges); if (FAILED(hr)) { printf("PFMultiplayerFinishProcessingLobbyStateChanges failed! %s\n", PFMultiplayerGetErrorMessage(hr)); return hr; } } ``` -------------------------------- ### Get Result of Server Ban Users Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/api-references/c/pfaccountmanagement/pfaccountmanagement_members.md Gets the result of a successful PFAccountManagementServerBanUsersAsync call. ```APIDOC ## PFAccountManagementServerBanUsersGetResult ### Description Gets the result of a successful PFAccountManagementServerBanUsersAsync call. ### Method PFAccountManagementServerBanUsersGetResult ### Parameters This function does not take any parameters. ### Request Example ```json { "example": "No request body for this operation." } ``` ### Response #### Success Response (200) This operation does not return a value in the success response. #### Response Example ```json { "example": "No response body for this operation." } ``` ``` -------------------------------- ### Include Your Game Script Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/sdks/javascript/quickstart.md Link your custom JavaScript file that contains PlayFab logic. This example assumes your file is named PlayFabGettingStarted.js. ```html ``` -------------------------------- ### Set Start Command for Windows Process Mode Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/multiplayer/servers/server-sdks/unreal-gsdk/third-person-mp-example-project-cloud-deployment.md In Windows Process Mode, the start command is executed directly from the unzipped asset files' location. Specify the executable name, optionally with '-log' to generate logs. Relative paths can be used if assets are zipped with sub-folders. ```text {ProjectName}Server.exe ``` ```text {ProjectName}Server.exe -log ``` ```text WindowsServer/{ProjectName}Server.exe ``` -------------------------------- ### Install PlayFab Multiplayer API PowerShell Module Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/multiplayer/servers/deploy-using-powershell-api.md Installs the latest PlayFab Multiplayer API PowerShell module. It's recommended to set the execution policy to Unrestricted for the current user before installation if you encounter issues. ```powershell Install-Module -Name PlayFabMultiplayerApi ``` -------------------------------- ### Login with Windows Hello Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/identity/player-identity/platform-specific-authentication/uwp.md Handles the complete login flow using Windows Hello, including requesting a challenge, signing it, and logging into PlayFab. ```csharp if (string.IsNullOrEmpty(challenge)) return; // Request user to sign the challenge. var signedChallenge = await RequestUserSignChallenge(credentials, challenge); if (string.IsNullOrEmpty(signedChallenge)) return; // Send the signature back to the server to confirm our identity. // The publicKeyHint tells the server which public key to use to verify the signature. var result = await CallPlayFabLoginWithHello(publicKeyHint, signedChallenge); if (result == null) return; // Report the result. await ShowMessage("Signed in with Session Ticket " + result.Result.SessionTicket); ``` -------------------------------- ### Initiate Product Purchase Source: https://github.com/microsoftdocs/playfab-docs/blob/docs/playfab-docs/economy-monetization/economy-v2/tutorials/getting-started-with-unity-and-android.md Starts the purchase process for a given product ID using the Unity IAP service. Includes a check to ensure the IAP service is initialized. ```csharp if (!IsInitialized) { Debug.LogError("IAP Service is not initialized!"); return; } s_storeController.InitiatePurchase(productId); ```