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

# Примеры HTTP-запросов к Exchanger API

> Проверьте доступность Exchanger API через cURL и подпишите приватный ping на PHP, Python, JavaScript или TypeScript средствами вашего окружения.

Публичный ping проверяет адрес Exchanger API. Приватный ping на том же домене проверяет Bearer-токен и подпись HMAC v2 без дополнительного scope. Оба запроса только читают данные.

## Публичный запрос через cURL

Замените `your-exchange` на домен вашего обменника.

```bash theme={null}
curl --fail-with-body --silent --show-error --max-time 10 \
  --header 'Accept: application/json' \
  'https://your-exchange/api/v3/ping'
```

Ожидаемый ответ содержит `state: 0` и `result.status: "ok"`. В `result.site_name` и `result.time` приходят название обменника и его текущее время.

## Подписанный запрос

Получите [API-ключ](https://exchanger-api.iexexchanger.com/start/access.md) и задайте переменные окружения процесса, в котором запускаете пример.

| Переменная | Значение |
| - | - |
| `EXCHANGER_API_ORIGIN` | Прямой HTTPS-адрес установки, например `https://your-exchange`. |
| `EXCHANGER_API_TOKEN` | Bearer-токен целиком. |
| `EXCHANGER_API_HMAC_SECRET` | Секрет подписи, выданный с этим токеном. |

Запросы отправляют `GET /api/v3/private/ping` по HTTPS и используют новую nonce на каждый запуск. Подпись содержит хеш пустого тела, пустую строку query и пустой ключ идемпотентности. При успехе примеры ниже печатают `200 ok`.

### PHP

Сохраните файл как `ping.php` и запустите `php ping.php` на PHP 8.5 с расширением cURL.

```php ping.php theme={null}
<?php

declare(strict_types=1);

$address = getenv('EXCHANGER_API_ORIGIN');
$token = getenv('EXCHANGER_API_TOKEN');
$secret = getenv('EXCHANGER_API_HMAC_SECRET');
if ($address === false || $address === '' || $token === false || $token === '' || $secret === false || $secret === '') {
    fwrite(STDERR, "Set EXCHANGER_API_ORIGIN, EXCHANGER_API_TOKEN, and EXCHANGER_API_HMAC_SECRET.\n");
    exit(1);
}

$origin = parse_url($address);
if (
    ! is_array($origin)
    || ($origin['scheme'] ?? '') !== 'https'
    || empty($origin['host'])
    || ! in_array($origin['path'] ?? '', ['', '/'], true)
    || isset($origin['user']) || isset($origin['pass']) || isset($origin['query']) || isset($origin['fragment'])
) {
    fwrite(STDERR, "Use the direct HTTPS origin of your exchanger.\n");
    exit(1);
}

$path = '/api/v3/private/ping';
$timestamp = (string) time();
$nonce = bin2hex(random_bytes(16));
$canonical = implode("\n", ['v2', 'GET', $path, '', hash('sha256', ''), $timestamp, $nonce, '']);
$signature = hash_hmac('sha256', $canonical, $secret);

$request = curl_init(rtrim($address, '/').$path);
curl_setopt_array($request, [
    CURLOPT_PROTOCOLS_STR => 'HTTPS',
    CURLOPT_FOLLOWLOCATION => false,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CONNECTTIMEOUT => 5,
    CURLOPT_TIMEOUT => 10,
    CURLOPT_HTTPHEADER => [
        'Accept: application/json',
        'Authorization: Bearer '.$token,
        'X-Api-Signature-Version: v2',
        'X-Api-Timestamp: '.$timestamp,
        'X-Api-Nonce: '.$nonce,
        'X-Api-Signature: sha256='.$signature,
    ],
]);

$body = curl_exec($request);
if (! is_string($body)) {
    fwrite(STDERR, 'Could not read the API response. cURL error '.curl_errno($request)."\n");
    exit(1);
}

$status = curl_getinfo($request, CURLINFO_RESPONSE_CODE);
$envelope = json_decode($body, true);
if ($status !== 200 || ($envelope['state'] ?? null) !== 0 || ($envelope['result']['status'] ?? null) !== 'ok') {
    $code = $envelope['error']['code'] ?? 'unexpected_response';
    fwrite(STDERR, "HTTP $status, $code\n");
    exit(1);
}

printf("%d %s\n", $status, $envelope['result']['status']);
```

### Python

Сохраните файл как `ping.py` и запустите `python3 ping.py`. Пример использует стандартную библиотеку Python 3.

```python ping.py theme={null}
import hashlib
import hmac
import http.client
import json
import os
import secrets
import time
from urllib.parse import urlsplit

address = os.environ.get('EXCHANGER_API_ORIGIN')
token = os.environ.get('EXCHANGER_API_TOKEN')
secret = os.environ.get('EXCHANGER_API_HMAC_SECRET')
if not address or not token or not secret:
    raise SystemExit('Set EXCHANGER_API_ORIGIN, EXCHANGER_API_TOKEN, and EXCHANGER_API_HMAC_SECRET.')

origin = urlsplit(address)
if (
    origin.scheme != 'https'
    or not origin.hostname
    or origin.path not in ('', '/')
    or origin.username is not None
    or origin.password is not None
    or origin.query
    or origin.fragment
):
    raise SystemExit('Use the direct HTTPS origin of your exchanger.')

path = '/api/v3/private/ping'
timestamp = str(int(time.time()))
nonce = secrets.token_hex(16)
body_hash = hashlib.sha256(b'').hexdigest()
canonical = '\n'.join(('v2', 'GET', path, '', body_hash, timestamp, nonce, ''))
signature = hmac.new(secret.encode('utf-8'), canonical.encode('utf-8'), 'sha256').hexdigest()

connection = http.client.HTTPSConnection(origin.hostname, port=origin.port, timeout=10)
try:
    connection.request('GET', path, headers={
        'Accept': 'application/json',
        'Authorization': f'Bearer {token}',
        'X-Api-Signature-Version': 'v2',
        'X-Api-Timestamp': timestamp,
        'X-Api-Nonce': nonce,
        'X-Api-Signature': f'sha256={signature}',
    })
    response = connection.getresponse()
    status = response.status
    body = response.read()
finally:
    connection.close()

try:
    envelope = json.loads(body)
except ValueError:
    raise SystemExit(f'HTTP {status}, unexpected_response') from None

if not isinstance(envelope, dict):
    raise SystemExit(f'HTTP {status}, unexpected_response')
result = envelope.get('result')
if status != 200 or envelope.get('state') != 0 or not isinstance(result, dict) or result.get('status') != 'ok':
    error = envelope.get('error')
    code = error.get('code', 'unexpected_response') if isinstance(error, dict) else 'unexpected_response'
    raise SystemExit(f'HTTP {status}, {code}')

print(status, result['status'])
```

### JavaScript

Скопируйте `request.mjs` из [быстрого старта](https://exchanger-api.iexexchanger.com/start/quickstart.md#2-проверьте-ключ-и-подпись) и запустите `node request.mjs` на Node.js 24. Скрипт выводит HTTP-статус `200` и исходный JSON с `result.status: "ok"`.

### TypeScript

Сохраните файл как `ping.mts` и запустите `node ping.mts` на Node.js 24. Код использует встроенные `node:crypto` и `fetch`.

```typescript ping.mts theme={null}
import { createHash, createHmac, randomBytes } from 'node:crypto';

type PingEnvelope = {
  state?: number;
  result?: { status?: string };
  error?: { code?: string };
};

const address = process.env.EXCHANGER_API_ORIGIN;
const token = process.env.EXCHANGER_API_TOKEN;
const secret = process.env.EXCHANGER_API_HMAC_SECRET;
if (!address || !token || !secret) {
  throw new Error('Set EXCHANGER_API_ORIGIN, EXCHANGER_API_TOKEN, and EXCHANGER_API_HMAC_SECRET.');
}

const origin = new URL(address);
if (origin.protocol !== 'https:' || origin.href !== `${origin.origin}/`) {
  throw new Error('Use the direct HTTPS origin of your exchanger.');
}

const path = '/api/v3/private/ping';
const timestamp = String(Math.floor(Date.now() / 1000));
const nonce = randomBytes(16).toString('hex');
const bodyHash = createHash('sha256').update('').digest('hex');
const canonical = ['v2', 'GET', path, '', bodyHash, timestamp, nonce, ''].join('\n');
const signature = createHmac('sha256', secret).update(canonical).digest('hex');

const response = await fetch(new URL(path, origin), {
  method: 'GET',
  headers: {
    Accept: 'application/json',
    Authorization: `Bearer ${token}`,
    'X-Api-Signature-Version': 'v2',
    'X-Api-Timestamp': timestamp,
    'X-Api-Nonce': nonce,
    'X-Api-Signature': `sha256=${signature}`,
  },
  redirect: 'error',
  signal: AbortSignal.timeout(10_000),
});

let envelope: PingEnvelope | null;
try {
  envelope = await response.json() as PingEnvelope | null;
} catch {
  throw new Error(`HTTP ${response.status}, unexpected_response`);
}

if (response.status !== 200 || envelope?.state !== 0 || envelope.result?.status !== 'ok') {
  throw new Error(`HTTP ${response.status}, ${envelope?.error?.code ?? 'unexpected_response'}`);
}

console.log(response.status, envelope.result.status);
```

Для других вызовов сверьте метод, права и параметры в [справочнике API](https://exchanger-api.iexexchanger.com/api.md). Подпись query, JSON и файлов описана в [правилах подписи](https://exchanger-api.iexexchanger.com/start/authentication.md). Если приватный ping вернул ошибку, проверьте HTTP-статус и [`error.code`](https://exchanger-api.iexexchanger.com/guides/reliability/errors).


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