Skip to main content

Integration Guide

This guide provides comprehensive information on integrating your game with the DNA Platform. Follow these steps to implement our API, authenticate securely, and see working examples.

API Overview

The DNA Platform offers a robust API that allows developers to interact with various platform features.

API Architecture

Our API follows REST principles with JSON as the primary data format:

  • Base URL: https://api.dna.game
  • Partner API Path: /api/v1/partner
  • Request Format: JSON
  • Response Format: JSON
  • Rate Limits: Rate limits are communicated in response headers:
    • X-RateLimit-Limit: Total requests allowed in the window
    • X-RateLimit-Remaining: Requests remaining in the current window
    • X-RateLimit-Reset: Time when the rate limit will reset (Unix timestamp)

Available Endpoints

The API is organized into several key areas:

  1. Games: Endpoints for managing game registrations and configurations
  2. Achievements: APIs for creating, updating, and verifying achievements
  3. Players: Endpoints for player information and DNA profiles
  4. Campaigns: APIs for campaign creation and management
  5. Analytics: Endpoints for retrieving game and player analytics
  6. Identity: Endpoints for cross-platform identity resolution

API Reference

The full API reference is available at our interactive documentation portal:

Authentication

Secure authentication is essential for protecting player data and ensuring API security.

API Keys

For server-to-server communication:

  1. Generate API keys in the Developer Dashboard
  2. Include your API key in the X-API-Key header
  3. Keep your API key secure and never expose it in client-side code
const fetchPlayerData = async (playerId: string) => {
  const response = await fetch(`https://api.dna.game/api/v1/partner/players/${playerId}`, {
    method: 'GET',
    headers: {
      'X-API-Key': 'YOUR_API_KEY',
      'Content-Type': 'application/json'
    }
  });
  return response.json();
};

OAuth 2.0

For player authentication:

  1. Register your application in the Developer Dashboard
  2. Implement the OAuth 2.0 authorization code flow
  3. Request appropriate scopes based on your needs
// Example OAuth 2.0 redirect
const initiateOAuth = () => {
  const clientId = 'YOUR_CLIENT_ID';
  const redirectUri = encodeURIComponent('YOUR_REDIRECT_URI');
  const scopes = encodeURIComponent('profile achievements dna');
  
  window.location.href = `https://auth.dna.game/oauth/authorize?client_id=${clientId}&redirect_uri=${redirectUri}&scope=${scopes}&response_type=code`;
};

JWT Authentication

For authenticated player sessions:

  1. Exchange OAuth code for access and refresh tokens
  2. Include the access token in the Authorization header
  3. Implement token refresh logic for expired tokens
const fetchPlayerProfile = async (accessToken: string) => {
  const response = await fetch('https://api.dna.game/v1/player/profile', {
    method: 'GET',
    headers: {
      'Authorization': `Bearer ${accessToken}`,
      'Content-Type': 'application/json'
    }
  });
  return response.json();
};

Direct API Integration

Currently, the DNA Platform is available exclusively through direct API integration. This approach gives you the most flexibility and control over how you implement our features in your game.

Integration Approach

To integrate with the DNA Platform:

  1. Use the authentication methods described above to secure your API calls
  2. Implement the necessary API endpoints for your specific use cases
  3. Set up error handling and retry logic for production reliability
  4. Consider implementing a caching layer for frequently accessed data

Best Practices

When implementing a direct API integration:

  1. Error Handling: Implement robust error handling for all API calls
  2. Rate Limiting: Respect the rate limits specified in response headers
  3. Caching: Cache appropriate responses to minimize API calls
  4. Logging: Maintain detailed logs for troubleshooting
  5. Retry Logic: Implement exponential backoff for failed requests

Implementation Examples

The following examples demonstrate common integration scenarios using direct API calls.

Player Authentication

