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

# Usage Examples

> Examples for calling the Plugin API from your own plugin, bot or backend.

In the examples below, replace `https://your-site.com` with your site and `YOUR_API_KEY` with the key from **Settings → API**.

> [!WARNING]
>
> These examples must run **on a server** (game server, bot host, your own backend). Never put the API key anywhere a browser or a player can reach.

## Client setup

```js Node.js theme={null}
const BASE = 'https://your-site.com/api';
const KEY = process.env.LEADEROS_API_KEY;

async function leaderos(method, path, body) {
  const res = await fetch(BASE + path, {
    method,
    headers: { 'X-Api-Key': KEY },
    // Form body: not JSON!
    body: body ? new URLSearchParams(body) : undefined,
  });
  const json = await res.json().catch(() => null);
  if (json && json.status === false) throw Object.assign(new Error(json.error), { code: json.error, json });
  return json;
}
```

```php PHP theme={null}
<?php
function leaderos(string $method, string $path, array $body = []) {
    $ch = curl_init('https://your-site.com/api' . $path);
    curl_setopt_array($ch, [
        CURLOPT_CUSTOMREQUEST  => $method,
        CURLOPT_HTTPHEADER     => ['X-Api-Key: ' . getenv('LEADEROS_API_KEY')],
        CURLOPT_RETURNTRANSFER => true,
    ]);
    if ($body) curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($body));
    $json = json_decode(curl_exec($ch), true);
    curl_close($ch);
    return $json;
}
```

```python Python theme={null}
import os, requests

BASE = "https://your-site.com/api"
HEADERS = {"X-Api-Key": os.environ["LEADEROS_API_KEY"]}

def leaderos(method, path, data=None):
    r = requests.request(method, BASE + path, headers=HEADERS, data=data)  # data= sends a form
    return r.json()
```

```java Java theme={null}
HttpClient client = HttpClient.newHttpClient();
String form = "target_username=" + URLEncoder.encode("Steve", UTF_8) + "&amount=25";
HttpRequest req = HttpRequest.newBuilder(URI.create("https://your-site.com/api/credits/add"))
    .header("X-Api-Key", apiKey)
    .header("Content-Type", "application/x-www-form-urlencoded")
    .POST(HttpRequest.BodyPublishers.ofString(form))
    .build();
String body = client.send(req, HttpResponse.BodyHandlers.ofString()).body();
```

## Users and balance

```bash theme={null}
# By username or ID
curl -H "X-Api-Key: YOUR_API_KEY" "https://your-site.com/api/users?username=Steve"
curl -H "X-Api-Key: YOUR_API_KEY" "https://your-site.com/api/credits?userID=42"
```

The `GET /users` response contains the account without the password, plus a `linkedAccounts` object (e.g. `{ "discord": "1234…" }`).

## Credit operations

```js theme={null}
await leaderos('POST', '/credits/add',    { target_username: 'Steve', amount: 50 });
await leaderos('POST', '/credits/remove', { target_username: 'Steve', amount: 10 });
await leaderos('POST', '/credits/set',    { target_username: 'Steve', amount: 100 });

// Player to player ("can send credits" must be on in the credit module)
await leaderos('POST', '/credits/send', {
  sender_username: 'Steve',
  target_username: 'Alex',
  amount: 5,
});
```

> [!TIP]
>
> Use `/credits/add` for vote rewards, event prizes or a Discord level system, for example. Add and remove are written to the player's credit history; `/credits/set` is not.

## Buying products with credits

Products are sent as a form array:

```bash theme={null}
curl -X POST https://your-site.com/api/store/buy \
  -H "X-Api-Key: YOUR_API_KEY" \
  -d "userID=42" \
  -d "products[0][id]=12" \
  -d "products[0][quantity]=1" \
  -d "products[1][id]=7" \
  -d "products[1][variables][3]=red"
```

```js theme={null}
await leaderos('POST', '/store/buy', {
  userID: 42,
  'products[0][id]': 12,
  'products[0][quantity]': 1,
});
```

A purchase follows the same rules as the website: discounts, subscription upgrades, required products, required linked accounts, tax, stock and cashback apply; commands and roles are delivered. Possible errors: `INSUFFICIENT_BALANCE`, `OUT_OF_STOCK`, `REQUIRED_PRODUCT`, `REQUIRED_LINKED_ACCOUNT`, `DOWNGRADE_NOT_ALLOWED`, `INVALID_VARIABLE`.

For an in-game store menu, `GET /store/listing?username=Steve` returns the category tree for that player with final prices and upgrade info.

## Roles

```bash theme={null}
# Give a role (empty expiryDate = never expires)
curl -X POST https://your-site.com/api/users/42/roles \
  -H "X-Api-Key: YOUR_API_KEY" \
  -d "roleID=3" -d "expiryDate=2026-12-31 23:59:59"

# Change a role (3 in the URL = current role)
curl -X PATCH https://your-site.com/api/users/42/roles/3 \
  -H "X-Api-Key: YOUR_API_KEY" \
  -d "roleID=5"

# Remove a role
curl -X DELETE https://your-site.com/api/users/42/roles/5 -H "X-Api-Key: YOUR_API_KEY"
```

## Support tickets

```js theme={null}
const { data } = await leaderos('POST', '/support/tickets', {
  userID: 42,
  categoryID: 1,
  title: 'Payment issue',
  message: 'My credits were not added.',
});

await leaderos('POST', `/support/tickets/${data.id}/close`);
```

Opening a ticket sends a Discord webhook notification (if configured).

## Discord bot

```bash theme={null}
curl -H "X-Api-Key: YOUR_API_KEY" https://your-site.com/api/integrations/discord/users/123456789012345678
curl -H "X-Api-Key: YOUR_API_KEY" https://your-site.com/api/integrations/discord/roles
curl -H "X-Api-Key: YOUR_API_KEY" https://your-site.com/api/integrations/discord/settings
```

Get a user and their roles by Discord ID, then sync roles on your server using the `discordRoleID` mapping.

## Donor board (scoreboard, hologram)

```bash theme={null}
curl -H "X-Api-Key: YOUR_API_KEY" "https://your-site.com/api/store/donations?type=top-monthly&limit=5"
```

`type`: `top-alltime`, `top-annual`, `top-monthly`, `top-daily`, `latest`. `limit`: 1–10.

## Error handling

```js theme={null}
try {
  await leaderos('POST', '/store/buy', { userID: 42, 'products[0][id]': 12 });
} catch (e) {
  switch (e.code) {
    case 'INSUFFICIENT_BALANCE': /* "Not enough credits" */ break;
    case 'OUT_OF_STOCK':         /* "Out of stock" */ break;
    case 'VALIDATION':           console.log(e.json.message); break;
    default:                     console.error(e.code);
  }
}
```

> [!NOTE]
>
> Error messages are in English and may change. Build the text you show players **from the `error` code**, in your own language.

## Tips

* **Caching:** cache data that rarely changes, such as `/store/listing`, `/store/products` and `/vote-links`, for a few minutes in your plugin.
* **Async calls:** do not call the API on the game server's main thread; the server may freeze.
* **Usernames:** on Minecraft sites `username` parameters match the player's real name (`realname`); on other games, the account username.
* **Time zone:** dates are in the site's time zone (except role expiry dates in the Discord user endpoint, which are UTC).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.