@momo-cloud/gami-sdk
v0.0.39
Published
SDK for web clients (limited version for npm)
Readme
Gami SDK
A comprehensive TypeScript SDK for building games on the MoMo platform
📋 Overview
Gami SDK is a powerful TypeScript library that provides a unified interface for developing web-based games on the MoMo platform. It abstracts platform-specific APIs and provides consistent access to authentication, game state management, storage, and platform features.
✨ Key Features
- 🔐 Authentication & Authorization - Seamless token exchange and user authentication
- 🎮 Game Lifecycle Management - Start, end, and manage game sessions
- 💾 Storage API - Client-side storage with automatic key prefixing
- 📊 Leaderboard & Rankings - Built-in support for competitive features
- 📅 Calendar Integration - Schedule reminders and events
- 🎯 Mission System - Track and complete user missions
- 🎲 Game Events - Real-time event handling and tracking
- 📈 Analytics & Tracking - Built-in event tracking and user behavior analytics
- 🌐 Cross-Platform - Works in browser and MoMo app
- 📦 TypeScript Support - Full type definitions included
📦 Installation
# Using npm
npm install @momo-cloud/gami-sdk
# Using yarn
yarn add @momo-cloud/gami-sdk
# Using pnpm
pnpm add @momo-cloud/gami-sdk🚀 Quick Start
import GamiSDK from '@momo-cloud/gami-sdk';
// Initialize the SDK
await GamiSDK.init({
gameId: 'your-game-id',
appjson: '',
source: 'game-launch-source'
});
console.log('User ID:', GamiSDK.userId);
console.log('Token:', GamiSDK.token);
// Start game session
await GamiSDK.startGame();
// Your game logic here...
// Submit score
const result = await GamiSDK.submit({
steps: [
{ action: 'move', timestamp: Date.now() },
{ action: 'jump', timestamp: Date.now() }
],
score: 1000
});
// End game session
await GamiSDK.endGame();📖 API Reference
Initialization
init(options)
Initialize the SDK with your game configuration.
await GamiSDK.init({
gameId: 'demo',
appjson?: '',
source: 'momo',
userId?: '1234567890' // Optional, for testing
});Parameters:
gameId(string, optional): Your game identifier. If not provided, usesfeatureIdfrom platformappjson(string, required): app.json configuration filesource(string, optional): Launch source for analyticsuserId(string, optional): Override user ID for testing
Returns: Promise<void>
Game Management
startGame()
Begin a new game session and notify the backend.
const response = await GamiSDK.startGame();
console.log('Game started:', response);Returns: Promise<any> - Server response with session data
endGame()
End the current game session and dismiss the app.
await GamiSDK.endGame();
// App will be dismissed automaticallyReturns: Promise<void>
submit(options)
Submit game results to the backend.
const result = await GamiSDK.submit({
steps: [
{ action: 'start', timestamp: 1699000000000, data: {...} },
{ action: 'move', timestamp: 1699000001000, data: {...} },
{ action: 'end', timestamp: 1699000010000, data: {...} }
],
score: 1500
});
console.log('Reward:', result.gift);Parameters:
steps(array): Array of gameplay events for validationscore(number): Final score achieved
Returns: Promise<{ gift?: any, ... }> - Server response with rewards
Configuration & Data
getConfig()
Fetch game configuration from the backend.
const config = await GamiSDK.getConfig();
console.log('Game config:', config);Returns: Promise<any> - Game configuration object
getBalance(options)
Get user's balance for specified balance IDs.
const balance = await GamiSDK.getBalance({
balanceIds: ['coin', 'gem', 'ticket']
});
console.log('Coins:', balance.coin);
console.log('Gems:', balance.gem);Parameters:
balanceIds(string[]): Array of balance identifiers
Returns: Promise<TBalance> - Balance data object
getBalanceConfig()
Get available balance types (pockets) configuration.
const pockets = await GamiSDK.getBalanceConfig();
console.log('Available balances:', pockets);Returns: Promise<any> - Pocket configuration
getTheme(options)
Fetch theme assets for the game.
const theme = await GamiSDK.getTheme({
ext: 'json',
name: 'lunar-new-year'
});
console.log('Theme data:', theme);Parameters:
ext(string): extension (rule)name(string): Theme name/identifier
Returns: Promise<any> - Theme data
Leaderboard & Rankings
getLeaderboard(options)
Fetch leaderboard data.
const res = await GamiSDK.getLeaderboard({
boardId: 'weekly',
limit: 50
});
console.log('Leaderboard:', res);Returns: Promise<TLeaderboard> - Leaderboard data
getHistory(options)
Get user's game history.
const history = await GamiSDK.getHistory({
page: 1,
limit: 0
});
console.log('Recent games:', history.items);Returns: Promise<THistory> - History records
Events & Missions
getEvent()
Fetch active events for the game.
const events = await GamiSDK.getEvent();
events.forEach(event => {
console.log(`Event: ${event.name}, Ends: ${event.endTime}`);
});Returns: Promise<TEvent> - Event data
mission.get()
Get user's mission status.
import { mission } from '@momo-cloud/gami-sdk';
const missions = await mission.get();
missions.forEach(m => {
console.log(`Mission: ${m.name}, Progress: ${m.progress}/${m.target}`);
});Returns: Promise<MissionResponse[]> - Array of missions
mission.sendEvent(eventName, serviceId?)
Mark a mission event as completed.
import { mission } from '@momo-cloud/gami-sdk';
await mission.done('level_completed', 'service-123');Parameters:
eventName(string): Event identifierserviceId(string, optional): Related service ID
Returns: Promise<any> - Server response
Storage
saveItem(key, value)
Save data to local storage with automatic game ID prefixing.
import { saveItem } from '@momo-cloud/gami-sdk';
// Save JSON object
await saveItem('userProgress', {
level: 5,
score: 1200,
items: ['sword', 'shield']
});
// Save string
await saveItem('playerName', 'MoMoGamer123');Parameters:
key(string): Storage key (will be prefixed with gameId)value(any): Data to store (will be JSON stringified)
Returns: Promise<void>
getItem(key)
Retrieve data from local storage.
import { getItem } from '@momo-cloud/gami-sdk';
const progress = await getItem('userProgress');
console.log('Current level:', progress?.level);
const name = await getItem('playerName');
console.log('Player name:', name);Parameters:
key(string): Storage key (gameId prefix added automatically)
Returns: Promise<any | null> - Stored data or null if not found
cacheFile(url)
Cache remote files and get blob URL.
import { cacheFile } from '@momo-cloud/gami-sdk';
const imageUrl = 'https://img.mservice.io/game/icon.png';
const cachedUrl = await cacheFile(imageUrl);
// Use cachedUrl in your game
document.getElementById('avatar').src = cachedUrl;Parameters:
url(string): Remote file URL
Returns: Promise<string> - Blob URL or original URL if caching fails
Calendar
addCalendar(options)
Add event to device calendar.
import { addCalendar } from '@momo-cloud/gami-sdk';
const added = await addCalendar({
title: 'Special Event Reminder',
startDate: new Date('2025-12-15T10:00:00'),
endDate: new Date('2025-12-15T12:00:00'),
notes: 'Don\'t miss the limited-time event!',
key: 'event-reminder-dec-15',
alarm: new Date('2025-12-15T09:30:00'), // 30 min before
desc: 'Complete special missions for exclusive rewards',
toast: 'Please grant calendar permission to set reminders'
});
console.log('Calendar event added:', added);Parameters:
title(string): Event titlestartDate(Date | number): Event start timeendDate(Date | number): Event end timenotes(string): Event noteskey(string): Unique identifier for the eventalarm(Date | number): Alarm/notification timedesc(string): Event descriptiontoast(string, optional): Permission request message
Returns: Promise<boolean> - True if added successfully
Platform APIs
The SDK exposes additional platform-specific APIs through GamiSDK:
showToast(options)
Display a toast notification to the user.
GamiSDK.showToast({
title: 'Welcome!',
description: 'Thanks for playing',
duration: 3000,
type: 'success' // 'success' | 'failure' | 'info'
});Parameters:
title(string, optional): Toast titledescription(string): Toast messageduration(number): Display duration in millisecondstype(string, optional): Toast type
showAlert(title, message, buttons?)
Show a native alert dialog.
GamiSDK.showAlert(
'Confirm Action',
'Are you sure you want to proceed?',
['Cancel', 'Confirm']
);Parameters:
title(string): Alert titlemessage(string): Alert messagebuttons(string[], optional): Button labels (default: ['OK'])
openWeb(options)
Open a URL in an in-app webview.
GamiSDK.openWeb({
url: 'https://example.com/rules',
title: 'Game Rules'
});
// Or with custom HTML
GamiSDK.openWeb({
html: '<h1>Custom Content</h1>',
title: 'Info'
});Parameters:
url(string, optional): URL to openhtml(string, optional): Custom HTML contenttitle(string, optional): Webview title
Returns: Promise<boolean>
openURL(url)
Open a URL in the device's external browser.
GamiSDK.openURL('https://momo.vn');Parameters:
url(string): URL to open
Returns: Promise<boolean>
shareExternal(options)
Share content to external apps.
GamiSDK.shareExternal({
title: 'Check out this game!',
message: 'I just scored 1000 points!',
url: 'https://momo.vn/game',
subject: 'Game Score'
});Parameters:
title(string, optional): Share titlemessage(string, optional): Share messageurl(string, optional): URL to sharesubject(string, optional): Email subject
Returns: Promise<boolean>
copyToClipBoard(text, message?)
Copy text to clipboard.
GamiSDK.copyToClipBoard(
'PROMO2025',
'Promo code copied!'
);Parameters:
text(string): Text to copymessage(string, optional): Success message to display
Returns: Promise<boolean>
shareFacebook(url) / shareMessenger(url)
Share URL to Facebook or Messenger (MoMo app only).
GamiSDK.shareFacebook('https://momo.vn/game');
GamiSDK.shareMessenger('https://momo.vn/game');Parameters:
url(string): URL to share
Returns: Promise<boolean>
requestPermission(permission) / checkPermission(permission)
Request or check device permissions.
// Request permission
const status = await GamiSDK.requestPermission('calendars');
console.log('Permission status:', status); // 'granted' | 'denied'
// Check existing permission
const hasPermission = await GamiSDK.checkPermission('contacts');Parameters:
permission(string): Permission type ('calendars', 'contacts', etc.)
Returns: Promise<string> - Permission status
getContacts()
Retrieve device contacts (MoMo app only, requires permission).
const contacts = await GamiSDK.getContacts();
console.log('Contacts:', contacts);Returns: Promise<any[] | null>
saveCalendarEvent(options)
Save an event to the device calendar (MoMo app only).
const saved = await GamiSDK.saveCalendarEvent({
title: 'Daily Bonus Available',
startDate: new Date('2025-12-15T10:00:00'),
endDate: new Date('2025-12-15T12:00:00'),
notes: 'Come back to claim your daily bonus!',
key: 'daily_bonus_reminder',
alarm: new Date('2025-12-15T09:45:00'),
des: 'Daily bonus notification',
toast: 'Please grant calendar permission'
});
console.log('Event saved:', saved);Parameters:
title(string): Event titlestartDate(Date | number): Event start timeendDate(Date | number): Event end timenotes(string): Event noteskey(string): Storage key for event IDalarm(Date | number): Reminder timedes(string): Event descriptiontoast(string, optional): Permission request message
Returns: Promise<boolean>
trackingEvent(event, data)
Track analytics events.
GamiSDK.trackingEvent('level_completed', {
level: 5,
score: 1200,
duration: 45
});Parameters:
event(string): Event namedata(object): Event data
screenTracking(options)
Track screen views and user actions.
GamiSDK.screenTracking({
game_id: 'vn.momo.web.luckywheel',
event_name: 'screen_view',
action_name: 'view_leaderboard',
screen_name: 'leaderboard_screen',
extra: { tab: 'weekly' },
error_code: 0
});Parameters:
game_id(string, optional): Game identifierevent_name(string): Event nameaction_name(string): Action identifierscreen_name(string): Screen identifierextra(object, optional): Additional dataerror_code(number | string, optional): Error code if applicable
startRefId(options)
Navigate to another feature/screen by reference ID.
// Start feature by code
GamiSDK.startRefId({
refId: 'FEATURE_CODE_123',
refExtra: { source: 'game' }
});
// Open URL
GamiSDK.startRefId({
refId: 'https://example.com',
useWeb: true // Open in webview instead of external browser
});
// Navigate to internal path
GamiSDK.startRefId({
refId: '/wallet/topup'
});Parameters:
refId(string): Feature code, URL, or internal pathrefExtra(object | string, optional): Additional parametersuseWeb(boolean, optional): Open URLs in webview (default: false)
listenShaking(options)
Listen to device shake events (MoMo app only).
GamiSDK.listenShaking({
onShake: (data) => {
console.log('Device shaken!', data);
// Trigger special action
showBonusReward();
}
});Parameters:
onShake(function): Callback when device is shaken
Returns: Listener object (for cleanup)
onFocusApp(callback) / onBlurApp(callback)
Listen to app focus/blur events.
GamiSDK.onFocusApp(() => {
console.log('App is now active');
resumeGame();
});
GamiSDK.onBlurApp(() => {
console.log('App went to background');
pauseGame();
});Parameters:
callback(function): Function to call on focus/blur
registerNoti(callback) / unregisterNoti()
Register/unregister notification listeners (MoMo app only).
// Register
GamiSDK.registerNoti((data) => {
console.log('Received notification:', data);
handleNotification(data);
});
// Unregister
GamiSDK.unregisterNoti();Parameters:
callback(function): Notification handler
Utilities
getServerTime()
Get synchronized server time.
import { getServerTime } from '@momo-cloud/gami-sdk';
const serverTime = getServerTime();
console.log('Server time:', new Date(serverTime));Returns: number - Server timestamp in milliseconds
setServerTime(time)
Set server time offset manually (usually handled by init).
import { setServerTime } from '@momo-cloud/gami-sdk';
setServerTime(Date.now() + 1000); // 1 second aheadParameters:
time(number): Server timestamp in milliseconds
Properties
Access SDK state and user information:
// User information
console.log(GamiSDK.userId); // string: User ID
console.log(GamiSDK.userInfo); // IUserInfo: Full user profile
console.log(GamiSDK.token); // string: Auth token
console.log(GamiSDK.gameId); // string: Current game ID
// Platform information
console.log(GamiSDK.isBrowser); // boolean: Running in browser
console.log(GamiSDK.isIos); // boolean: iOS device
console.log(GamiSDK.feature); // any: Platform featuresUser Info Type:
interface IUserInfo {
id: string;
name: string;
phone?: string;
avatar?: string;
// ... additional fields
}🔐 Authentication Flow
User Opens Game
↓
SDK.init() called
↓
Get user profile and authentication
↓
Backend: login(appToken) → Exchange for gameToken
↓
Backend: getProfile(gameToken) → Get game profile
↓
Backend: getBalance(gameToken) → Get balances
↓
Backend: getServerTime() → Sync time
↓
Game Ready ✓🌐 Platform Support
| Feature | Browser | MoMo App | Notes | |---------|---------|----------|-------| | Authentication | ✅ | ✅ | Mock in browser | | Storage | ✅ | ✅ | localStorage / native | | Calendar | ❌ | ✅ | Native only | | Notifications | ❌ | ✅ | Native only | | Game APIs | ✅ | ✅ | Full support |
⚙️ Configuration
TypeScript
The SDK is written in TypeScript and includes type definitions:
import GamiSDK, { TBalance, TLeaderboard, IUserInfo } from '@momo-cloud/gami-sdk';
const balance: TBalance = await GamiSDK.getBalance({
balanceIds: ['coin']
});Vite Integration
// vite.config.ts
import { defineConfig } from 'vite';
export default defineConfig({
resolve: {
alias: {
'@sdk': '@momo-cloud/gami-sdk'
}
}
});📄 License
UNLICENSED
