Open Game SDK - backup

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 - backup

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!

AI Prompt

Using Cursor, Windsurf, or other AI agents? If so, you can use an AI prompt to integrate the SDK for you.

Expand the section below, copy to clipboard, and paste into your AI context window.

Prompt
# Open Game Protocol Developer Docs

## ๐Ÿ“„ Source
- **Game developer onboarding:** https://docs.opengameprotocol.com/build-on-og/game-developer-onboarding
- **Open Game SDK:** https://docs.opengameprotocol.com/build-on-og/open-game-sdk

---

## ๐Ÿš€ Getting Started: Game Developer Onboarding

### โœ… Step 1: Register as a Developer
Visit the [Pre-release Onboarding App](https://docs.opengameprotocol.com/build-on-og/game-developer-onboarding)

Youโ€™ll receive:
- **โœ… Required:** `Public API Key` โ€“ used to identify your game
- **โœ… Required:** `Secret` โ€“ for server-side API requests (shown only once)

โš ๏ธ If the secret is lost, you must regenerate it in the app.

---

### ๐Ÿ”’ Step 2: Verify Game Ownership

Insert the following meta tag directly into the HTML `<head>` section of your gameโ€™s main entry file:

```html
<meta name="x-ogp-key" content="API_KEY">
```

> ๐Ÿ’ก Ask the user: โ€œWhat is your Public API Key so I can replace 'API_KEY' in the HTML?โ€
> You can find it after registering at https://onboarding.opengameprotocol.com/

โ— Must be hardcoded in HTML and **not** dynamically injected via JavaScript.

---

### ๐Ÿ•น๏ธ Step 3: Register Your Game

Inside the onboarding app:
- Provide a **โœ… required** unique `gameId` for each game.
> ๐Ÿ’ก Ask the user: โ€œWhat would you like to use as your internal gameId (e.g., 'my-space-blaster')?โ€

---

## ๐Ÿงฉ Open Game SDK

### ๐Ÿ”ง Installation

#### โœ… Required: Choose one installation method

##### Via Script Tag
```html
<script src="https://cdn.opengameprotocol.com/opengame-sdk-v2.min.js"></script>
```

##### OR via NPM
```bash
npm install @ogp/game-sdk
```

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

---

### โš™๏ธ Initialization

Create and configure your SDK instance:

```js
const ogp = new OpenGameSDK({
  ui: {
    gameIcon: '/icon.png' // ๐Ÿ” Optional: Set an icon for built-in UI
  },
  useCustomAuth: true // ๐Ÿ” Optional: Set to true to use your own auth system
});
```

Initialize the SDK:
```js
ogp.init({ gameId: '<YOUR_GAME_ID>' }).then(() => {
  console.log('SDK initialized');
});
ogp.gameReadyToPlay();
```

> ๐Ÿ’ก Ask the user:
> - โ€œWhat is your gameId (a unique string identifier)?โ€
> - โ€œDo you want to use a custom authentication system (like Firebase/Auth0)?โ€

---

## ๐Ÿ” Authentication

### โœ… Required (one of the following methods)

#### Built-in Login (Privy)

> โš ๏ธ If using the **default UI** (i.e., `gameIcon` is set and `useCustomAuth` is `false`), login is **handled automatically** by the SDK widget.
> Do **not** create a manual login button in this case.

Only use the `ogp.login()` method if:
- You're building a custom UI, **and**
- You have not set a `playerId`, **and**
- You want to trigger the login process manually

```js
ogp.login();
```

#### Custom Auth
```js
ogp.setCustomAuthToken('<YOUR_JWT_TOKEN>');
```

> ๐Ÿ’ก Ask the user: โ€œWhat JWT token should be used for authentication?โ€

---

## ๐Ÿงฎ Points API

### โœ… Required to earn points

#### Save Points
```js
ogp.savePoints(<POINTS_NUMBER>);
```
- `points`: **โœ… Required**, must be > 0

#### Get Points
```js
ogp.getPoints().then(response => {
  console.log('Total points:', response.data.points);
});
```

> ๐Ÿ’ก Ask the user: โ€œHow many points should be awarded for this game session?โ€

---

## ๐ŸŽ Rewards API

### ๐Ÿ” Optional

```js
ogp.listUserRewards();
ogp.listGameRewards();
ogp.claimRewards(true);
ogp.getRewardStatus('<TX_HASH>');
ogp.getTimeUntilNextClaim();
```

> ๐Ÿ’ก Ask the user:
> - โ€œWould you like to let users claim rewards?โ€
> - โ€œDo you want to use our built-in reward modals or custom UI?โ€
> - โ€œWhat is the transaction hash you'd like to check status for?โ€

---

## ๐Ÿงญ Events

### ๐Ÿ” Optional

Subscribe to SDK lifecycle events:
```js
ogp.on('OnReady', () => console.log('SDK is ready!'));
ogp.on('LoginSuccess', () => console.log('Logged in successfully.'));
```

Unsubscribe when needed:
```js
ogp.off('OnReady', callback);
ogp.off('*', callback);
```

---

## โ— Error Display

```js
ogp.showError({
  title: 'Error',
  message: 'Something went wrong.'
});
```

> ๐Ÿ’ก Ask the user: โ€œWhat should the error message say if saving points fails?โ€

---

## ๐Ÿงช HTML Integration Example

```html
<!DOCTYPE html>
<html>
<head>
  <script src="https://cdn.opengameprotocol.com/opengame-sdk-v2.min.js"></script>
</head>
<body>
  <button id="addPoint">Add Point</button>
  <button id="savePoints">Save Points</button>
  <button id="getPoints">Get Points</button>
  <!-- Remove login button when using default UI -->
<!-- <button id="login">Login</button> -->

  <script>
    const ogp = new OpenGameSDK({ ui: { gameIcon: '/icon.png' } });
    ogp.on('OnReady', () => {
      ogp.init({ gameId: '<YOUR_GAME_ID>' }).then(() => {
        ogp.gameReadyToPlay();
      });
    });

    let points = 0;
    document.getElementById('addPoint').onclick = () => { points += 1; };
    document.getElementById('savePoints').onclick = () => {
      ogp.savePoints(points).then(() => { points = 0; });
    };
    document.getElementById('getPoints').onclick = () => {
      ogp.getPoints().then(response => console.log(response));
    };
    // Only attach login handler if building custom UI and not using default UI
// document.getElementById('login').onclick = () => ogp.login();
  </script>
</body>
</html>
```
---

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

  • 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
  },
  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 can be any string you use internally to identify your game.

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

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 is initialized.

Parameters:

  • None

Returns:

  • void

Example:

ogp.gameReadyToPlay();

setPlayerId

Sets or updates the player's ID.

Parameters:

  • id (string, required) โ€“ The new player ID.

Returns:

  • void

Example:

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

Authentication

The SDK supports two authentication methods: a built-in login interface (powered by Privy) and custom authentication for integrating third-party providers like Auth0 or Firebase.

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.

Custom Authentication

Integrate your own authentication flow and pass the resulting 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.

Parameters:

  • points (number, required) โ€“ The number of points to save.

Returns:

  • Promise<{ data: { savePoints: "success"; } }> โ€“ 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(response => {
  console.log('Points saved:', response);
});

getPoints

Retrieves the player's current points.

Parameters:

  • None

Returns:

  • Promise<number | undefined> โ€“ API response with points data.

Example:

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

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