Open Game SDK

The Open Game SDK provides a simple interface for frontend developers to integrate authentication, points management, and rewards functionality into their games. It supports both built-in authentication (via Privy) and custom authentication flows (e.g., using Auth0), offering flexibility for various integration needs.

Before using the SDK, see Game developer onboarding

For advanced integrations, see Open Game Endpoints


Quickstart

For the most basic integration, you only need to do the following steps:

  1. Creating an SDK Instance and set gameIcon parameter to opt in to our automated UI

  2. Call init() to initialize the SDK

  3. Call gameReadyToPlay() when your game is ready to start play

  4. Call savePoints() after a round of game play

With this setup, all OGP related UI will be handled automatically. Seamless and simple!

Installation

To use the Open Game SDK in your project, you can choose one of the following methods:

Via Script Tag

Include the following script tag in your HTML file:

<script src="https://cdn.opengameprotocol.com/opengame-sdk-v3.min.js"></script>

Once the script is loaded, the SDK becomes available as a global variable OpenGameSDK

Via NPM

The SDK is also available as an NPM package. Install it using:

npm install @ogp/game-sdk

Then, import it in your JavaScript code:

import OpenGameSDK from "@ogp/game-sdk";

After installation, create an instance of the SDK as detailed in the Initialization section.


Initialization

After installing the SDK, you need to create an instance and initialize it with your game’s configuration. This section covers the steps to set up the SDK for use.

Creating an SDK Instance

Create a new instance of the SDK with optional configuration options for UI customization and authentication preferences.

Parameters:

  • ui.gameIcon: (string, optional) - Specifies the game icon displayed in the SDK’s UI.

  • ui.usePointsWidget: (boolean, optional) - Choose whether to turn on the header points widget

  • useCustomAuth: (boolean, optional) - Set to true to use a custom authentication token instead of the built-in login.

When you specify the game icon, the image will be used inside our convenient default UI experience. If you wish to provide a custom UI experience, then do not specify this value.

Example:

const ogp = new OpenGameSDK({
  ui: {
    gameIcon: 'path/to/icon.png', // Optional: URL or path to the game icon
    usePointsWidget: true, // Optional: Show points widget, defaults to false
  },
  useCustomAuth: true // Optional: Enable custom authentication (default: false)
});

init

Initialize the SDK with your game’s unique identifier and an optional player ID. This method returns a promise that resolves once the SDK is fully initialized, which requires calling gameReadyToPlay.

Parameters:

  • gameId (string, required) – Your game's custom unique ID. This value can be found in the Pre-release Onboarding App games section once the game has been "claimed".

  • playerId (string, optional) – The player's unique ID. This is an optional parameter for developers that want to provide their own custom player IDs. If not set, then a login is provided for the user.

Returns:

  • void

Example:

// This must be called in order for init to resolve
ogp.gameReadyToPlay();
// Init will only resolve once "gameReadyToPlay"
ogp.init({ gameId: 'your-game-id', playerId: 'player-123' }).then(() => {
  console.log('SDK initialized');
});

gameReadyToPlay

Signal that the game is ready to start. This must be called for the init promise to resolve, indicating the game environment is fully prepared and the SDK can finish its initialization.

Parameters:

  • None

Returns:

  • void

Example:

// This must be called in order for the SDK finish initializing
ogp.gameReadyToPlay();

Authentication

The SDK supports two authentication methods: a built-in login interface (powered by Privy) and custom authentication for integrating third-party providers that uses JWKS endpoint, like Auth0 or Firebase. We also support Anon sessions that let new users play without having to immediately sign up.

Built-in Login

Trigger the SDK’s default login UI.javascript

ogp.login();

This opens the Privy login modal when useCustomAuth is set to false during instantiation.

Login is automatically displayed and handled by the SDK widget when opting in to the default UI during Initialization. This function only needs to be called in the rare case when you are providing a custom UI and never set playerId. In that case, it is suggested to call login the first time before saving points.

Anon sessions

If you want to reduce friction and not ask the user to login straight away that's also an option. If you already use some sort of identifier, like fingerprint.js for example, you can set that as a playerId. The session will be setup using that and whenever the user wants to claim rewards, they will be prompted to login and have their data migrated into a fully fledged OGP user.

setPlayerId

Sets or updates the player's ID.

Parameters:

  • id (string, required) – The new player ID.

