Player Balance API
The Player Balance API provides real-time access to player currency balances across all registered games. Built to handle 60M+ users with sub-100ms response times and comprehensive balance management features.
Real-time Balances
Get instant access to current player balances with live updates and transaction processing.
Multi-Currency Support
Support multiple virtual currencies per game with automatic conversion and exchange rates.
Reserved Balances
Track reserved funds for pending transactions, ensuring accurate available balance calculations.
High Performance
Sub-100ms response times with advanced caching and optimized database queries.
Batch Operations
Efficiently query multiple player balances in a single API call for better performance.
Balance Analytics
Comprehensive balance history and analytics for player spending patterns and trends.
Balance Structure
Player balances are structured to provide comprehensive information about available funds, reserved amounts, and transaction history:
{
"player": {
"player_id": 12345,
"player_name": "John Doe",
"player_email": "john.doe@example.com",
"date_joined": "2024-01-15T10:30:00Z",
"last_active": "2024-12-09T12:34:56Z"
},
"balances": [
{
"currency_id": 1,
"currency_name": "Gold Coins",
"currency_symbol": "GC",
"available_balance": "150.00", // Funds available for spending
"reserved_balance": "25.00", // Funds reserved for pending transactions
"total_balance": "175.00", // Total balance (available + reserved)
"last_transaction": "2024-12-09T11:45:30Z"
},
{
"currency_id": 2,
"currency_name": "Premium Gems",
"currency_symbol": "PG",
"available_balance": "500.00",
"reserved_balance": "0.00",
"total_balance": "500.00",
"last_transaction": "2024-12-08T15:22:10Z"
}
],
"summary": {
"total_currencies": 2,
"total_value_usd": "67.50", // Approximate USD value
"has_funds": true,
"last_updated": "2024-12-09T12:34:56Z"
}
}Balance Types Explained
Available Balance
Funds that can be immediately spent or transferred. This is the amount players can use for purchases or transfers.
Use for: Purchase validation, transfer limits, spending checks
Reserved Balance
Funds temporarily held for pending transactions like transfers awaiting SMS verification or processing payments.
Use for: Transaction tracking, pending operation displays
Total Balance
Complete balance including both available and reserved funds. Represents the player's total currency holdings.
Use for: Portfolio displays, wealth tracking, analytics
Core API Endpoints
Get Player Balance
GET /api/player-balances/player/{player_id}Retrieve current balance for a specific player by their player ID.
Example Response:
{
"player": {
"player_id": 12345,
"player_name": "John Doe",
"player_email": "john@example.com"
},
"balances": [
{
"currency_id": 1,
"currency_name": "Gold Coins",
"available_balance": "1500.00",
"reserved_balance": "50.00",
"total_balance": "1550.00"
}
]
}Get Balance by Email
GET /api/player-balances/player/by-email/{email}Look up player balance using their email address - the most common method for game integration.
Authentication Required:
const response = await fetch(
'https://invo.network/api/player-balances/player/by-email/john@example.com',
{ headers: { 'X-Game-Secret-Key': 'ivsdk_your_key_here' } }
);Batch Balance Query
POST /api/player-balances/batchGet balances for multiple players at once - perfect for leaderboards, tournaments, or analytics.
Request Body:
{
"player_emails": [
"player1@example.com",
"player2@example.com",
"player3@example.com"
],
"include_summary": true
}Response:
{
"players": [
{
"player_email": "player1@example.com",
"balances": [...],
"total_value": "1250.00"
}
],
"summary": {
"total_players": 3,
"total_value": "5430.00"
}
}Balance Operations
Credit Operations
Credit Player Balance
Add funds to a player's available balance
POST /api/player-balances/creditPurchase Rewards
Credit currency after real money purchases
POST /api/currency-purchases/confirm-paymentDebit Operations
Debit Player Balance
Remove funds from a player's balance
POST /api/player-balances/debitItem Purchases
Debit currency for in-game item purchases
POST /api/item-purchases/purchase-itemBalance Validation Example
Here's how to validate if a player has sufficient funds before processing a purchase:
// Check if player has sufficient balance for a purchase
async function validatePurchase(playerEmail, currencyId, amount) {
try {
// Get current player balance
const response = await fetch(
`https://invo.network/api/player-balances/player/by-email/${encodeURIComponent(playerEmail)}`,
{ headers: { 'X-Game-Secret-Key': SDK_KEY } }
);
const balanceData = await response.json();
// Find the specific currency balance
const currencyBalance = balanceData.balances.find(
balance => balance.currency_id === currencyId
);
if (!currencyBalance) {
return {
valid: false,
error: 'Currency not found for player'
};
}
// Check if available balance is sufficient
const availableAmount = parseFloat(currencyBalance.available_balance);
const purchaseAmount = parseFloat(amount);
if (availableAmount >= purchaseAmount) {
return {
valid: true,
available_balance: availableAmount,
purchase_amount: purchaseAmount,
remaining_balance: availableAmount - purchaseAmount
};
} else {
return {
valid: false,
error: 'Insufficient funds',
available_balance: availableAmount,
required_amount: purchaseAmount,
shortfall: purchaseAmount - availableAmount
};
}
} catch (error) {
return {
valid: false,
error: 'Failed to validate balance: ' + error.message
};
}
}
// Usage example
const validation = await validatePurchase('player@example.com', 1, '25.00');
if (validation.valid) {
console.log('Purchase approved:', validation);
// Proceed with purchase
} else {
console.log('Purchase denied:', validation.error);
// Show error to player
}Performance & Optimization
High-Performance Architecture
The Balance API is optimized for high performance with several caching layers:
- • Redis Cache: Sub-10ms response times for frequently accessed balances
- • Database Optimization: Indexed queries and read replicas for scalability
- • CDN Distribution: Global edge caching for reduced latency
- • Batch Processing: Efficient multi-player balance queries
- • Real-time Updates: WebSocket connections for live balance changes
- • Auto-scaling: Handles 60M+ users with elastic infrastructure
Rate Limits
⚡ Balance Query Limits
- • Individual queries: 2,000/minute per game
- • Batch queries: 100/minute per game
- • Email lookups: 1,500/minute per game
- • Burst allowance: 50% additional capacity
📊 Optimization Tips
- • Use batch queries for multiple players
- • Cache balance data on your side for 30-60 seconds
- • Implement exponential backoff for retries
- • Use webhooks for real-time balance updates
Error Handling
Common Error Responses
400 - Bad RequestInvalid player ID, email format, or missing parameters
401 - UnauthorizedInvalid or missing SDK key in Authorization header
404 - Not FoundPlayer not found or no balance data available
429 - Too Many RequestsRate limit exceeded, implement exponential backoff
500 - Internal Server ErrorTemporary service issue, retry with exponential backoff
Best Practices
💡 Integration Best Practices
- • Always check available_balance before allowing purchases or transfers
- • Use email-based lookups for better user experience
- • Implement client-side caching with 30-60 second TTL
- • Use batch queries when displaying multiple player balances
- • Handle rate limits gracefully with exponential backoff
- • Monitor balance query patterns and optimize accordingly
⚠️ Important Considerations
- • Reserved balances are not available for spending - always check available_balance
- • Player balances update in real-time across all games in the network
- • New players automatically receive starting currency amounts as configured
- • Balance history is maintained indefinitely for compliance and analytics
- • All monetary values are returned as strings to prevent floating-point precision issues
- • SDK keys must be used server-side only - never expose in client code
Real-time Balance Updates
WebSocket Integration
For real-time balance updates in your game, consider implementing WebSocket connections:
// WebSocket connection for real-time balance updates
const socket = new WebSocket('wss://invo.network/ws/balance-updates');
socket.onopen = function() {
// Subscribe to balance updates for specific players
socket.send(JSON.stringify({
action: 'subscribe_player_balances',
player_emails: ['player1@example.com', 'player2@example.com'],
auth_token: 'Bearer ' + SDK_KEY
}));
};
socket.onmessage = function(event) {
const update = JSON.parse(event.data);
if (update.type === 'balance_update') {
console.log('Balance updated:', update.player_email, update.new_balance);
// Update your game UI with new balance
updatePlayerBalanceUI(update.player_email, update.new_balance);
}
};