### Install Poki Phaser Plugin Source: https://sdk.poki.com/phaser Install the Poki Phaser Plugin using npm or yarn. ```bash $ npm install --save-dev @poki/phaser-3 # or $ yarn add --dev @poki/phaser-3 ``` -------------------------------- ### Measure Level Start (Unity) Source: https://sdk.poki.com/game-events Use PokiUnitySDK.Instance.measure to track the start of a game level in Unity projects. ```csharp PokiUnitySDK.Instance.measure("level", "1", "start"); ``` -------------------------------- ### Measure Level Start (HTML5 - Alternative) Source: https://sdk.poki.com/game-events An alternative syntax for PokiSDK.measure to track the start of a game level in HTML5 projects. ```javascript PokiSDK.measure("level", "1", "start") ``` -------------------------------- ### Fetch Increment Counter Example Source: https://sdk.poki.com/auds Example of how to make a fetch request to increment a counter value. ```javascript fetch('https://auds.poki.io/v0/use-your-poki-game-id/userdata/tests/ce702oq1gkcvlv1tmlgg/_increment?key=play-count', { method: 'POST' }) .then(response => response.text()) .then(result => console.log(result)) .catch(error => console.log('error', error)); ``` -------------------------------- ### Initialize PokiSDK Source: https://sdk.poki.com/html5 Initialize the SDK at the start of your game. This promise-based function logs success or failure. ```javascript PokiSDK.init().then(() => { console.log("Poki SDK successfully initialized"); // fire your function to continue to game }).catch(() => { console.log("Initialized, something went wrong, load you game anyway"); // fire your function to continue to game }); ``` -------------------------------- ### Handle Commercial Break Start and Success Source: https://sdk.poki.com/defold This method allows for more granular control by handling both the start and success states of a commercial break. ```lua poki_sdk.commercial_break(function(self, status) if status == poki_sdk.COMMERCIAL_BREAK_START then -- gameplay stops elseif status == poki_sdk.COMMERCIAL_BREAK_SUCCESS then -- fire your function to continue the game end end) ``` -------------------------------- ### Measure Level Start (Poki JS SDK) Source: https://sdk.poki.com/game-events Use poki_sdk.measure to track the start of a game level using the Poki JavaScript SDK. ```javascript poki_sdk.measure("level", "1", "start") ``` -------------------------------- ### Example Fetch Request to Create Userdata Source: https://sdk.poki.com/auds This JavaScript example demonstrates how to construct and send a POST request to create userdata using the Fetch API. Ensure you store the returned secret. ```JavaScript const body = { data: { tiles: [1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0], note: 'data in userdata is freeform, can be anything.' }, values: { levelname: 'Test level', type: 'arena-1v1', note: "'values' can only be key/value pairs where values can only be string, number, or boolean" } }; const requestOptions = { method: 'POST', body: JSON.stringify(body), }; fetch('https://auds.poki.io/v0/use-your-poki-game-id/userdata/tests', requestOptions) .then(response => response.text()) .then(result => console.log(result)) .catch(error => console.log('error', error)); ``` -------------------------------- ### Example Vote Request Source: https://sdk.poki.com/auds Example of how to send a POST request to the vote endpoint using the fetch API. ```JavaScript fetch('https://auds.poki.io/v0/use-your-poki-game-id/userdata/tests/ce702oq1gkcvlv1tmlgg/_vote?key=up-vote', { method: 'POST' }) .then(response => response.text()) .then(result => console.log(result)) .catch(error => console.log('error', error)); ``` -------------------------------- ### Measure Level Start (Phaser 3) Source: https://sdk.poki.com/game-events Use the Poki plugin in Phaser 3 to track the start of a game level. ```javascript const poki = scene.plugins.get('poki') poki.measure('level', '1', 'start') ``` -------------------------------- ### Measure Level Start (Generic Function) Source: https://sdk.poki.com/game-events Use the generic poki_measure function to track the start of a game level. ```javascript poki_measure("level", "1", "start"); ``` -------------------------------- ### gameplayStart and gameplayStop Source: https://sdk.poki.com/phaser Manually fire gameplay start and stop events. Useful for games that do not use multiple scenes for gameplay. ```APIDOC ## Fire SDK events manually ### Description If your game doesn’t use multiple scenes for gameplay, you can manually call the events like so. Use `gameplayStart()` to signal the beginning of gameplay and `gameplayStop()` to signal its end. ### Method `poki.gameplayStart()` `poki.gameplayStop()` ### Request Example ```javascript const poki = scene.plugins.get('poki') // get the plugin from the Phaser PluginManager poki.gameplayStart() // ... start gameplay ... scene.on('player_died', () => { poki.gameplayStop() }) ``` ``` -------------------------------- ### Implement Gameplay Events Source: https://sdk.poki.com/html5 Use gameplayStart and gameplayStop to track user engagement, such as level starts, pauses, and game over. ```javascript // first level loads, player clicks anywhere PokiSDK.gameplayStart(); // player is playing // player loses round PokiSDK.gameplayStop(); // game over screen pops up ``` -------------------------------- ### Unity SDK Integration Example Source: https://sdk.poki.com/sdk-documentation Demonstrates the full lifecycle of a game using the Poki SDK in Unity. Covers initialization, loading, gameplay start/stop, and ad break handling for rewards and progression. ```csharp using UnityEngine; public class Game : MonoBehaviour { public void Awake () { // Initialize SDK PokiUnitySDK.Instance.init(); StartLoading(); } public void StartLoading() { // Load the game! // [...loading logic goes here...] // When all files are loaded OpenMainMenu(); } public void OpenMainMenu(){ gamePause(); // we mute audio and stop gameplay here if(!PokiUnitySDK.Instance.adsBlocked()){ PokiUnitySDK.Instance.commercialBreakCallBack = StartGame; // after the commercial break we trigger StartGame PokiUnitySDK.Instance.commercialBreak(); }else StartGame(); } public void StartGame() { Debug.Log("Starting a new round!"); PokiUnitySDK.Instance.gameplayStart(); //[... do all the gameplay stuff]; // We died but we can get one more shot by watching a rewarded video if(PokiUnitySDK.Instance.adsBlocked()){ //hide the rewarded video }else{ PokiUnitySDK.Instance.rewardedBreakCallBack = RevivePlayer; PokiUnitySDK.Instance.rewardedBreak(); } // ahh we died again, let’s restart RestartLevel(); } public void RevivePlayer(bool withReward){ if(withReward){ Debug.Log("Revive!"); //resume game }else{ //exit level } } public void RestartLevel(){ // we failed the level, let’s close this gameplay session and trigger a break gamePause(); PokiUnitySDK.Instance.gameplayStop(); // we closed the gameplay now let’s trigger the break if(!PokiUnitySDK.Instance.adsBlocked()){ PokiUnitySDK.Instance.commercialBreakCallBack = StartGame; // after the commercial break we trigger StartGame PokiUnitySDK.Instance.commercialBreak(); }else StartGame(); } public void gamePause() { Debug.Log("Starting break"); //muteMusic(); //pauseGamePlay(); } public void continueGame() { Debug.Log("Break completed"); //unMuteMusic(); //resumeGameplay(); } } ``` -------------------------------- ### Example Response for Userdata by ID Source: https://sdk.poki.com/auds This is an example JSON response when successfully fetching userdata by ID, showing the structure of the returned data including metadata and values. ```json { "id": "ce702oq1gkcvlv1tmlgg", "meta": { "revision": 1, "created_at": "2022-12-05T14:34:11.677983Z", "expires_at": "2023-12-05T14:37:02.733083Z", "expires_in": 31536000 }, "values": { "levelname": "Test level", "note": "'values' can only be key/value pairs where values can only be string, number, or boolean", "type": "arena-1v1" }, "data": { "note": "data in userdata is freeform, can be anything.", "tiles": [1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0] } } ``` -------------------------------- ### Example Vote Response Source: https://sdk.poki.com/auds Example JSON response after successfully voting on a value. Note that only 'updated_at' changes, not 'revision'. ```JSON { "id": "ce702oq1gkcvlv1tmlgg", "meta": { "revision": 1, "created_at": "2022-12-05T14:34:11.677983Z", "updated_at": "2022-12-05T14:41:58.223397772Z", "expires_at": "2023-12-05T14:41:58.223397772Z", "expires_in": 31536000 }, "values": { "levelname": "Test level", "up-vote": 33 } } ``` -------------------------------- ### Start and Stop Gameplay Events Source: https://sdk.poki.com/godot Use `gameplayStart()` when the player begins playing and `gameplayStop()` when they stop, such as at the end of a round or when pausing. ```javascript # first level loads, player clicks anywhere PokiSDK.gameplayStart() # player is playing # player loses round PokiSDK.gameplayStop() # game over screen pops up ``` -------------------------------- ### Implement Gameplay Events Source: https://sdk.poki.com/cocos Use CCPokiSDK.gameplayStart() when users begin playing (e.g., level start, unpause) and CCPokiSDK.gameplayStop() when they are not playing (e.g., level finish, game over, pause). ```javascript // first level loads, player clicks anywhere CCPokiSDK.gameplayStart() // player is playing // player loses round CCPokiSDK.gameplayStop() // game over screen pops up ``` -------------------------------- ### Measure Level Start (Cocos) Source: https://sdk.poki.com/game-events Use CCPokiSDK.measure to track the start of a game level in Cocos projects. ```javascript CCPokiSDK.measure('level', '1', 'start') ``` -------------------------------- ### Example Response for Userdata Creation Source: https://sdk.poki.com/auds The response includes an 'id' and a 'secret'. The 'secret' is crucial for future updates and is only provided upon creation. ```JSON { "id": "ce702oq1gkcvlv1tmlgg", "secret": "Qn8iO6bQVlGyVPkJhoi4oHwufb6GWgpgyedP5cO3fB39rzwTJZwg7N2n7GbLU3aG", "meta": { "revision": 1, "created_at": "2022-12-05T14:34:11.67798351Z", "expires_at": "2023-12-05T14:34:11.67798351Z", "expires_in": 31536000 }, "values": { "levelname": "Test level", "note": "'values' can only be key/value pairs where values can only be string, number, or boolean", "type": "arena-1v1" } } ``` -------------------------------- ### Fetch DELETE Userdata by ID Example Source: https://sdk.poki.com/auds Example of how to make a fetch request to delete userdata by ID using the Authorization header. ```javascript const body = { secret: 'Qn8iO6bQVlGyVPkJhoi4oHwufb6GWgpgyedP5cO3fB39rzwTJZwg7N2n7GbLU3aG', }; const requestOptions = { method: 'DELETE', body: JSON.stringify(body), // Or instead of the body: // headers: { // 'Authorization': 'AdminToken ', // } }; fetch('https://auds.poki.io/v0/use-your-poki-game-id/userdata/tests/ce702oq1gkcvlv1tmlgg', requestOptions) .then(response => response.text()) .then(result => console.log(result)) .catch(error => console.log('error', error)); ``` -------------------------------- ### Track Level Start Event Source: https://sdk.poki.com/game-events Use this snippet to log the start of a specific level. Ensure the category, level identifier, and action are clearly defined. ```javascript PokiSDK.measure('level', '1', 'start'); ``` -------------------------------- ### Run Code on PokiSDK Initialization Source: https://sdk.poki.com/phaser Execute a function once the PokiSDK is fully initialized or immediately if it's already ready. Get the plugin from the Phaser PluginManager first. ```javascript const poki = scene.plugins.get('poki') // get the plugin from the Phaser PluginManager poki.runWhenInitialized((poki) => { // This is called after the PokiSDK is fully initialized, or immediately if // the PokiSDK has already been initialized. }) ``` -------------------------------- ### Clone Poki SDK Repository Source: https://sdk.poki.com/cocos Clone the Poki SDK repository from GitHub to get the source code. ```bash git clone https://github.com/vkbsb/cocos-creator-poki-sdk ``` -------------------------------- ### Example Response for Userdata Update Source: https://sdk.poki.com/auds A successful response after updating userdata, showing the updated values and metadata. ```json { "id": "ce702oq1gkcvlv1tmlgg", "meta": { "revision": 2, "created_at": "2022-12-05T14:34:11.677983Z", "updated_at": "2022-12-05T14:41:58.223397772Z", "expires_at": "2023-12-05T14:41:58.223397772Z", "expires_in": 31536000 }, "values": { "levelname": "Test level (edited)", "type": "arena-1v1" } } ``` -------------------------------- ### Example Request to Fetch Userdata Source: https://sdk.poki.com/auds This JavaScript snippet demonstrates how to make a fetch request to the userdata by ID endpoint and log the response or any errors. ```javascript fetch('https://auds.poki.io/v0/use-your-poki-game-id/userdata/tests/ce702oq1gkcvlv1tmlgg') .then(response => response.text()) .then(result => console.log(result)) .catch(error => console.log('error', error)); ``` -------------------------------- ### Example Response for Increment Counter Source: https://sdk.poki.com/auds Shows the structure of a successful response after incrementing a counter. ```JSON { "id": "ce702oq1gkcvlv1tmlgg", "meta": { "revision": 1, "created_at": "2022-12-05T14:34:11.677983Z", "updated_at": "2022-12-05T14:41:58.223397772Z", "expires_at": "2023-12-05T14:41:58.223397772Z", "expires_in": 31536000 }, "values": { "levelname": "Test level", "play-count": 42 } } ``` -------------------------------- ### Example Response for List Userdata Source: https://sdk.poki.com/auds This JSON response illustrates the structure when listing userdata, including the total count and an array of items, each with its ID, metadata, and values. ```json { "total": 1, "items": [ { "id": "ce702oq1gkcvlv1tmlgg", "meta": { "revision": 1, "created_at": "2022-12-05T14:34:11.677983Z", "expires_at": "2023-12-05T14:34:11.677983Z", "expires_in": 31536000 }, "values": { "levelname": "Test level", "note": "'values' can only be key/value pairs where values can only be string, number, or boolean", "type": "arena-1v1" } } ] } ``` -------------------------------- ### Example Request to List Userdata Source: https://sdk.poki.com/auds This JavaScript snippet shows how to request a list of userdata entries, filtered by type and sorted by key. It logs the result or any errors encountered. ```javascript fetch('https://auds.poki.io/v0/use-your-poki-game-id/userdata/tests?q=type:arena-1v1') .then(response => response.text()) .then(result => console.log(result)) .catch(error => console.log('error', error)); ``` -------------------------------- ### Create Shareable URLs and Read URL Parameters Source: https://sdk.poki.com/phaser Generate a shareable URL with custom data and retrieve URL parameters using the PokiSDK. Get the plugin from the Phaser PluginManager first. ```javascript const poki = scene.plugins.get('poki') poki.shareableURL({ id: 'myid', type: 'mytype', score: 28 }).then((url) => { console.log(url) }) const id = poki.getURLParam('id') ``` -------------------------------- ### Replace index.html onload script Source: https://sdk.poki.com/gamemaker Replace the default window.onload script with this code to integrate the PokiSDK. This ensures the SDK is initialized before GameMaker starts. ```html ``` ```html ``` -------------------------------- ### Get Authentication Token Source: https://sdk.poki.com/gdevelop Obtain a token for backend verification when the player initiates an account-dependent action. The token expires in 1 minute and should not be stored. ```GDevelop Events Condition: [Player starts an account-backed action] Action: Poki Games SDK > Get token Parameter: PlayerToken ``` -------------------------------- ### Start and Stop Gameplay Events Source: https://sdk.poki.com/defold Call `poki_sdk.gameplay_start()` when the player begins interacting with the game or unpauses. Call `poki_sdk.gameplay_stop()` when the player is not actively playing, such as after a level finish, game over, or pausing. ```lua -- player interacts with the game poki_sdk.gameplay_start() -- player is playing -- player loses round poki_sdk.gameplay_stop() -- game over screen pops up ``` -------------------------------- ### Get User Information Source: https://sdk.poki.com/gdevelop Retrieve current user details when the scene starts or the account UI opens. The PlayerUser structure contains username and avatar URL. ```GDevelop Events Condition: [Scene starts or account UI opens] Action: Poki Games SDK > Get user Parameter: PlayerUser ``` ```GDevelop Events PlayerUser.username PlayerUser.avatarUrl ``` -------------------------------- ### HTML SDK Integration Example Source: https://sdk.poki.com/sdk-documentation Demonstrates the full lifecycle of a game using the Poki SDK in an HTML environment. Includes initialization, loading, gameplay start/stop, and ad break handling for progression and rewards. ```javascript function init() { PokiSDK.init().then(startLoading) // remove this line in your production build PokiSDK.setDebug(true); }; function startLoading() { // Load the game! // When all files are loaded loadingComplete(); }; function loadingComplete() { // We're done loading! PokiSDK.gameLoadingFinished(); // Lets start playing after the initial commercial break PokiSDK.commercialBreak().then(() => { PokiSDK.gameplayStart(); startGame(); }); }; function startGame() { console.log("Starting a new round!"); // .. user plays for a while // We died! onDeath(); }; function onDeath() { // Lets run the on death code: but we can get one more shot by watching a rewarded video PokiSDK.gameplayStop(); if(canRevive){ // we have the option to revive! (usually this is on a button in the game over screen) PokiSDK.rewardedBreak(() => { // if the ad loads and will show pause the game and mute the menu music pauseGame(); }).then((withReward) => { // when the ad is completed, skipped or did not play we run this code if (withReward) { // withReward is a boolean that you receive that indicates whether a user actually finished the video correctly console.log("Revive!"); PokiSDK.gameplayStart(); canRevive = false; revive(); } else{ // User skipped the video, not entitled to a reward restartLevel() } }); } else { // if we can't revive we just restart restartLevel() } } function restartLevel() { // we failed the level, let’s close this gameplay session and trigger a break PokiSDK.gameplayStop(); // we closed the gameplay now let’s trigger the break PokiSDK.commercialBreak(() => { // if we actually start showing an ad, pause the game ( this function also mutes the game music) pauseGame(); }).then(() => { // when the ad is completed, or we didn't show an ad run this code PokiSDK.gameplayStart(); unMuteSound(); startLevel(); }); }; function pauseGame() { console.log("Starting break"); muteAudio(); disableKeyboardInput(); }; function unPauseGame() { console.log("Break completed"); unMuteAudio(); enableKeyboardInput(); }; ``` -------------------------------- ### Manually Fire SDK Gameplay Events Source: https://sdk.poki.com/phaser Manually trigger gameplay start and stop events if your game does not use multiple scenes. Get the plugin from the Phaser PluginManager first. ```javascript const poki = scene.plugins.get('poki') // get the plugin from the Phaser PluginManager poki.gameplayStart() // ... start gameplay ... scene.on('player_died', () => { poki.gameplayStop() }) ``` -------------------------------- ### Initialize PokiSDK in Unity Source: https://sdk.poki.com/unity Call this method as early as possible in your application to initialize the PokiSDK. ```csharp PokiUnitySDK.Instance.init(); ``` -------------------------------- ### Wait for Poki SDK Initialization and Signal Game Loading Finished Source: https://sdk.poki.com/gdevelop Use the 'Poki SDK is ready' condition to ensure the SDK is initialized before proceeding. Then, use the 'Game loading finished' action when your game is ready to display the main menu or first playable screen. ```GDevelop Events Condition: Poki Games SDK > Poki SDK is ready Action: Poki Games SDK > Game loading finished ``` -------------------------------- ### runWhenInitialized Source: https://sdk.poki.com/phaser Executes a callback function once the PokiSDK has been fully initialized. If the SDK is already initialized, the function runs immediately. ```APIDOC ## runWhenInitialized ### Description To run code only when the PokiSDK is initialized, you can use the `runWhenInitialized` interface. This function is called after the PokiSDK is fully initialized, or immediately if the PokiSDK has already been initialized. ### Method `poki.runWhenInitialized(callback)` ### Parameters #### Arguments - **callback** (function) - A function to be executed after initialization. ### Request Example ```javascript const poki = scene.plugins.get('poki') // get the plugin from the Phaser PluginManager poki.runWhenInitialized((poki) => { // This is called after the PokiSDK is fully initialized, or immediately if // the PokiSDK has already been initialized. }) ``` ``` -------------------------------- ### Signal Gameplay Started and Stopped Events Source: https://sdk.poki.com/gdevelop Use the 'Gameplay started' action to indicate when users are actively playing (e.g., level start, unpause). Use the 'Gameplay stopped' action when users are not playing (e.g., level finish, game over, pause, quit to menu). ```GDevelop Events Condition: [Player clicks or taps to start] Action: Poki Games SDK > Gameplay started ``` ```GDevelop Events Condition: [Player dies / level ends / game pauses] Action: Poki Games SDK > Gameplay stopped ``` -------------------------------- ### Example Fetch Request to Update Userdata Source: https://sdk.poki.com/auds An example using the fetch API to send a POST request to update userdata. The secret can be included in the request body or via the Authorization header. ```javascript const body = { secret: 'Qn8iO6bQVlGyVPkJhoi4oHwufb6GWgpgyedP5cO3fB39rzwTJZwg7N2n7GbLU3aG', data: { tiles: [1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1] }, values: { levelname: 'Test level (edited)', type: 'arena-1v1' } }; const requestOptions = { method: 'POST', body: JSON.stringify(body), // Or instead of the secret in the body: // headers: { // 'Authorization': 'AdminToken ', // } }; fetch('https://auds.poki.io/v0/use-your-poki-game-id/userdata/tests/ce702oq1gkcvlv1tmlgg', requestOptions) .then(response => response.text()) .then(result => console.log(result)) .catch(error => console.log('error', error)); ``` -------------------------------- ### Initiate User Login Source: https://sdk.poki.com/gdevelop Prompt the player to log in from a click or tap event. A successful login may refresh the page, requiring a subsequent check of user status. ```GDevelop Events Condition: [Player clicks "Log in"] Action: Poki Games SDK > Login ``` -------------------------------- ### Get URL Parameter Source: https://sdk.poki.com/cocos Retrieves the value of a specific parameter from the current URL. ```APIDOC ## CCPokiSDK.getURLParam(key) ### Description Extracts the value of a specified URL parameter from the current page's query string. ### Method `sync` ### Endpoint N/A (SDK Method) ### Parameters - **key** (string) - The name of the URL parameter to retrieve. ### Request Example ```javascript const id = CCPokiSDK.getURLParam("id"); console.log(id); ``` ### Response #### Success Response - **value** (string | null) - The value of the specified URL parameter, or null if not found. #### Response Example ``` "myid" ``` ``` -------------------------------- ### Implement Commercial Break Callback and Trigger Source: https://sdk.poki.com/unity Set up a callback function to be executed when a commercial break finishes and then trigger the commercial break. ```csharp public void commercialBreakComplete(){ Debug.Log("Commercial break finished"); } //Set the complete callback PokiUnitySDK.Instance.commercialBreakCallBack = commercialBreakComplete; PokiUnitySDK.Instance.commercialBreak(); ``` -------------------------------- ### Configure Phaser Game with Poki Plugin Source: https://sdk.poki.com/phaser Add the PokiPlugin to your Phaser game configuration. Ensure the 'poki' key is set and 'start' is true. Configure loading and gameplay scene keys, and optionally enable autoCommercialBreak. ```javascript import { PokiPlugin } from '@poki/phaser-3' // ... const config = { // ... plugins: { global: [ { plugin: PokiPlugin, key: 'poki', start: true, // must be true, in order to load data: { // This must be the key/name of your loading scene loadingSceneKey: 'LoadingScene', // This must be the key/name of your game (gameplay) scene gameplaySceneKey: 'PlayScene', // This will always request a commercialBreak when gameplay starts, // set to false to disable this behaviour (recommended to have true, // see Poki SDK docs for more details). autoCommercialBreak: true } } ] } } // ... var game = new Phaser.Game(config) ``` -------------------------------- ### PokiSDK.login() Source: https://sdk.poki.com/godot Initiates the login process for a player. This should only be called in response to direct player interaction. A successful login may refresh the page. ```APIDOC ## PokiSDK.login() ### Description Initiates the login process for a player. This should only be called in response to direct player interaction. A successful login may refresh the page. ### Method Call ### Parameters None ### Signals Emitted - `login_done()`: Emitted when the login process is successfully completed. - `login_failed(error)`: Emitted if the login process fails (e.g., user closes the panel, timeout). ``` -------------------------------- ### User Account APIs Source: https://sdk.poki.com/phaser Provides methods to retrieve user information and initiate the login process. It's recommended to call `getUser()` after the game loads and `login()` only upon user interaction. ```APIDOC ## User Account Methods ### `getUser()` #### Description Retrieves the current logged-in user's information. Should be called after the game loads to check login status. #### Method `poki.getUser()` #### Response - **Promise** - Resolves with a user object containing `username` and `avatarUrl`, or `null` if the user is not logged in. ### `login()` #### Description Initiates the user login process. This should only be called from a user interaction that requires an account. A successful login might refresh the page. #### Method `poki.login()` #### Response - **Promise** - Resolves upon successful login. ### `getToken()` #### Description Retrieves a token for verifying the Poki user on your own backend. The token expires in 1 minute and should only be used for immediate backend verification. #### Method `poki.getToken()` #### Response - **Promise** - Resolves with a string representing the authentication token. ### Backend Verification Endpoint - **Method**: `GET` - **Endpoint**: `https://user-vault.poki.com/auth/verify-token` - **Headers**: `Authorization: Bearer `, `X-Poki-Team-Api-Key: ` - **Response**: Returns an immutable, game-specific `user_id`. ``` -------------------------------- ### Stop Gameplay During Commercial Break Source: https://sdk.poki.com/defold Use this to pause your game when a commercial break starts. The game continues when the break is successful. ```lua -- gameplay stops poki_sdk.commercial_break(function(self, status) if status == poki_sdk.COMMERCIAL_BREAK_SUCCESS then -- fire your function to continue the game end end) ``` -------------------------------- ### SDK Initialization Check Source: https://sdk.poki.com/unity Checks if the Poki SDK has been initialized. ```APIDOC ## PokiUnitySDK.Instance.isInitialized ### Description Determines if the Poki SDK has been successfully initialized. ### Method `PokiUnitySDK.Instance.isInitialized()` ### Returns * (bool) - `true` if the SDK is initialized, `false` otherwise. ``` -------------------------------- ### Track Progress Event Source: https://sdk.poki.com/game-events Use the 'start', 'complete', or 'fail' action values to track progress funnels like levels or tutorials. ```javascript measure('level', '1', 'start'); measure('level', '1', 'complete'); measure('level', '1', 'fail'); ``` -------------------------------- ### Get List of Userdata Source: https://sdk.poki.com/auds Lists userdata entries, with options to filter by values, sort results, and include the full data payload. ```APIDOC ## GET /v0//userdata/ ### Description Use this endpoint to list userdata. You can optionally filter and sort the results. ### Method GET ### Endpoint `https://auds.poki.io/v0//userdata/` ### Parameters #### Path Parameters - **your-poki-game-id** (string) - Required - The unique identifier for your Poki game. - **freeform-key** (string) - Required - A key to categorize the userdata. #### Query Parameters - **q=key:value** (string) - Optional - Filters the results by a `values` key. Only basic matching is supported. - **q=** (string) - Optional - URL-encoded JSON query for advanced filters. See https://github.com/poki/mongodb-filter-to-postgres for syntax. - **sort=key** (string) - Optional - Sorts results ascending by the given `values` key. - **sort=-key** (string) - Optional - Sorts results descending by the given `values` key. - **includedata** (boolean) - Optional - If present, includes the `data` field in the returned items. - **limit** (integer) - Optional - Limits the number of results returned (min 1, max 100). ### Request Example ```javascript fetch('https://auds.poki.io/v0/use-your-poki-game-id/userdata/tests?q=type:arena-1v1') .then(response => response.text()) .then(result => console.log(result)) .catch(error => console.log('error', error)); ``` ### Response #### Success Response (200) - **total** (integer) - The total number of userdata entries matching the query. - **items** (array) - A list of userdata entries. - Each item contains: - **id** (string) - The unique identifier of the userdata entry. - **meta** (object) - Metadata about the userdata entry. - **revision** (integer) - **created_at** (string) - **expires_at** (string) - **expires_in** (integer) - **values** (object) - Key/value pairs representing the core userdata. #### Response Example ```json { "total": 1, "items": [ { "id": "ce702oq1gkcvlv1tmlgg", "meta": { "revision": 1, "created_at": "2022-12-05T14:34:11.677983Z", "expires_at": "2023-12-05T14:34:11.677983Z", "expires_in": 31536000 }, "values": { "levelname": "Test level", "note": "'values' can only be key/value pairs where values can only be string, number, or boolean", "type": "arena-1v1" } } ] } ``` ``` -------------------------------- ### Get Authentication Token Source: https://sdk.poki.com/cocos Retrieves an authentication token for backend verification. The token expires in 1 minute and should only be used for immediate verification. ```javascript const token = await CCPokiSDK.getToken() ``` -------------------------------- ### Initiate User Login with Poki SDK Source: https://sdk.poki.com/phaser Call `login()` within a user interaction to prompt the player to log in. A successful login might refresh the page, so it's recommended to call `getUser()` again afterward. Handle errors if the user closes the authentication panel or the login times out. ```javascript async function onLoginButtonPressed () { try { await poki.login() // If the page did not refresh, the user was already logged in. const user = await poki.getUser() console.log('Logged in as', user.username) } catch (error) { // User closed the auth panel or login timed out. } } ``` -------------------------------- ### login Source: https://sdk.poki.com/defold Initiates the user login process. This function should only be called in response to a player's interaction that requires an account. A successful login might refresh the page, so it's recommended to call `get_user()` again after the load. ```APIDOC ## Function: poki_sdk.login ### Description Starts the Poki user login flow. This typically prompts the user to authenticate via a Poki account. ### Parameters * `callback` (function, optional) - A function that is called when the login process is finished. It accepts two arguments: `success` (boolean) and `error` (any). `success` is true if the login was successful, false otherwise (e.g., user closed the panel or timed out). ### Example ```lua local function on_login_finished(self, success, error) if not success then -- User closed the auth panel or login timed out. return end -- If the page did not refresh, the user was already logged in. poki_sdk.get_user(function(self, user, error) if user then print("Logged in as", user.username) end end) end poki_sdk.login(on_login_finished) ``` ``` -------------------------------- ### Disable Audio and Input During Ads Source: https://sdk.poki.com/unity Implement this to mute audio and disable keyboard input when a commercial break starts, and re-enable them when the break ends. ```csharp public void triggerRestartGame() { // fire your mute audio function // fire your disable keyboard input function PokiUnitySDK.Instance.commercialBreakCallBack = restartGame; PokiUnitySDK.Instance.commercialBreak(); } public void restartGame(){ // reset game here // fire your unmute audio function // fire your enable keyboard input function } ``` -------------------------------- ### Implement Poki Gameplay Events Source: https://sdk.poki.com/gamemaker Use poki_gameplay_start() when the player begins playing and poki_gameplay_stop() when they are no longer playing (e.g., level end, game over). ```javascript // first level loads, player clicks anywhere poki_gameplay_start(); // player is playing // player loses round poki_gameplay_stop(); // game over screen pops up ``` -------------------------------- ### Get Authentication Token Source: https://sdk.poki.com/godot Retrieves an authentication token from Poki for backend verification. This token is short-lived and should only be used for immediate verification against the Poki backend. ```gdscript func _on_verify_button_pressed(): PokiSDK.getToken() func _on_token_ready(token): if token != null and token != "": print("Token ", token) func _on_token_failed(error): pass ``` -------------------------------- ### Initiate Login and Handle Completion Source: https://sdk.poki.com/godot Initiates the Poki login process when a user interaction requires it. Handles the completion of the login flow, including refreshing user data if the page does not automatically reload. ```gdscript func _on_login_button_pressed(): PokiSDK.login() func _on_login_done(): # If the page did not refresh, the user was already logged in. PokiSDK.getUser() func _on_login_failed(error): # User closed the auth panel or login timed out. pass ``` -------------------------------- ### Get User Source: https://sdk.poki.com/html5 Returns the current logged-in user information or null if no user is logged in. Throws an exception if user accounts are not enabled or if the user has opted out. ```APIDOC ## Get User ### Description Returns the current logged-in user information, or `null` if no user is logged in. Throws an exception if user accounts is not enabled or if the user has opted out of the feature. Call this function after your game loads to handle all possible user states (logged in, logged out, or after a page refresh due to an authentication state change). ### Method `getUser(): Promise` ### Parameters None ### Response #### Success Response - **User** (object) - User information if logged in. - **null** - If no user is logged in. ### Request Example ```javascript try { const user = await PokiSDK.getUser(); if (user) { console.log(`Welcome ${user.username}!`); } else { // User is not logged in, you can call PokiSDK.login() to prompt it console.log("User not logged in"); } } catch (error) { // user accounts is not available or user opted out of the feature } ``` ### Debug Mode (Inspector) When running with debug mode enabled, `getUser()` returns static mock data for local development and testing: ```json { "username": "TestUser", "avatarUrl": "https://a.poki-cdn.com/img/placeholder_gradient.png" } ``` ``` -------------------------------- ### Get Authentication Token Source: https://sdk.poki.com/cocos Retrieves an authentication token for backend verification. This token is short-lived (1 minute) and should only be used for verifying the Poki user on your own server. ```APIDOC ## CCPokiSDK.getToken() ### Description Obtains a temporary authentication token for verifying the Poki user on your backend server. The token is valid for 1 minute. ### Method `async` ### Endpoint N/A (SDK Method) ### Parameters None ### Request Example ```javascript const token = await CCPokiSDK.getToken(); // Use this token for backend verification ``` ### Response #### Success Response - **token** (string) - The authentication token. #### Response Example ``` "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." ``` ### Verification Endpoint `GET https://user-vault.poki.com/auth/verify-token` Headers: - `Authorization: Bearer ` - `X-Poki-Team-Api-Key: ` Returns an immutable, game-specific `user_id`. ```