Package Exports
- playe-developer-sdk
- playe-developer-sdk/package.json
Readme
Playe Developer SDK
A comprehensive browser-based SDK for integrating games with the Playe platform. This SDK provides easy-to-use APIs for game session management, campaign integration, leaderboards, and anti-cheat validation.
Features
- 🎮 Game Session Management - Initialize, start, update, and complete game sessions
- 🏆 Campaign Integration - Access campaign information, leaderboards, and player attempts
- 🛡️ Anti-Cheat Protection - Built-in validation and heartbeat mechanisms
- 📱 Device Detection - Automatic device information and fingerprinting
- 🔧 Developer Tools - Test game sessions and debugging utilities
- 📊 Real-time Updates - Progress tracking and live leaderboards
- ⚡ Browser Optimized - Lightweight and fast for web games
Installation
NPM (Recommended)
npm install playe-developer-sdk
# or
yarn add playe-developer-sdk
# or
pnpm add playe-developer-sdkCDN (No build tools required)
<!-- For production -->
<script src="https://unpkg.com/playe-developer-sdk@latest/dist/playe-sdk.umd.min.js"></script>
<!-- Alternative CDN -->
<script src="https://cdn.jsdelivr.net/npm/playe-developer-sdk@latest/dist/playe-sdk.umd.min.js"></script>Workspace (Internal development)
{
"dependencies": {
"@workspace/playe-developer-sdk": "workspace:*"
}
}Quick Start
NPM Usage
import { createPlayeSDK } from 'playe-developer-sdk';
// Initialize the SDK
const sdk = createPlayeSDK({
apiBaseUrl: 'https://api.playe.com',
apiKey: 'your-api-key',
enableDebugMode: true, // Enable for development
});
// Initialize a game session
const session = await sdk.initializeGameSession({
campaignId: 'campaign-123',
gameId: 'game-456',
playerFingerprint: 'unique-player-fingerprint',
playerEmail: 'player@example.com',
});
// Start the game
await sdk.startGameSession(session.sessionId);
// Update progress during gameplay
await sdk.updateGameProgress(session.sessionId, {
currentScore: 1500,
elapsedTime: 120, // seconds
gameState: { level: 3, lives: 2 },
});
// Complete the game
const result = await sdk.completeGame(session.sessionId, {
finalScore: 2500,
gameMetrics: {
totalPlayTime: 300,
actionsPerformed: 150,
powerUpsUsed: 5,
levelsCompleted: 5,
},
});
console.log('Game completed!', {
isWinner: result.isWinner,
finalRank: result.finalRank,
prizeAmount: result.prizeAmount,
});CDN Usage
<script src="https://unpkg.com/playe-developer-sdk@latest/dist/playe-sdk.umd.min.js"></script>
<script>
// SDK is available as global PlayeSDK
const sdk = PlayeSDK.createPlayeSDK({
apiBaseUrl: 'https://api.playe.com',
apiKey: 'your-api-key',
enableDebugMode: true,
});
// All utilities are available
const fingerprint = PlayeSDK.DeviceUtils.generateFingerprint();
// Same API as NPM version
const session = await sdk.initializeGameSession({
campaignId: 'campaign-123',
gameId: 'game-456',
playerFingerprint: fingerprint,
});
</script>API Reference
SDK Configuration
interface SDKConfig {
apiBaseUrl: string; // Required: API base URL
apiKey?: string; // Optional: API key for authentication
enableDebugMode?: boolean; // Optional: Enable debug logging
retryAttempts?: number; // Optional: Number of retry attempts (default: 3)
timeoutMs?: number; // Optional: Request timeout in ms (default: 30000)
enableOfflineMode?: boolean; // Optional: Enable offline mode (default: false)
}Core Methods
Game Session Management
// Initialize a new game session
await sdk.initializeGameSession({
campaignId: string;
gameId: string;
playerFingerprint: string;
playerEmail?: string;
deviceInfo?: DeviceInfo;
receiptImage?: string; // Base64 encoded
geolocationData?: GeolocationData;
});
// Start the game session
await sdk.startGameSession(sessionId: string, config?: Record<string, any>);
// Update game progress
await sdk.updateGameProgress(sessionId: string, {
currentScore: number;
gameState?: Record<string, any>;
elapsedTime: number;
achievements?: Achievement[];
clientTimestamp?: string;
});
// Complete the game
await sdk.completeGame(sessionId: string, {
finalScore: number;
gameMetrics?: GameMetrics;
finalGameState?: Record<string, any>;
});
// Abandon the game
await sdk.abandonGame(sessionId: string, reason?: string, lastKnownScore?: number);Campaign Information
// Get campaign status
await sdk.getCampaignStatus(campaignId: string, playerId?: string);
// Get leaderboard
await sdk.getLeaderboard(campaignId: string, limit?: number, playerId?: string);
// Get player attempts
await sdk.getPlayerAttempts(campaignId: string, playerId: string);Validation & Anti-Cheat
// Validate game session
await sdk.validateGameSession(sessionId: string, validationData?: Record<string, any>);
// Send heartbeat (usually handled automatically)
await sdk.sendHeartbeat(sessionId: string, currentScore?: number);Utility Methods
// Test SDK functionality
sdk.test('Custom test message');
// Check if running in demo mode
const isDemoMode = sdk.isDemo();
// Game lifecycle events
sdk.gameLoadingStart();
sdk.gameLoadingFinished();
sdk.gamePlayStop();
// Clean up resources
sdk.destroy();Device Utilities
import { DeviceUtils } from '@workspace/playe-developer-sdk';
// Get device information
const deviceInfo = DeviceUtils.getDeviceInfo();
// Get geolocation
const location = await DeviceUtils.getGeolocationData();
// Generate fingerprint
const fingerprint = DeviceUtils.generateFingerprint();
// Check browser support
const isSupported = DeviceUtils.isBrowser();
const features = DeviceUtils.getFeatureSupport();Error Handling
import {
PlayeSDKError,
ValidationError,
NetworkError,
AuthenticationError,
GameSessionError
} from '@workspace/playe-developer-sdk';
try {
await sdk.initializeGameSession(params);
} catch (error) {
if (error instanceof ValidationError) {
console.error('Validation failed:', error.message);
} else if (error instanceof NetworkError) {
console.error('Network error:', error.message);
} else if (error instanceof AuthenticationError) {
console.error('Authentication failed:', error.message);
} else if (error instanceof PlayeSDKError) {
console.error('SDK error:', error.toJSON());
}
}Campaign Styles
The SDK supports different campaign styles:
- SingleWinner: One winner takes all
- FixedPool: Fixed number of winners
- Leaderboard: Winners based on ranking
- RewardForAll: Everyone gets rewards
Events
The SDK emits custom browser events for tracking:
// Listen for SDK events
window.addEventListener('playe:game-loading-start', () => {
console.log('Game loading started');
});
window.addEventListener('playe:game-loading-finished', () => {
console.log('Game loading finished');
});
window.addEventListener('playe:game-play-stop', () => {
console.log('Game play stopped');
});Development
Testing
// Create a test game session for development
const testSession = await sdk.createTestGameSession({
mockCampaign: true,
mockPlayers: 10,
testScenario: 'leaderboard',
});Debug Mode
Enable debug mode to see detailed logging:
const sdk = createPlayeSDK({
apiBaseUrl: 'https://api.playe.com',
enableDebugMode: true, // This will log all API calls and responses
});Browser Compatibility
- Chrome 60+
- Firefox 55+
- Safari 12+
- Edge 79+
Distribution
The SDK is available in multiple formats:
- NPM Package:
npm install playe-developer-sdk - CDN (UMD):
https://unpkg.com/playe-developer-sdk@latest/dist/playe-sdk.umd.min.js - Workspace:
@workspace/playe-developer-sdk(internal development)
Bundle Sizes
- ESM: 27.3KB (8KB gzipped)
- CommonJS: 27.6KB (8KB gzipped)
- UMD: 30.8KB (9KB gzipped)
- UMD Minified: 13.7KB (5KB gzipped)
For detailed distribution information, see DISTRIBUTION.md.
TypeScript Support
This SDK is written in TypeScript and includes full type definitions. No additional @types packages are needed.
License
MIT License - see LICENSE file for details.
Support
For support, please contact the Playe development team or create an issue in the repository.