// Direct API authentication example
const authenticatePlayer = async (username, password) => {
  try {
    // Request access token
    const tokenResponse = await fetch('https://api.dna.game/api/v1/auth/token', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        grant_type: 'password',
        username,
        password,
        client_id: 'YOUR_CLIENT_ID'
      })
    });
    
    const tokenData = await tokenResponse.json();
    
    if (!tokenResponse.ok) {
      throw new Error(tokenData.message || 'Authentication failed');
    }
    
    // Store the tokens securely
    const { access_token, refresh_token } = tokenData;
    
    // Get the authenticated player's profile
    const profileResponse = await fetch('https://api.dna.game/api/v1/player/profile', {
      headers: {
        'Authorization': `Bearer ${access_token}`
      }
    });
    
    return await profileResponse.json();
  } catch (error) {
    console.error('Authentication failed:', error);
    throw error;
  }
};

Reporting Achievements

// Direct API achievement reporting
const reportAchievement = async (gameId, playerId, achievementId, apiKey) => {
  try {
    const response = await fetch('https://api.dna.game/api/v1/partner/achievements/report', {
      method: 'POST',
      headers: {
        'X-API-Key': apiKey,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        game_id: gameId,
        player_id: playerId,
        achievement_id: achievementId,
        unlock_time: new Date().toISOString(),
        verification_data: {
          difficulty: 'hard',
          time_to_complete: 3600 // in seconds
        }
      })
    });
    
    const result = await response.json();
    console.log('Achievement reported:', result.status);
    return result.status === 'success';
  } catch (error) {
    console.error('Failed to report achievement:', error);
    return false;
  }
};

Accessing Player DNA

// Direct API player DNA access
const getPlayerTraits = async (playerId, apiKey) => {
  try {
    const response = await fetch(`https://api.dna.game/api/v1/partner/players/${playerId}/dna`, {
      method: 'GET',
      headers: {
        'X-API-Key': apiKey,
        'Content-Type': 'application/json'
      }
    });
    
    const dnaProfile = await response.json();
    
    // Access the player's traits
    const traits = Object.values(dnaProfile.traits);
    
    // Find traits with high confidence (>0.7)
    const strongTraits = traits.filter(trait => trait.confidence > 0.7);
    
    console.log('Player strong traits:', strongTraits);
    return strongTraits;
  } catch (error) {
    console.error('Failed to get player traits:', error);
    return [];
  }
};

Creating a Campaign

// Direct API campaign creation
const createCampaign = async (apiKey) => {
  try {
    const response = await fetch('https://api.dna.game/api/v1/partner/campaigns', {
      method: 'POST',
      headers: {
        'X-API-Key': apiKey,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        name: 'Summer Challenge 2025',
        description: 'Complete challenges to earn exclusive rewards!',
        start_date: '2025-06-01T00:00:00Z',
        end_date: '2025-08-31T23:59:59Z',
        requirements: [
          {
            type: 'ACHIEVEMENT',
            achievement_id: 'summer_boss_defeated',
            count: 1
          },
          {
            type: 'PLAYTIME',
            minutes: 120
          }
        ],
        rewards: [
          {
            type: 'IN_GAME_ITEM',
            item_id: 'summer_sword',
            name: 'Sword of Summer'
          },
          {
            type: 'BADGE',
            badge_id: 'summer_champion_2025'
          }
        ]
      })
    });
    
    const campaign = await response.json();
    console.log('Campaign created:', campaign.id);
    return campaign;
  } catch (error) {
    console.error('Failed to create campaign:', error);
    return null;
  }
};

Webhooks

Set up webhooks to receive real-time notifications:

  1. Configure webhook endpoints in the Developer Dashboard
  2. Implement handlers for the following events:
    • Achievement Unlocked
    • Campaign Completed
    • Player DNA Updated
    • Profile Updated
// Example webhook handler (Express.js)
import express from 'express';
import bodyParser from 'json-parser';
import crypto from 'crypto';

