> ## Documentation Index
> Fetch the complete documentation index at: https://docs.engagefabric.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Player Management

> Manage gamification players with EngageFabric. Create profiles, track XP and levels, adjust currencies, and query player activity history.

## Overview

Players are the core entities in EngageFabric. Each player represents a user in your application who can earn XP, level up, complete quests, and appear on leaderboards.

## Creating Players

Players are identified by an `externalUserId` - typically the user ID from your own system.

<CodeGroup>
  ```javascript SDK theme={null}
  import { EngageFabric } from '@engagefabricsdk/sdk';

  const client = new EngageFabric({
    apiKey: 'your-api-key',
    projectId: 'your-project-id'
  });

  // Create or get existing player
  const player = await client.players.upsert({
    externalUserId: 'user-123',
    displayName: 'John Doe',
    avatarUrl: 'https://example.com/avatar.jpg',
    metadata: {
      email: 'john@example.com',
      tier: 'premium'
    }
  });
  ```

  ```bash cURL theme={null}
  curl -X POST https://api.engagefabric.com/api/v1/players \
    -H "Authorization: Bearer your-api-key" \
    -H "Content-Type: application/json" \
    -d '{
      "externalUserId": "user-123",
      "displayName": "John Doe",
      "avatarUrl": "https://example.com/avatar.jpg",
      "metadata": {
        "email": "john@example.com",
        "tier": "premium"
      }
    }'
  ```
</CodeGroup>

## Retrieving Players

### Get by External User ID

```javascript theme={null}
const player = await client.players.getByExternalId('user-123');
console.log(player);
// {
//   id: 'player-uuid',
//   externalUserId: 'user-123',
//   displayName: 'John Doe',
//   xp: 1500,
//   level: 5,
//   currencies: { coins: 100, gems: 10 },
//   ...
// }
```

### Get Player State

Retrieve comprehensive player state including XP, level, currencies, and active quests:

```javascript theme={null}
const state = await client.players.getState('user-123');
console.log(state);
// {
//   xp: 1500,
//   level: 5,
//   xpToNextLevel: 500,
//   levelProgress: 0.75,
//   currencies: { coins: 100, gems: 10 },
//   lives: { current: 5, max: 5 },
//   activeQuests: [...],
//   badges: [...]
// }
```

## Updating Players

### Update Profile

```javascript theme={null}
await client.players.update('user-123', {
  displayName: 'John D.',
  avatarUrl: 'https://example.com/new-avatar.jpg',
  metadata: {
    tier: 'gold'
  }
});
```

### Add XP

XP is typically awarded through the Rules Engine via events, but you can also add it directly:

```javascript theme={null}
await client.players.addXp('user-123', {
  amount: 100,
  reason: 'Manual reward'
});
```

### Modify Currencies

```javascript theme={null}
// Add currency
await client.players.addCurrency('user-123', {
  currency: 'coins',
  amount: 50,
  reason: 'Daily bonus'
});

// Deduct currency
await client.players.deductCurrency('user-123', {
  currency: 'coins',
  amount: 25,
  reason: 'Item purchase'
});
```

## Player Metadata

Metadata allows you to store custom data with each player. This is useful for:

* Storing user preferences
* Tracking subscription tiers
* Custom segmentation
* Integration with your app's data

```javascript theme={null}
// Update specific metadata fields (merge)
await client.players.updateMetadata('user-123', {
  preferredLanguage: 'en',
  notificationsEnabled: true
});

// Replace all metadata
await client.players.setMetadata('user-123', {
  preferredLanguage: 'es'
});
```

## Listing Players

```javascript theme={null}
const { players, total, page } = await client.players.list({
  page: 1,
  limit: 20,
  sortBy: 'xp',
  sortOrder: 'desc'
});
```

## Deleting Players

<Warning>
  Deleting a player removes all their progress, quest completions, and leaderboard entries.
  This action cannot be undone.
</Warning>

```javascript theme={null}
await client.players.delete('user-123');
```

***

## Admin Operations

These endpoints are available to authenticated admin users via the Admin Console or JWT authentication.

### Player Activity Log

View a complete activity history for a player, including client events and system events:

```bash theme={null}
curl -X GET "https://api.engagefabric.com/api/v1/players/{playerId}/activity?limit=50&offset=0" \
  -H "Authorization: Bearer your-jwt-token"
```

**Response:**

```json theme={null}
{
  "events": [
    {
      "id": "evt-123",
      "type": "CLIENT",
      "name": "lesson_completed",
      "properties": { "courseId": "math-101", "score": 95 },
      "createdAt": "2025-12-01T10:30:00Z",
      "status": "COMPLETED"
    },
    {
      "id": "evt-124",
      "type": "SYSTEM",
      "name": "xp_granted",
      "properties": { "amount": 100, "source": "rule" },
      "createdAt": "2025-12-01T10:30:01Z",
      "status": "COMPLETED"
    }
  ],
  "total": 156,
  "limit": 50,
  "offset": 0
}
```

### Admin XP Adjustment

Admins can manually adjust player XP with an audit trail:

```bash theme={null}
curl -X POST "https://api.engagefabric.com/api/v1/players/{playerId}/adjust-xp" \
  -H "Authorization: Bearer your-jwt-token" \
  -H "Content-Type: application/json" \
  -d '{
    "amount": 500,
    "reason": "Customer support compensation"
  }'
```

<Note>
  Negative amounts are allowed for XP deductions. All adjustments are logged to the audit trail.
</Note>

### Admin Currency Adjustment

Admins can adjust any currency balance:

```bash theme={null}
curl -X POST "https://api.engagefabric.com/api/v1/players/{playerId}/adjust-currency" \
  -H "Authorization: Bearer your-jwt-token" \
  -H "Content-Type: application/json" \
  -d '{
    "currency": "coins",
    "amount": 1000,
    "reason": "Promotional bonus"
  }'
```

<Info>
  All admin adjustments are recorded in the **Audit Log** with the admin's identity, timestamp, and reason. This ensures accountability and enables compliance reporting.
</Info>

## Best Practices

<CardGroup cols={2}>
  <Card title="Use Consistent IDs" icon="fingerprint">
    Always use the same `externalUserId` format across your application to avoid duplicate players.
  </Card>

  <Card title="Batch Operations" icon="layer-group">
    When updating multiple players, use batch endpoints to reduce API calls and improve performance.
  </Card>

  <Card title="Cache Player State" icon="database">
    Cache player state on the client side and use webhooks to invalidate when changes occur.
  </Card>

  <Card title="Handle Conflicts" icon="triangle-exclamation">
    Use upsert operations when player creation might race with other operations.
  </Card>
</CardGroup>

## Related

<CardGroup cols={2}>
  <Card title="Event Tracking" icon="bolt" href="/guides/event-tracking">
    Learn how to track player actions and trigger rewards
  </Card>

  <Card title="Game Economy" icon="coins" href="/concepts/game-economy">
    Understand XP, levels, and currencies
  </Card>
</CardGroup>