Returns:

  • void

Example:

ogp.setPlayerId('new-player-456');

Custom Authentication

Integrate your own authentication flow and pass the resulting JWT token to the SDK.

setCustomAuthToken

Sets the authentication token (e.g., JWT) after a successful login.

ogp.setCustomAuthToken('your-jwt-token');
  • token (string, required) - A valid token from your auth provider.

Example with Firebase:

import { getAuth, signInWithPopup, GoogleAuthProvider } from "firebase/auth";
import { useEffect } from 'react';

const GameAuth = () => {
  const auth = getAuth();

  useEffect(() => {
    if (auth.currentUser && ogp) {
      auth.currentUser.getIdToken().then(token => {
        ogp.setCustomAuthToken(token);
      });
    }
  }, [auth.currentUser]);

  const signIn = () => {
    const provider = new GoogleAuthProvider();
    signInWithPopup(auth, provider);
  };

  return <button onClick={signIn}>Sign in with Google</button>;
};

startCustomAuth

Initiate the custom login process.

Parameters:

  • None

Returns:

  • void

Example:

ogp.startCustomAuth();

cancelCustomAuth

Cancel the custom login process if the user aborts.

Parameters:

  • None

Returns:

  • void

Example:

ogp.cancelCustomAuth();

Custom Flow Example:

  1. Call ogp.startCustomAuth() to begin

  2. Redirect to your auth provider (e.g., Auth0)

  3. On success, call ogp.setCustomAuthToken(token)

  4. If canceled, call ogp.cancelCustomAuth()


Points

Manage player points with methods to save and retrieve them.

savePoints

Saves the player's earned points. Only accepts numbers bigger than 0. Trying to save 0 or negative numbers will return a failure response. On success returns the totalPoints the user has saved for the day.

Parameters:

  • points (number, required) – The number of points to save.

Returns:

  • Promise<{ number }> – API response.

When opted in to our default UI during Initialization, calling savePoints() will automatically open our widget UI flow. This allows the player to save their points and then claim any rewards.

Example:

ogp.savePoints(100).then(() => {
  console.log('Points saved');
});

getPoints

Retrieves the player's current points along with the game tokens in which the points are distributed to.

Parameters:

  • None

Returns:

interface GetPoints {
  points: number;
  tokens: { 
    name: string; 
    image: string; 
    symbol: string; 
    network: string; 
    address: string; 
    extraPoints?: number; 
  }[];
}
  • Promise<GetPoints | undefined> – API response with points data.

Example:

ogp.getPoints().then(response => {
  console.log('Total points:', response.points);
});

Points Widget

addPoints

Add points to the session, which are reflected in the points widget. The points added here are merely for display purpose, if not saved, they will be lost.

Parameters:

  • points (number, required) – The number of points to added.

Example:

ogp.addPoints(1);

ui.showPoints

Shows the points widget if it was opt-in during SDK instatiation via ui.usePointsWidget

Parameters:

  • None

Example:

ogp.ui.showPoints();

ui.hidePoints

Hides the points widget

Parameters:

  • None

Example:

ogp.ui.hidePoints();

Rewards

Manage player rewards with methods for listing, claiming, and checking status.

The reward functions only need to be called when providing a custom UI. You can opt in to automatic default UI during Initialization.

listUserRewards

Retrieves a list of rewards available to the player.

Parameters:

  • none

Returns:

  • Promise<{ { items: RewardItem[]; total: number; nextToken?: string } }> – API response with available rewards.

  • RewardItem - A type available in the SDK

Example:

ogp.listUserRewards().then(response => {
  console.log('User rewards:', response.items);
});

listGameRewards

Retrieve a list of rewards available in the game.

Parameters:

  • None

Returns:

  • Promise<{ { items: GameRewardItem[]; total: number; nextToken?: string } }> – API response with game rewards.

  • GameRewardItem - A type available in the SDK

Example:

ogp.listGameRewards().then(response => {
  console.log('Game rewards:', response.items);
});

claimRewards

Attempts to claim available rewards for the player.

Parameters:

  • useRewardModal (boolean, optional) – If true, displays a modal listing user rewards before confirming the claim; if false, directly shows the confirm claim modal.

Returns:

  • void

Example:

ogp.claimRewards(true); // Shows reward modal

getRewardStatus

Retrieve the status of a reward claim transaction.