const app = express();
app.use(bodyParser.json());

// Verify webhook signature
const verifySignature = (req) => {
  const signature = req.headers['x-dna-signature'];
  const hmac = crypto.createHmac('sha256', 'YOUR_WEBHOOK_SECRET');
  const digest = hmac.update(JSON.stringify(req.body)).digest('hex');
  return signature === digest;
};

// Achievement webhook handler
app.post('/webhooks/achievements', (req, res) => {
  if (!verifySignature(req)) {
    return res.status(401).send('Invalid signature');
  }
  
  const { playerId, achievementId, timestamp } = req.body;
  console.log(`Player ${playerId} unlocked achievement ${achievementId} at ${timestamp}`);
  
  // Process the achievement
  // ...
  
  res.status(200).send('Webhook received');
});

app.listen(3000, () => {
  console.log('Webhook server running on port 3000');
});

WebSocket API for Real-Time Events

The DNA Platform provides a WebSocket API for receiving real-time events:

Connection

Connect to the WebSocket endpoint with your API key:

const socket = new WebSocket('wss://api.dna.game/partner/events?api_key=YOUR_API_KEY');

socket.onopen = () => {
  console.log('Connected to DNA Platform events');
};

socket.onclose = (event) => {
  console.log('Disconnected from DNA Platform events:', event.code, event.reason);
};

socket.onerror = (error) => {
  console.error('WebSocket error:', error);
};

Event Handling

Handle incoming events based on their type:

socket.onmessage = (event) => {
  const data = JSON.parse(event.data);
  
  switch (data.event_type) {
    case 'ACHIEVEMENT_POSTED':
      handleAchievementPosted(data.data);
      break;
    case 'DNA_UPDATED':
      handleDNAUpdated(data.data);
      break;
    case 'CAMPAIGN_UPDATE':
      handleCampaignUpdate(data.data);
      break;
    default:
      console.log('Unknown event type:', data.event_type);
  }
};

// Example event handlers
function handleAchievementPosted(data) {
  console.log(`Player ${data.player_id} unlocked achievement ${data.achievement_id} in game ${data.game_id}`);
  // Update UI, trigger notifications, etc.
}

function handleDNAUpdated(data) {
  console.log(`Player ${data.player_id} DNA updated with new traits:`, data.new_traits);
  // Update player profile, adjust game experience, etc.
}

function handleCampaignUpdate(data) {
  console.log(`Campaign ${data.campaign_id} update: ${data.status}`);
  // Update campaign UI, notify players, etc.
}

Reconnection Strategy

Implement a robust reconnection strategy for production use:

let reconnectAttempts = 0;
const maxReconnectAttempts = 10;
const baseReconnectDelay = 1000; // 1 second

function connectWebSocket() {
  const socket = new WebSocket('wss://api.dna.game/partner/events?api_key=YOUR_API_KEY');
  
  socket.onopen = () => {
    console.log('Connected to DNA Platform events');
    reconnectAttempts = 0;
  };
  
  socket.onclose = (event) => {
    if (event.code !== 1000) { // Not a normal closure
      if (reconnectAttempts < maxReconnectAttempts) {
        const delay = baseReconnectDelay * Math.pow(1.5, reconnectAttempts);
        console.log(`Reconnecting in ${delay}ms...`);
        setTimeout(connectWebSocket, delay);
        reconnectAttempts++;
      } else {
        console.error('Max reconnect attempts reached');
      }
    }
  };
  
  // Add other event handlers...
  
  return socket;
}

const socket = connectWebSocket();

Troubleshooting

Common integration issues and their solutions:

API Errors

  • 401 Unauthorized: Check your API key or access token
  • 403 Forbidden: Verify that your API key has the necessary permissions
  • 429 Too Many Requests: You've exceeded the rate limit, implement backoff strategy

Support Resources

Next Steps

Now that you understand how to integrate with the DNA Platform, you might want to: