Open Game SDK

OGP is the fastest way to launch, distribute, and monetize games - without middlemen.

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. Call init() with your game Id

  2. 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-latest.min.js"></script>

Alternatively, you can use a specific version of the SDK:

<script src="https://cdn.opengameprotocol.com/opengame-sdk-v0.3.8.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.

const ogp = new OpenGameSDK({ ui: { usePointsWidget: true, }});

Parameters

Parameter
Type
Default
Description

ui.theme

'light' | 'dark'

'light'

Sets a light or dark theme for our default UI

ui.usePointsWidget

boolean

false

Show floating points widget

ui.useCustomUi

boolean

false

Disable all automatic modals/widgets; control UI entirely yourself

useCustomAuth

boolean

false

Use custom authentication via JWT

logLevel

number

2

Console logging level

Log Levels

Value
Level
Description

0

VERBOSE

Most detailed logging

1

INFO

Standard information logging

2

WARN

Warning messages only

3

ERROR

Error messages only

4

DISABLE

No logging

interface SDKOpts {
  ui?: {
    gameIcon?: string;
    theme?: Theme;
    usePointsWidget?: boolean;
    useCustomUi?: boolean;
  };
  useCustomAuth?: boolean;
  logLevel?: number; // 0=VERBOSE, 1=INFO, 2=WARN, 3=ERROR, 4=DISABLED
}

init

Initialize the SDK with your game’s unique identifier and an optional player ID.

ogp.init({ gameId: 'your-game-id' });

Parameters:

  • gameId (string, required) – You can find your game's ID after After adding a game in the Pre-release Onboarding App

  • 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:

  • Promise<void>


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.

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

Parameters:

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

Returns:

  • void


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.

ogp.startCustomAuth();

Parameters:

  • None

Returns:

  • void

cancelCustomAuth

Cancel the custom login process if the user aborts.

ogp.cancelCustomAuth();

Parameters:

  • None

Returns:

  • void

logout

Logs out the current user and clears the session.

ogp.logout();

Parameters:

  • None

Returns:

  • void


Points

Manage player points with methods to save and retrieve them.

savePoints

Saves the player's earned points. Only accepts numbers greater 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.

ogp.savePoints(100);

Parameters:

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

Returns:

  • Promise<number | undefined> – API response with the total points saved for the day.

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.

getPoints

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

ogp.getPoints().then(response => {
  if (response) {
    console.log('Total points:', response.points);
    console.log('Tokens:', response.tokens);
  } else {
    console.log('No points data available');
  }
}).catch(error => {
  console.error('Error fetching points:', error);
});

Parameters:

  • None

Returns:

  • Promise<PlayerPoints | undefined> – API response with points data or undefined if the request fails.

  • PlayerPoints structure

interface PlayerPoints {
  points: number;
  tokens: {
    name: string;
    image: string;
    symbol: string;
    network: string;
    address: string;
    points?: number;
  }[];
}

Points Widget

ui.showPoints

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

ogp.ui.showPoints();

Parameters:

  • None

ui.hidePoints

Hides the points widget

ogp.ui.hidePoints();

Parameters:

  • None

ui.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.

ogp.ui.addPoints(1);

Parameters:

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


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.

listPlayerRewards

Fetches a list of rewards available to the player.

ogp.listPlayerRewards().then(response => {
  if (response) {
    console.log('Player rewards:', response.rewardDetails);
  } else {
    console.log('No rewards available');
  }
}).catch(error => {
  console.error('Error fetching player rewards:', error);
});

Parameters:

  • none

Returns:

  • Promise<PlayerRewards | undefined> – API response with player rewards data or undefined if the request fails.

  • PlayerRewards structure:

    interface PlayerRewards {
      rewardDetails: {
        id: string;
        name: string;
        image: string;
        description: string;
        points: number;
        rewards: {
          token: {
            address: string;
            symbol: string;
            name: string;
            image: string;
            network: string;
            history: {
              date: string;
              points: number;
              amount: number;
              gAmount: number;
              mUsdAmount: number;
              gUsdAmount: number;
            }[];
            claimed: number;
            unclaimed: number;
          };
        }[];
      }[];
      totalUsd: number;
      topTokenNames: string[];
    }

listCreatorRewards

Fetches a list of creator rewards available to the current player

ogp.listCreatorRewards().then(response => {
  if (response) {
    console.log('Creator rewards:', response.rewardDetails);
  } else {
    console.log('No creator rewards available');
  }
}).catch(error => {
  console.error('Error fetching creator rewards:', error);
});

Parameters:

  • None

Returns:

  • Promise<CreatorRewards | undefined> – API response with creator rewards data or undefined if the request fails.

  • CreatorRewards structure:

    interface CreatorRewards {
      rewardDetails: {
        name: string;
        symbol: string;
        image: string;
        usdAmount: number;
        unclaimed: number;
        address: string;
        network: string;
      }[];
      totalUsd: number;
      topTokenNames: string[];
    }

claimPlayerRewards

Attempts to claim available rewards for the player.

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

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

claimCreatorRewards

Attempts to claim available rewards for the game creator. Displays the creator rewards modal for the current playerId

ogp.claimCreatorRewards();

Parameters:

  • None

Returns:

  • void

getRewardStatus

Retrieve the status of a reward claim transaction.

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

Parameters:

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

Returns:

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

getTimeUntilNextClaim

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

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

Parameters:

  • None

Returns:

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


Event Callbacks

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

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

onAny

Capture all SDK events with a single listener.

Parameters:

  • callback (function) – Receives the event name and 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)

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.

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

showError

Show an error message to the user.

Parameters:

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


Demos

Our public demo GitHub is at https://github.com/OpusGameLabs/ogp-demos

Simple Game Demo (simple-game/)

This demo shows how to:

  • Initialize and configure the OpenGameSDK

  • Track player points in real-time using addPoints()

  • Save final scores using savePoints()

  • Handle SDK events (OnReady, OnSessionStarted)

Claim Creator Rewards Demo (claim-creator-rewards/)

This demo shows how to:

  • Claim creator rewards using claimCreatorRewards()

  • Handle async SDK operations with proper error handling

  • Provide user feedback during claim operations

  • Implement a simplified single-purpose SDK integration

Last updated