### Quick Start: Make API Calls
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/README.md
Examples of making API calls to Client, Server, and Data APIs.
```javascript
// Client API
PlayFab.ClientApi.GetPlayerStatistics({}, callback);
// Server API (from backend only)
PlayFab.ServerApi.UpdatePlayerStatistics({
PlayFabId: "player_id",
Statistics: [{ StatisticName: "Level", Value: 5 }]
}, callback);
// Data API (entity storage)
PlayFab.DataApi.SetObjects({
Entity: { Id: playFabId },
Objects: [{
ObjectName: "MyData",
DataObject: { key: "value" }
}]
}, callback);
```
--------------------------------
### Basic Configuration and Login
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/api-reference/PlayFabModule.md
Example of configuring the SDK and performing a basic login with email.
```APIDOC
## Usage Examples
### Basic Configuration and Login
```javascript
// Configure the SDK
PlayFab.settings.titleId = "YOUR_TITLE_ID";
// Login with email
PlayFab.ClientApi.LoginWithEmailAddress(
{
Email: "player@example.com",
Password: "secure_password",
CreateAccount: true
},
function(result, error) {
if (error) {
console.error(PlayFab.GenerateErrorReport(error));
return;
}
console.log("Logged in successfully!");
console.log("PlayFabId:", result.data.PlayFabId);
}
);
```
```
--------------------------------
### Quick Start: Login with PlayFab
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/README.md
Logs in a player using PlayFab credentials and logs the PlayFab ID upon successful login.
```javascript
PlayFab.ClientApi.LoginWithPlayFab(
{ Username: "player", Password: "pass123" },
function(result, error) {
if (!error) {
console.log("Logged in! PlayFab ID:", result.data.PlayFabId);
}
}
);
```
--------------------------------
### Example 404 Not Found Error Object
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/errors.md
Shows an example error object for a 404 Not Found response, often indicating that a requested PlayFab ID or resource does not exist.
```javascript
{
code: 404,
status: "Not Found",
error: "InvalidPlayFabId",
errorMessage: "The PlayFab user was not found"
}
```
--------------------------------
### Quick Start: Get Entity Token
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/README.md
Retrieves an entity token, which is required for entity-based API calls.
```javascript
PlayFab.AuthenticationApi.GetEntityToken(
{},
function(result, error) {
if (!error) {
console.log("Entity token obtained");
}
}
);
```
--------------------------------
### Install PlayFab JavaScript SDK via NPM
Source: https://github.com/playfab/javascriptsdk/blob/master/README.md
Install the web JavaScript package for PlayFab SDK using npm. This package can be integrated into client-side JavaScript codebases using build tools.
```bash
npm install playfab-web-sdk
```
--------------------------------
### Complete Client Authentication Flow
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/api-reference/AuthenticationApi.md
This example demonstrates the full client authentication process: logging in with credentials, obtaining an entity token, and then using that token to access entity-based APIs like PlayFab Data API.
```javascript
// 1. Login with credentials
PlayFab.ClientApi.LoginWithPlayFab(
{ Username: "player1", Password: "pass123" },
function(result, error) {
if (error) return;
// 2. Get entity token for entity-based APIs
PlayFab.AuthenticationApi.GetEntityToken(
{},
function(entityResult, entityError) {
if (entityError) return;
// 3. Now can use entity-based APIs
PlayFab.DataApi.GetObjects(
{ Entity: entityResult.data.Entity },
function(dataResult, dataError) {
if (!dataError) {
console.log("Entity data retrieved");
}
}
);
}
);
}
);
```
--------------------------------
### Initialize PlayFab SDK and Login
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/api-reference/PlayFabModule.md
Include the SDK script, configure your title ID and global headers, then use the ClientApi to log in with a custom ID. This is a common starting point for client-side PlayFab integration.
```javascript
// 1. Include the SDK script in your HTML
//
// 2. Configure settings
PlayFab.settings.titleId = "YOUR_TITLE_ID";
PlayFab.settings.GlobalHeaderInjection = {
"X-Custom-User-Agent": "MyGame/1.0"
};
// 3. Use the APIs
PlayFab.ClientApi.LoginWithCustomID({
CustomId: "user_" + Date.now(),
CreateAccount: true
}, function(result, error) {
if (error) {
console.error("Login failed:", error.errorMessage);
} else {
console.log("Login successful! PlayFabId:", result.data.PlayFabId);
}
});
```
--------------------------------
### Callback-based API Call Example
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/api-reference/PlayFabModule.md
Demonstrates how to make an asynchronous API call using a callback function. The callback handles success by logging account info or failure by logging an error message.
```javascript
PlayFab.ClientApi.GetAccountInfo(
{},
function(result, error) {
if (error) {
console.error("Error:", error.errorMessage);
return;
}
console.log("Account info retrieved:", result.data);
}
);
```
--------------------------------
### Accessing PlayFab SDK Version
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/api-reference/PlayFabModule.md
Shows how to get the current SDK version from the global PlayFab object.
```javascript
console.log(PlayFab.sdkVersion); // "1.217.260605"
```
--------------------------------
### Server API
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/MANIFEST.md
Complete server-to-server API documentation with session validation, player management, statistics, data management, virtual currency, character management, shared groups, CloudScript, and leaderboards. Includes method signatures, parameter tables, return types, and code examples.
```APIDOC
## Server API
### Description
Complete server-to-server API documentation with session validation, player management, statistics, data management, virtual currency, character management, shared groups, CloudScript, and leaderboards. Includes method signatures, parameter tables, return types, and code examples.
### Key Sections
- Session Validation (AuthenticateSessionTicket)
- Player Account Management (DeletePlayer, BanUsers)
- Player Statistics (UpdatePlayerStatistics, GetPlayerStatistics)
- Player Data Management (SetUserData, GetUserData, etc.)
- Virtual Currency (AddUserVirtualCurrency, SubtractUserVirtualCurrency)
- Character Management (GrantCharacterToUser, DeleteCharacterFromUser, etc.)
- Shared Group Data (CreateSharedGroup, UpdateSharedGroupData, etc.)
- CloudScript Execution
- Leaderboards
```
--------------------------------
### Example Network Error Object
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/errors.md
Illustrates a typical PlayFab network error object that might be returned when connectivity issues prevent communication with the server. This example shows a 'Service Unavailable' error with a connection error message.
```javascript
{
code: 503,
status: "Service Unavailable",
error: "Connection error",
errorMessage: "Failed to connect to PlayFab"
}
```
--------------------------------
### Example 429 Too Many Requests Error Object
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/errors.md
Displays an example error object for a 429 Too Many Requests response, which includes 'retryAfterSeconds' to indicate when the request can be retried.
```javascript
{
code: 429,
status: "Too Many Requests",
error: "RateLimitExceeded",
errorMessage: "Request rate limit exceeded",
retryAfterSeconds: 60
}
```
--------------------------------
### Client API
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/MANIFEST.md
Complete client-side API documentation with login methods (10+ variants), account management, player data, statistics, title data, leaderboards, characters, CloudScript, and additional functionality. Includes full method signatures, parameter tables, return types, and code examples.
```APIDOC
## Client API
### Description
Complete client-side API documentation with login methods (10+ variants), account management, player data, statistics, title data, leaderboards, characters, CloudScript, and additional functionality. Includes full method signatures, parameter tables, return types, and code examples.
### Key Sections
- Core Authentication (IsClientLoggedIn, ForgetAllCredentials)
- Login Methods (10+ authentication providers)
- Account Management (GetAccountInfo, GetPlayerProfile, etc.)
- Player Data (GetUserData, UpdateUserData, etc.)
- Statistics (GetPlayerStatistics, UpdatePlayerStatistics)
- Title Data (GetTitleData, GetCatalogItems, GetTime)
- Leaderboards (GetLeaderboard, GetLeaderboardAroundPlayer)
- Character Methods (GrantCharacterToUser, GetAllUsersCharacters)
- CloudScript (ExecuteCloudScript)
- Additional Methods
```
--------------------------------
### Initiate and Finalize File Uploads
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/api-reference/DataApi.md
Demonstrates the workflow for uploading files using PlayFab's Data API. This involves initiating the upload to get a URL, uploading the file content, and then finalizing the upload.
```javascript
// 1. Initiate upload
PlayFab.DataApi.InitiateFileUploads({
Entity: { Id: playFabId },
FileNames: ["profile_picture.png"]
}, function(result, error) {
if (error) return;
// 2. Upload file to provided URL
var uploadUrl = result.data.UploadDetails[0].UploadUrl;
// Use XMLHttpRequest or Fetch API to upload
fetch(uploadUrl, {
method: "PUT",
body: fileData,
headers: {
"Content-Type": "application/octet-stream"
}
});
// 3. Finalize upload
PlayFab.DataApi.FinalizeFileUploads({
Entity: { Id: playFabId },
FileNames: ["profile_picture.png"]
}, finalizeCallback);
});
```
--------------------------------
### Promise-based API Call Example
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/api-reference/PlayFabModule.md
Shows how to use Promises for asynchronous API calls. The `.then()` block handles successful responses, and the `.catch()` block handles errors.
```javascript
PlayFab.ClientApi.GetAccountInfo({})
.then(function(result) {
console.log("Account info:", result.data);
})
.catch(function(error) {
console.error("Error:", error.errorMessage);
});
```
--------------------------------
### Get User Data
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/api-reference/ClientApi.md
Retrieves custom player data for specific keys. Use this to fetch player-specific settings or progress.
```javascript
PlayFab.ClientApi.GetUserData(
{
Keys: ["LastLevel", "PlayerSettings"]
},
function(result, error) {
if (!error) {
var data = result.data.Data;
console.log("Last Level:", data.LastLevel.Value);
console.log("Last Updated:", data.LastLevel.LastUpdated);
}
}
);
```
--------------------------------
### Authentication API
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/MANIFEST.md
Entity token management and game server authentication API documentation covering GetEntityToken, ValidateEntityToken, AuthenticateGameServerWithCustomId, Delete, and ForgetAllCredentials methods. Includes entity types, authentication headers, error scenarios, best practices, and workflow examples.
```APIDOC
## Authentication API
### Description
Entity token management and game server authentication API documentation covering GetEntityToken, ValidateEntityToken, AuthenticateGameServerWithCustomId, Delete, and ForgetAllCredentials methods. Includes entity types, authentication headers, error scenarios, best practices, and workflow examples.
### Key Sections
- Core Methods (GetEntityToken, ValidateEntityToken, etc.)
- Method Signatures and Parameters
- Return Types and Responses
- Entity Types
- Authentication Headers
- Error Scenarios
- Best Practices
- Workflow Examples
- Source Files
```
--------------------------------
### Payment Endpoints
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/endpoints.md
Legacy endpoints for managing the purchase process, including starting, paying, confirming, and retrieving payment tokens.
```APIDOC
## POST /Client/StartPurchase
### Description
Start purchase (legacy)
### Method
POST
### Endpoint
/Client/StartPurchase
```
```APIDOC
## POST /Client/PayForPurchase
### Description
Pay for purchase (legacy)
### Method
POST
### Endpoint
/Client/PayForPurchase
```
```APIDOC
## POST /Client/ConfirmPurchase
### Description
Confirm purchase (legacy)
### Method
POST
### Endpoint
/Client/ConfirmPurchase
```
```APIDOC
## POST /Client/GetPaymentToken
### Description
Get payment token (legacy)
### Method
POST
### Endpoint
/Client/GetPaymentToken
```
```APIDOC
## POST /Client/ConsumeItem
### Description
Consume item (legacy)
### Method
POST
### Endpoint
/Client/ConsumeItem
```
--------------------------------
### Data API
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/MANIFEST.md
Entity-based data storage API documentation covering GetObjects, SetObjects, DeleteObjects, GetObject, and file management (GetFiles, InitiateFileUploads, FinalizeFileUploads, etc.). Includes concepts, method signatures, examples, and storage patterns.
```APIDOC
## Data API
### Description
Entity-based data storage API documentation covering GetObjects, SetObjects, DeleteObjects, GetObject, and file management (GetFiles, InitiateFileUploads, FinalizeFileUploads, etc.). Includes concepts, method signatures, examples, and storage patterns.
### Key Sections
- Core Concepts (Entities, Objects, Keys, Permissions)
- Method Overview
- GetObjects
- SetObjects
- DeleteObjects
- GetObject
- File Management Methods
- Data Storage Patterns
- Concurrency Control
- Large Data Handling
- Source Files
```
--------------------------------
### JavaScript PlayFab Custom Data Example
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/README.md
Demonstrates passing custom data with an API call, which can be accessed in the callback's result or error object.
```javascript
PlayFab.ClientApi.GetAccountInfo(
{},
function(result, error) {
// result.customData or error.customData will contain the value
},
{ userId: "12345", timestamp: Date.now() }
);
```
--------------------------------
### Login with Custom ID Example
Source: https://github.com/playfab/javascriptsdk/blob/master/JavaScriptGettingStarted.md
This snippet demonstrates how to log in a user using a custom ID. Ensure PlayFab.settings.titleId is set before making this call. The LoginCallback function will be invoked upon completion of the asynchronous request.
```javascript
var loginRequest = {
CustomId: "MyUniquePlayerId",
CreateAccount: true
};
PlayFabClientSDK.LoginWithCustomID(loginRequest, LoginCallback);
function LoginCallback(result, error) {
if (error) {
// Handle login error
console.error("Login failed:", error.errorMessage);
} else {
// Login successful, result contains player info
console.log("Login successful:", result);
}
}
```
--------------------------------
### Other Client Endpoints
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/endpoints.md
Miscellaneous client-side endpoints for ad placements, device info reporting, install attribution, content downloads, push notifications, and Photon authentication.
```APIDOC
## POST /Client/GetAdPlacements
### Description
Get ad placements
### Method
POST
### Endpoint
/Client/GetAdPlacements
```
```APIDOC
## POST /Client/ReportDeviceInfo
### Description
Report device info
### Method
POST
### Endpoint
/Client/ReportDeviceInfo
```
```APIDOC
## POST /Client/AttributeInstall
### Description
Attribute install
### Method
POST
### Endpoint
/Client/AttributeInstall
```
```APIDOC
## POST /Client/GetContentDownloadUrl
### Description
Get content download URL
### Method
POST
### Endpoint
/Client/GetContentDownloadUrl
```
```APIDOC
## POST /Client/AndroidDevicePushNotificationRegistration
### Description
Register for push
### Method
POST
### Endpoint
/Client/AndroidDevicePushNotificationRegistration
```
```APIDOC
## POST /Client/GetPhotonAuthenticationToken
### Description
Get Photon auth token
### Method
POST
### Endpoint
/Client/GetPhotonAuthenticationToken
```
--------------------------------
### Get Leaderboard
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/api-reference/ClientApi.md
Retrieves a leaderboard of ranked players based on a specified statistic. You can control the starting position and the number of results returned.
```javascript
PlayFab.ClientApi.GetLeaderboard(
{
StatisticName: "Score",
StartPosition: 0,
MaxResultsCount: 10
},
function(result, error) {
if (!error) {
result.data.Leaderboard.forEach(function(entry) {
console.log(entry.Position + ". " + (entry.DisplayName || entry.PlayFabId) + ": " + entry.Score);
});
}
}
);
```
--------------------------------
### Using Multiple APIs
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/api-reference/PlayFabModule.md
Demonstrates how to use both Client and Server APIs sequentially after a successful login.
```APIDOC
### Using Multiple APIs
```javascript
// After login, access client and server APIs
PlayFab.ClientApi.GetAccountInfo(
{},
function(result, error) {
if (!error) {
// Now use server API for admin operations
PlayFab.ServerApi.UpdatePlayerStatistics(
{
PlayFabId: result.data.PlayFabInfo.PlayFabId,
Statistics: [
{ StatisticName: "Level", Value: 5 }
]
},
function(serverResult, serverError) {
if (!serverError) {
console.log("Statistics updated");
}
}
);
}
}
);
```
```
--------------------------------
### Example InvalidPlayFabId Error Object
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/errors.md
An example error object for 'InvalidPlayFabId', indicating that the specified player account could not be found.
```javascript
{
code: 404,
error: "InvalidPlayFabId",
errorMessage: "The PlayFab user was not found"
}
```
--------------------------------
### Example 403 Forbidden Error Object
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/errors.md
Presents an example error object for a 403 Forbidden response, typically occurring when a user lacks the necessary permissions for an operation.
```javascript
{
code: 403,
status: "Forbidden",
error: "NotAuthorized",
errorMessage: "User does not have permission to call this method"
}
```
--------------------------------
### Project File Structure
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/INDEX.md
Overview of the directory structure for the PlayFab JavaScript SDK project.
```text
output/
├── INDEX.md (this file)
├── MANIFEST.md (documentation overview)
├── README.md (main entry point)
├── configuration.md
├── types.md
├── errors.md
├── endpoints.md
└── api-reference/
├── PlayFabModule.md
├── ClientApi.md
├── ServerApi.md
├── AuthenticationApi.md
└── DataApi.md
```
--------------------------------
### Global PlayFab Object Usage
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/README.md
Demonstrates how to configure the SDK settings and invoke various API methods using the global PlayFab object.
```APIDOC
## Global PlayFab Object
All SDK functionality is accessed through the global `PlayFab` object.
### Configuration
```javascript
PlayFab.settings.titleId = "YOUR_TITLE_ID";
```
### API Usage Examples
```javascript
// Client API
PlayFab.ClientApi.LoginWithPlayFab({...}, callback);
// Server API
PlayFab.ServerApi.UpdatePlayerStatistics({...}, callback);
// Data API
PlayFab.DataApi.SetObjects({...}, callback);
```
```
--------------------------------
### Include PlayFab Client SDK
Source: https://github.com/playfab/javascriptsdk/blob/master/TypeScriptGettingStarted.md
Load the PlayFab Client SDK from a local file or a CDN. Ensure your app.js file is correctly linked in your HTML.
```html
...
```
--------------------------------
### GetPlayerStatistics
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/api-reference/ServerApi.md
Retrieves a player's statistics. You can specify which statistics to retrieve or get all of them.
```APIDOC
## GetPlayerStatistics
### Description
Retrieves a player's statistics.
### Method
GET (Assumed, as it retrieves data)
### Endpoint
/ServerApi/GetPlayerStatistics (Assumed)
### Parameters
#### Query Parameters
- **PlayFabId** (string) - Required - The player's PlayFab ID
- **StatisticNames** (string[]) - Optional - Specific statistics to retrieve
### Request Example
```javascript
{
"PlayFabId": "PLAYER_ID",
"StatisticNames": ["Level", "WinCount"]
}
```
### Response
#### Success Response (200)
- **Statistics** (object[]) - Array of statistic objects
- **StatisticName** (string) - Name of the statistic
- **Value** (number) - Value of the statistic
#### Response Example
```json
{
"data": {
"Statistics": [
{ "StatisticName": "Level", "Value": 15 },
{ "StatisticName": "WinCount", "Value": 42 }
]
}
}
```
```
--------------------------------
### Legacy SDK References
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/api-reference/PlayFabModule.md
Direct access to API clients for backwards compatibility using global variables.
```APIDOC
## Legacy SDK References
For backwards compatibility, the following global variables provide direct access to API clients:
```javascript
// Legacy global references
PlayFabAdminSDK // Equivalent to PlayFab.AdminApi
PlayFabClientSDK // Equivalent to PlayFab.ClientApi
PlayFabServerSDK // Equivalent to PlayFab.ServerApi
PlayFabAuthenticationSDK // Equivalent to PlayFab.AuthenticationApi
PlayFabCloudScriptSDK // Equivalent to PlayFab.CloudScriptApi
PlayFabDataSDK // Equivalent to PlayFab.DataApi
PlayFabEconomySDK // Equivalent to PlayFab.EconomyApi
PlayFabEventsSDK // Equivalent to PlayFab.EventsApi
PlayFabExperimentationSDK // Equivalent to PlayFab.ExperimentationApi
PlayFabInsightsSDK // Equivalent to PlayFab.InsightsApi
PlayFabGroupsSDK // Equivalent to PlayFab.GroupsApi
PlayFabProgressionSDK // Equivalent to PlayFab.ProgressionApi
PlayFabLocalizationSDK // Equivalent to PlayFab.LocalizationApi
PlayFabMultiplayerSDK // Equivalent to PlayFab.MultiplayerApi
PlayFabProfilesSDK // Equivalent to PlayFab.ProfilesApi
PlayFabAddonSDK // Equivalent to PlayFab.AddonApi
```
```
--------------------------------
### GetUserData
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/api-reference/ServerApi.md
Retrieves a player's custom data. You can specify which data keys to retrieve or get all available keys.
```APIDOC
## GetUserData
### Description
Retrieves a player's custom data.
### Method
GET (Assumed, as it retrieves data)
### Endpoint
/ServerApi/GetUserData (Assumed)
### Parameters
#### Query Parameters
- **PlayFabId** (string) - Required - The player's PlayFab ID
- **Keys** (string[]) - Optional - Specific keys to retrieve
### Request Example
```javascript
{
"PlayFabId": "PLAYER_ID",
"Keys": ["LastLevelReached", "TotalPlayTime"]
}
```
### Response
#### Success Response (200)
- **Data** (object) - Key-value pairs of player data
- **Value** (string) - The value of the data field
#### Response Example
```json
{
"data": {
"Data": {
"LastLevelReached": { "Value": "10" },
"TotalPlayTime": { "Value": "3600" }
}
}
}
```
```
--------------------------------
### Using Client and Server APIs Together
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/api-reference/PlayFabModule.md
Demonstrates how to chain API calls, first retrieving account information using the Client API and then using that information to update player statistics via the Server API. This is useful for operations requiring both client and server contexts.
```javascript
// After login, access client and server APIs
PlayFab.ClientApi.GetAccountInfo(
{},
function(result, error) {
if (!error) {
// Now use server API for admin operations
PlayFab.ServerApi.UpdatePlayerStatistics(
{
PlayFabId: result.data.PlayFabInfo.PlayFabId,
Statistics: [
{ StatisticName: "Level", Value: 5 }
]
},
function(serverResult, serverError) {
if (!serverError) {
console.log("Statistics updated");
}
}
);
}
}
);
```
--------------------------------
### Get Player Statistics
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/api-reference/ServerApi.md
Retrieves a player's statistics from the server. You can fetch all statistics or specify particular ones by name.
```javascript
PlayFab.ServerApi.GetPlayerStatistics(
{
PlayFabId: "PLAYER_ID",
StatisticNames: ["Level", "WinCount"]
},
function(result, error) {
if (!error) {
result.data.Statistics.forEach(function(stat) {
console.log(stat.StatisticName + ": " + stat.Value);
});
}
}
);
```
--------------------------------
### List Entity Files
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/api-reference/DataApi.md
Lists all files available for a specified entity. The entity's ID and type must be provided.
```javascript
PlayFab.DataApi.GetFiles(
{
Entity: {
Id: playFabId,
Type: "title_player_account"
}
},
function(result, error) {
if (error) {
console.error("Failed to list files:", error.errorMessage);
return;
}
for (var fileName in result.data.Metadata) {
var metadata = result.data.Metadata[fileName];
console.log(fileName + ": " + metadata.Size + " bytes");
}
}
);
```
--------------------------------
### Get Entity Object
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/api-reference/DataApi.md
Retrieves a single JSON object for a specified entity. Ensure the EntityKey and ObjectName are correctly provided.
```javascript
PlayFab.DataApi.GetObject(
{
Entity: {
Id: characterId,
Type: "character"
},
ObjectName: "CharacterStats"
},
function(result, error) {
if (error) {
console.error("Failed:", error.errorMessage);
return;
}
var stats = JSON.parse(result.data.Data.DataAsJson);
console.log("Character stats:", stats);
}
);
```
--------------------------------
### Server Configuration
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/configuration.md
Configure the SDK for server-side operations using titleId, developerSecretKey, and productionServerUrl. Ensure developerSecretKey is never exposed to clients.
```javascript
PlayFab.settings.titleId = "YOUR_TITLE_ID";
PlayFab.settings.developerSecretKey = "YOUR_DEVELOPER_SECRET_KEY";
PlayFab.settings.productionServerUrl = ".playfabapi.com";
```
--------------------------------
### GetLeaderboard
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/api-reference/ClientApi.md
Retrieves a leaderboard of ranked players based on a specified statistic. Allows control over the starting position and the number of results.
```APIDOC
## GetLeaderboard
### Description
Retrieves a leaderboard of ranked players based on a specified statistic. Allows control over the starting position and the number of results.
### Method
GetLeaderboard
### Parameters
#### Request Body
- **StatisticName** (string) - Required - Name of the statistic to rank by
- **StartPosition** (number) - Optional - Position to start from (default: 0)
- **MaxResultsCount** (number) - Optional - Number of results to return (default: 10)
### Returns
```typescript
interface GetLeaderboardResult extends IPlayFabResultCommon {
Leaderboard?: PlayerLeaderboardEntry[];
}
interface PlayerLeaderboardEntry {
PlayFabId?: string;
Position: number;
Profile?: PlayerProfile;
Score: number;
DisplayName?: string;
}
```
### Request Example
```javascript
PlayFab.ClientApi.GetLeaderboard(
{
StatisticName: "Score",
StartPosition: 0,
MaxResultsCount: 10
},
function(result, error) {
if (!error) {
result.data.Leaderboard.forEach(function(entry) {
console.log(entry.Position + ". " + (entry.DisplayName || entry.PlayFabId) + ": " + entry.Score);
});
}
}
);
```
```
--------------------------------
### Get Player Statistics
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/api-reference/ClientApi.md
Retrieves the player's statistics by name. Use this to fetch game progress like score or level.
```javascript
PlayFab.ClientApi.GetPlayerStatistics(
{
StatisticNames: ["Level", "Score", "WinsCount"]
},
function(result, error) {
if (!error) {
result.data.Statistics.forEach(function(stat) {
console.log(stat.StatisticName + ": " + stat.Value);
});
}
}
);
```
--------------------------------
### Loading PlayFab Client SDK from CDN
Source: https://github.com/playfab/javascriptsdk/blob/master/JavaScriptGettingStarted.md
This HTML snippet demonstrates how to include the PlayFab Client SDK in your project by loading it directly from the PlayFab Content Delivery Network (CDN). This ensures you are using the latest version of the SDK.
```html
```
--------------------------------
### Get Player Data
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/api-reference/ServerApi.md
Retrieves a player's custom data. You can specify which data keys to fetch or retrieve all available keys.
```javascript
PlayFab.ServerApi.GetUserData(
{
PlayFabId: "PLAYER_ID",
Keys: ["LastLevelReached", "TotalPlayTime"]
},
function(result, error) {
if (!error) {
var data = result.data.Data;
console.log("Last Level:", data.LastLevelReached.Value);
}
}
);
```
--------------------------------
### Configure SDK and Login with Email
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/api-reference/PlayFabModule.md
This snippet shows how to configure the PlayFab SDK with a title ID and then log in a player using their email address and password. It includes basic error handling and logs the PlayFab ID upon successful login.
```javascript
// Configure the SDK
PlayFab.settings.titleId = "YOUR_TITLE_ID";
// Login with email
PlayFab.ClientApi.LoginWithEmailAddress(
{
Email: "player@example.com",
Password: "secure_password",
CreateAccount: true
},
function(result, error) {
if (error) {
console.error(PlayFab.GenerateErrorReport(error));
return;
}
console.log("Logged in successfully!");
console.log("PlayFabId:", result.data.PlayFabId);
}
);
```
--------------------------------
### Data API Endpoints - Object Storage
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/endpoints.md
Endpoints for managing object storage, including getting, setting, and deleting multiple or single objects.
```APIDOC
### Header
X-EntityToken: {entityToken}
## POST /Data/GetObjects
### Description
Get multiple objects
### Method
POST
### Endpoint
/Data/GetObjects
## POST /Data/GetObject
### Description
Get single object
### Method
POST
### Endpoint
/Data/GetObject
## POST /Data/SetObjects
### Description
Create/update objects
### Method
POST
### Endpoint
/Data/SetObjects
## POST /Data/DeleteObjects
### Description
Delete objects
### Method
POST
### Endpoint
/Data/DeleteObjects
```
--------------------------------
### LoginWithSteam
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/api-reference/ClientApi.md
Signs a user in using their Steam authentication ticket. This method can optionally create a new account if the Steam ID is not linked.
```APIDOC
## LoginWithSteam
### Description
Signs a user in using their Steam authentication ticket. This method can optionally create a new account if the Steam ID is not linked.
### Method
POST
### Endpoint
/Client/LoginWithSteam
### Parameters
#### Request Body
- **SteamTicket** (string) - Required - Steam authentication ticket
- **CreateAccount** (boolean) - Optional - Create account if Steam ID not linked
- **InfoRequestParameters** (GetPlayerCombinedInfoRequestParams) - Optional - Additional player data to retrieve
### Request Example
```json
{
"SteamTicket": "USER_STEAM_TICKET",
"CreateAccount": true
}
```
### Response
#### Success Response (200)
- **PlayFabId** (string) - The PlayFab ID of the logged-in player.
#### Response Example
```json
{
"data": {
"PlayFabId": "ABCDEF1234"
}
}
```
```
--------------------------------
### InitiateFileUploads
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/api-reference/DataApi.md
Initiates the file upload process for a specified entity. This is the first step in a multi-part file upload workflow.
```APIDOC
## InitiateFileUploads
Initiates file upload for an entity.
### Description
Initiates the file upload process for a specified entity. This is the first step in a multi-part file upload workflow.
### Method
POST (Assumed based on typical API patterns for initiating actions)
### Endpoint
/DataApi/InitiateFileUploads (Assumed based on SDK method name)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **Entity** (EntityKey) - Required - The entity for which to initiate file uploads.
- **FileNames** (string[]) - Required - An array of file names to initiate uploads for.
- **CustomTags** (object) - Optional - A set of custom tags to apply to the request.
### Request Example
```json
{
"Entity": {
"Id": "playFabId"
},
"FileNames": ["profile_picture.png"]
}
```
### Response
#### Success Response (200)
- **UploadDetails** (FileUploadDetails[]) - Optional - Details for each file upload, including the URL.
- **ProfileVersion** (number) - Optional - The version of the entity's profile after the operation.
#### Response Example
```json
{
"UploadDetails": [
{
"FileName": "profile_picture.png",
"UploadUrl": "https://example.com/upload/url"
}
],
"ProfileVersion": 123
}
```
```
--------------------------------
### Authentication API Endpoints
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/endpoints.md
Endpoints for managing entity tokens, including getting, validating, and deleting tokens, as well as authenticating game servers.
```APIDOC
## POST /Authentication/GetEntityToken
### Description
Get entity token
### Header
X-Authorization or X-SecretKey
### Method
POST
### Endpoint
/Authentication/GetEntityToken
## POST /Authentication/ValidateEntityToken
### Description
Validate entity token
### Header
X-SecretKey
### Method
POST
### Endpoint
/Authentication/ValidateEntityToken
## POST /Authentication/Delete
### Description
Delete game server entity
### Header
X-SecretKey
### Method
POST
### Endpoint
/Authentication/Delete
## POST /Authentication/AuthenticateGameServerWithCustomId
### Description
Authenticate game server
### Method
POST
### Endpoint
/Authentication/AuthenticateGameServerWithCustomId
```
--------------------------------
### LoginWithEmailAddress
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/api-reference/ClientApi.md
Allows a player to sign in using their email address and password. Note that account creation is not supported for this method.
```APIDOC
## LoginWithEmailAddress
### Description
Sign in with email and password.
### Signature
```typescript
LoginWithEmailAddress(
request: LoginWithEmailAddressRequest,
callback: ApiCallback,
customData?: any,
extraHeaders?: { [key: string]: string }
): Promise>
```
### Parameters
#### Request Body
```typescript
interface LoginWithEmailAddressRequest extends IPlayFabRequestCommon {
Email: string; // Email address associated with the account
Password: string; // Player's password
CreateAccount?: boolean; // Create account if email not found (not supported for email login)
InfoRequestParameters?: GetPlayerCombinedInfoRequestParams;
}
```
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| Email | string | Yes | Email address associated with the account |
| Password | string | Yes | Player's password |
| CreateAccount | boolean | No | Create account if email not found (not supported for email login) |
| InfoRequestParameters | GetPlayerCombinedInfoRequestParams | No | Additional player data to retrieve |
**Note:** Unlike other login methods, `CreateAccount` is not supported for email login. Use `RegisterPlayFabUser` to create email accounts.
### Returns
`Promise>` which resolves to a LoginResult object
### Example
```javascript
PlayFab.ClientApi.LoginWithEmailAddress(
{
Email: "player@example.com",
Password: "password123"
},
function(result, error) {
if (error) {
console.error(PlayFab.GenerateErrorReport(error));
return;
}
console.log("Logged in as:", result.data.PlayFabId);
}
);
```
```
--------------------------------
### Optional Field Pattern Example
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/types.md
Illustrates the common pattern of using optional fields in PlayFab interfaces, including required, optional, data, and timestamp fields.
```typescript
interface MyType {
RequiredField: string; // Always present
OptionalField?: string; // May be undefined
DataField?: any; // Serialized JSON
Timestamp?: string; // ISO 8601 format
}
```
--------------------------------
### Project Structure
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/README.md
Illustrates the directory structure of the PlayFab JavaScript SDK, including source code and TypeScript definitions.
```tree
javascriptsdk/
├── PlayFabSdk/
│ ├── package.json
│ ├── src/
│ │ ├── PlayFab/ (JavaScript implementations)
│ │ │ ├── PlayFabClientApi.js
│ │ │ ├── PlayFabServerApi.js
│ │ │ ├── PlayFabAuthenticationApi.js
│ │ │ ├── PlayFabDataApi.js
│ │ │ └── ... (other API modules)
│ │ └── Typings/ (TypeScript definitions)
│ │ └── PlayFab/
│ │ ├── Playfab.d.ts
│ │ ├── PlayFabClientApi.d.ts
│ │ ├── PlayFabServerApi.d.ts
│ │ └── ... (other type definitions)
│ └── README.md
```
--------------------------------
### Example 401 Unauthorized Error Object
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/errors.md
Illustrates a typical error object structure for a 401 Unauthorized response, indicating an invalid or expired session ticket.
```javascript
{
code: 401,
status: "Unauthorized",
error: "InvalidSession",
errorMessage: "Player session ticket is not valid"
}
```
--------------------------------
### Handle Configuration Validation Errors
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/errors.md
Catch exceptions for missing PlayFab configurations like 'titleId' or 'developerSecretKey' and set them.
```javascript
try {
PlayFab.ServerApi.UpdatePlayerStatistics({...});
} catch (e) {
if (e.indexOf("developerSecretKey") !== -1) {
PlayFab.settings.developerSecretKey = "YOUR_SECRET_KEY";
}
}
```
--------------------------------
### Get Leaderboard Around Player
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/api-reference/ClientApi.md
Retrieves a leaderboard centered around the current player or a specified player. You can define the number of results to fetch above and below the target player.
```typescript
PlayFab.ClientApi.GetLeaderboardAroundPlayer({
StatisticName: "Rank",
MaxResultsCount: 5
});
```
--------------------------------
### HTML Structure for PlayFab Integration
Source: https://github.com/playfab/javascriptsdk/blob/master/JavaScriptGettingStarted.md
This HTML file sets up the user interface for making a PlayFab API call, including input fields for Title ID and Custom ID, a button to trigger the login, and a textarea for displaying results. It also includes script tags to load the PlayFab Client SDK and your custom JavaScript file.
```html
PlayFab JavaScript Unit Tests
PlayFab Getting Started Guide
TitleID:
CustomID:
Result:
```
--------------------------------
### Get Account Info
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/api-reference/ClientApi.md
Retrieves the user's PlayFab account information. Use this to access details like username, creation date, and linked accounts.
```javascript
PlayFab.ClientApi.GetAccountInfo(
{},
function(result, error) {
if (error) {
console.error("Failed to get account info:", error.errorMessage);
return;
}
var accountInfo = result.data.AccountInfo;
console.log("Account created:", accountInfo.TitleInfo.Created);
console.log("Username:", accountInfo.Username);
}
);
```
--------------------------------
### Global PlayFab Object Usage
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/README.md
Demonstrates how to access and use the global PlayFab object for SDK configuration and API calls.
```javascript
// Configure
PlayFab.settings.titleId = "YOUR_TITLE_ID";
// Use APIs
PlayFab.ClientApi.LoginWithPlayFab({...}, callback);
PlayFab.ServerApi.UpdatePlayerStatistics({...}, callback);
PlayFab.DataApi.SetObjects({...}, callback);
```
--------------------------------
### Get Shared Group Data
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/api-reference/ServerApi.md
Retrieves data associated with a specific shared group. You can optionally request specific keys or include the list of group members.
```javascript
PlayFab.ServerApi.GetSharedGroupData({
SharedGroupId: "guild_12345",
Keys: ["Name", "Level"],
GetMembers: true
}, function(result, error) {
if (!error) {
console.log(JSON.stringify(result.data));
}
});
```
--------------------------------
### Get Title Data
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/api-reference/ClientApi.md
Retrieves title-wide read-only data. You can specify an array of keys to fetch specific data, or omit the Keys parameter to retrieve all title data.
```javascript
PlayFab.ClientApi.GetTitleData(
{
Keys: ["GameVersion", "LevelDefinitions"]
},
function(result, error) {
if (!error) {
console.log("Game Version:", result.data.Data.GameVersion.Value);
}
}
);
```
--------------------------------
### Optional PlayFab SDK Configuration
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/README.md
Configures optional settings like global header injection for custom headers or a developer secret key for server-only authentication.
```javascript
PlayFab.settings.GlobalHeaderInjection = {
"X-Custom-Header": "value"
};
PlayFab.settings.developerSecretKey = "SECRET_KEY"; // Server only
```
--------------------------------
### Client API: LoginWithPlayFab
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/README.md
Logs a player into PlayFab using their username and password. This is a fundamental step for client-side authentication.
```APIDOC
## Client API: LoginWithPlayFab
### Description
Logs a player into PlayFab using their username and password.
### Method
POST (Implied by SDK function call)
### Endpoint
(Not explicitly defined in source, inferred from SDK usage)
### Parameters
#### Request Body
- **Username** (string) - Required - The player's username.
- **Password** (string) - Required - The player's password.
### Request Example
```json
{
"Username": "player",
"Password": "pass123"
}
```
### Response
#### Success Response
- **data** (object) - Contains player session information, including `PlayFabId`.
#### Response Example
```json
{
"data": {
"PlayFabId": "some_playfab_id"
}
}
```
```
--------------------------------
### Get Player Inventory and Virtual Currency
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/api-reference/ServerApi.md
Retrieves a player's inventory items and their current virtual currency balances. Useful for displaying player assets and currency.
```javascript
PlayFab.ServerApi.GetUserInventory(
{
PlayFabId: "PLAYER_ID"
},
function(result, error) {
if (!error) {
var currencies = result.data.VirtualCurrency;
for (var key in currencies) {
console.log(key + ": " + currencies[key]);
}
}
}
);
```
--------------------------------
### Get Catalog Items (Legacy)
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/api-reference/ClientApi.md
Retrieves the title's item catalog using the Legacy Economy API. Note: Use PlayFab Economy v2 for new implementations.
```typescript
PlayFab.ClientApi.GetCatalogItems({
CatalogVersion: "someCatalogVersion"
});
```
--------------------------------
### Access SDK Version Information
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/configuration.md
Retrieve the current SDK version and build identifier at runtime. This is useful for debugging and compatibility checks.
```javascript
// Current SDK version
PlayFab.sdkVersion = "1.217.260605"
// Build identifier
PlayFab.buildIdentifier = "adobuild_javascriptsdk_114"
```
--------------------------------
### ISettings Interface
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/types.md
Specifies the configuration settings required for initializing the PlayFab SDK.
```typescript
interface ISettings {
titleId: string;
developerSecretKey: string;
GlobalHeaderInjection?: { [key: string]: string };
productionServerUrl: string;
}
```
--------------------------------
### Get Player Profile
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/api-reference/ClientApi.md
Retrieves a player's profile information, including display name, creation date, and avatar URL. Specify ProfileConstraints to control which sections are returned.
```javascript
PlayFab.ClientApi.GetPlayerProfile(
{
ProfileConstraints: {
ShowDisplayName: true,
ShowStatistics: true,
ShowAvatarUrl: true,
ShowCreated: true,
ShowLastLogin: true
}
},
function(result, error) {
if (!error) {
var profile = result.data.PlayerProfile;
console.log("Display Name:", profile.DisplayName);
console.log("Created:", profile.Created);
}
}
);
```
--------------------------------
### Generating PlayFab Error Report
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/api-reference/PlayFabModule.md
Provides an example of using the GenerateErrorReport method to create a human-readable error message from a PlayFab error object, useful for debugging API call failures.
```javascript
PlayFab.ClientApi.LoginWithPlayFab(
{ Username: "invalid", Password: "" },
function(result, error) {
if (error) {
var errorReport = PlayFab.GenerateErrorReport(error);
console.log(errorReport);
// Output:
// Invalid username or password
// Password: Password must be specified
}
}
);
```
--------------------------------
### SetObjects - Player Settings Pattern
Source: https://github.com/playfab/javascriptsdk/blob/master/_autodocs/api-reference/DataApi.md
Stores player-specific settings such as theme, language, and notification preferences.
```APIDOC
## SetObjects - Player Settings Pattern
Stores player-specific settings such as theme, language, and notification preferences.
### Description
This pattern demonstrates how to save player settings like UI theme, language, and notification preferences using the SetObjects API.
### Method
POST (Assumed based on typical API patterns for setting data)
### Endpoint
/DataApi/SetObjects (Assumed based on SDK method name)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **Entity** (EntityKey) - Required - The entity for which to set objects. Typically the player's ID.
- **Objects** (object[]) - Required - An array of objects to set. Each object contains an ObjectName and DataObject.
- **ObjectName** (string) - Required - The name of the object to store (e.g., "PlayerSettings").
- **DataObject** (object) - Required - The actual data to store, represented as a JSON object.
### Request Example
```json
{
"Entity": {
"Id": "playerId"
},
"Objects": [
{
"ObjectName": "PlayerSettings",
"DataObject": {
"theme": "dark",
"language": "en",
"notifications": {
"email": true,
"push": false,
"sms": false
}
}
}
]
}
```
### Response
#### Success Response (200)
(Success response details not explicitly provided for this pattern, but implies successful data storage.)
#### Response Example
(No example provided in source.)
```