Parameters:

  • txHash (string, required) – The transaction hash.

Returns:

  • 'pending' | 'complete' | 'failed'

Example:

const status = ogp.getRewardStatus('tx123');
console.log('Reward status:', status);

getTimeUntilNextClaim

Retrieve the time until the player can claim their next reward.

Parameters:

  • None

Returns:

  • Promise<{ number }> – API response with time data (in milliseconds).

Example:

ogp.getTimeUntilNextClaim().then(response => {
  console.log('Time until next claim (ms):', response);
});;

Event Callbacks

Handle SDK events with individual listeners or a catch-all approach.

onAny

Capture all SDK events with a single listener.

Parameters:

  • callback (function) – Receives the event name and data.

Example:

ogp.onAny((eventName, data) => {
  console.log(`Event: ${eventName}`, data);
});

Specific Events

Handle specific events as needed:

  • OnReady: Fired when the SDK is initialized.

ogp.on('OnReady', () => {
  console.log('SDK ready');
});
  • OnSessionStarted: Fired when a session begins.

ogp.on('SessionStarted', () => {
  console.log('Session started');
});
  • OnLoginSuccess: Fired after successful login.

ogp.on('LoginSuccess', () => {
  console.log('Login successful');
});

Full Event List:

  • 'OnReady': SDK initialized.

  • 'SessionStarted': Session established.

  • 'SessionFailed': Session fails (e.g., missing parameters).

  • 'LoginRequest': Login process starts (built-in or via startCustomAuth).

  • 'LoginCancelled': Login canceled (via modal or cancelCustomAuth).

  • 'LoginSuccess': Login succeeds.

  • 'LoginFailed': Authentication fails.

  • 'Logout': User logs out.

  • 'SavePointsSuccess': Points saved successfully.

  • 'SavePointsCancelled': Save points canceled.

  • 'SavePointsFailed': Points save fails.

  • 'ClaimRequest': Claim request sent.

  • 'ClaimSuccess': Claim transaction succeeds.

  • 'ClaimFailure': Claim fails (e.g., no rewards).

  • 'ClaimCancelled': Claim transaction not signed.

Unsubscribing from Events

To unsubscribe from a specific event, use ogp.off(eventName, callback). To unsubscribe from all events captured by onAny, use ogp.off('*', callback)

Example:

const onReadyCallback = () => console.log('SDK ready');
ogp.on('OnReady', onReadyCallback);
// Later
ogp.off('OnReady', onReadyCallback);

Error Handling

Display errors to users via the SDK’s UI.

showError

Show an error message to the user.

Parameters:

  • error (object, required) – Contains title and message.

Example:

ogp.showError({
  title: 'Error',
  message: 'Failed to save points. Try again.'
});

Example Usage

Here’s a complete example integrating the SDK into a web page:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Game Example</title>
  <script src="https://cdn.opengameprotocol.com/opengame-sdk-v2.min.js"></script>
</head>
<body>
  <div id="game">
    <p>Points: <span id="points">0</span></p>
    <button id="addPoint">Add Point</button>
    <button id="savePoints">Save Points</button>
    <p>Points for Today: <span id="totalPoints">0</span></p>
    <button id="getPoints">Get Points</button>
    <button id="login">Login</button>
  </div>

  <script>
    const ogp = new OpenGameSDK({ ui: { gameIcon: '/icon.png' }, useCustomAuth: false });

    ogp.on('OnReady', () => {
      ogp.init({ gameId: 'my-game' }).then(() => {
        console.log('SDK initialized');
      });
      ogp.gameReadyToPlay();
    });

    ogp.on('SessionStarted', () => {
      console.log('Session started');
    });

    ogp.on('LoginSuccess', () => {
      console.log('Logged in');
    });

    let points = 0;
    document.getElementById('addPoint').addEventListener('click', () => {
      points += 1;
      document.getElementById('points').textContent = points;
    });

    document.getElementById('savePoints').addEventListener('click', () => {
      ogp.savePoints(points).then(() => {
        points = 0;
        document.getElementById('points').textContent = points;
      });
    });

    document.getElementById('getPoints').addEventListener('click', () => {
      ogp.getPoints().then(response => {
        document.getElementById('totalPoints').textContent = response.data.points;
      });
    });

    document.getElementById('login').addEventListener('click', () => {
      ogp.login();
    });
  </script>
</body>
</html>

Last updated