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.
Quickstart
For the most basic integration, you only need to do the following steps:
Creating an SDK Instance and set gameIcon parameter to opt in to our automated UI
Call init() to initialize the SDK
Call gameReadyToPlay() when your game is ready to start play
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.
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 totrue
to use a custom authentication token instead of the built-in login.
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:
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:
Example:
ogp.gameReadyToPlay();
setPlayerId
Sets or updates the player's ID.
Parameters:
id
(string, required) โ The new player ID.
Returns:
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.
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.
For custom authentication to work, you must contact the Open Game team and provide a JWKS endpoint.
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:
Example:
ogp.startCustomAuth();
cancelCustomAuth
Cancel the custom login process if the user aborts.
Parameters:
None
Returns:
Example:
ogp.cancelCustomAuth();
Custom Flow Example:
Call
ogp.startCustomAuth()
to beginRedirect to your auth provider (e.g., Auth0)
On success, call
ogp.setCustomAuthToken(token)
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.
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.
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) โ Iftrue
, displays a modal listing user rewards before confirming the claim; iffalse
, 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 viastartCustomAuth
).'LoginCancelled'
: Login canceled (via modal orcancelCustomAuth
).'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) โ Containstitle
andmessage
.
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