# Швидкий старт

Мінімальна інтеграція приймання платежів: створення рахунку через API й обробка сповіщення про оплату. Наприкінці — рекомендації щодо видачі товару. Приклади самодостатні, SDK не використовується.

:::tip
**Працюєте з ШІ-агентом?** Передайте йому [markdown-версію цієї сторінки](/uk/quick-start.md). На ній достатньо даних, щоб написати інтеграцію для вашого сайту чи магазину.
:::

## Підготовка

| Значення | Де взяти |
| --- | --- |
| API ключ | Розділ [Інтеграції](https://dash.bitsby.app/integrations/list) (Integrations) |
| ID проєкту | Розділ [Проєкти](https://dash.bitsby.app/projects/list) (Projects) |
| Секрет вебхука | Налаштування проєкту |

Там само в налаштуваннях проєкту вкажіть **Webhook URL** — адресу обробника сповіщень на вашому сервері. Лише https, редиректи не виконуються.

У прикладах використано тестові значення — підставте свої.

## Створення рахунку

`POST https://api.bitsby.app/invoices/create`, API ключ передається в заголовку `Authorization`.

| Параметр | Обов’язковий | Значення |
| --- | --- | --- |
| `projectId` | так | ID проєкту, UUID |
| `amountFiat` | так | Сума рахунку |
| `currencyFiat` | так | Валюта: USD, EUR, RUB |
| `timeToPay` | так | Строк оплати в годинах: 0.5, 1, 3, 6, 12 |
| `description` | ні | Опис, покупець бачить його на платіжній сторінці |
| `serviceData` | ні | Службові дані, покупець їх не бачить. Радимо передавати номер замовлення: він повернеться у сповіщенні про оплату |

**cURL**

```bash showLineNumbers
curl -X POST https://api.bitsby.app/invoices/create \
  -H "Authorization: Token MSvL2ltaDZdWVjmZURURMVWhqSJLT2NURjhL2Fla1Z1T1IxQTltKs1T3Ay" \
  -F "projectId=9deea1e2-0c08-41a3-bdc2-a34eada3892d" \
  -F "amountFiat=49.90" \
  -F "currencyFiat=USD" \
  -F "timeToPay=1" \
  -F "description=Order 4172" \
  -F "serviceData=order-4172"
```

**PHP**

```php showLineNumbers
<?php
$apiKey    = 'MSvL2ltaDZdWVjmZURURMVWhqSJLT2NURjhL2Fla1Z1T1IxQTltKs1T3Ay';
$projectId = '9deea1e2-0c08-41a3-bdc2-a34eada3892d';

$ch = curl_init('https://api.bitsby.app/invoices/create');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 10,
    CURLOPT_HTTPHEADER     => ['Authorization: Token '.$apiKey],
    CURLOPT_POSTFIELDS     => http_build_query([
        'projectId'    => $projectId,
        'amountFiat'   => 49.90,
        'currencyFiat' => 'USD',
        'timeToPay'    => 1,
        'description'  => 'Order 4172',
        'serviceData'  => 'order-4172',  // your order id
    ]),
]);

$response = json_decode(curl_exec($ch), true);
curl_close($ch);

if ($response['result'] !== 'success') {
    exit('API error: '.$response['data']);
}

$invoice = $response['data'];

// $invoice['id']  — invoice id, store it with the order
// $invoice['url'] — payment page for the customer
```

**TypeScript**

```typescript showLineNumbers
const API_KEY = 'MSvL2ltaDZdWVjmZURURMVWhqSJLT2NURjhL2Fla1Z1T1IxQTltKs1T3Ay';
const PROJECT_ID = '9deea1e2-0c08-41a3-bdc2-a34eada3892d';

interface Invoice {
    id: string;
    uid: string;
    url: string;
    timeToPayDatetime: string;
}

const response = await fetch('https://api.bitsby.app/invoices/create', {
    method: 'POST',
    headers: { Authorization: `Token ${API_KEY}` },
    body: new URLSearchParams({
        projectId: PROJECT_ID,
        amountFiat: '49.90',
        currencyFiat: 'USD',
        timeToPay: '1',
        description: 'Order 4172',
        serviceData: 'order-4172',  // your order id
    }),
    signal: AbortSignal.timeout(10_000),
});

const result: { result: string; data: Invoice | string } = await response.json();

if (result.result !== 'success') {
    throw new Error(`API error: ${result.data}`);
}

const invoice = result.data as Invoice;

// invoice.id  — invoice id, store it with the order
// invoice.url — payment page for the customer
```

**JavaScript**

```js showLineNumbers
const API_KEY = 'MSvL2ltaDZdWVjmZURURMVWhqSJLT2NURjhL2Fla1Z1T1IxQTltKs1T3Ay';
const PROJECT_ID = '9deea1e2-0c08-41a3-bdc2-a34eada3892d';

const response = await fetch('https://api.bitsby.app/invoices/create', {
    method: 'POST',
    headers: { Authorization: `Token ${API_KEY}` },
    body: new URLSearchParams({
        projectId: PROJECT_ID,
        amountFiat: '49.90',
        currencyFiat: 'USD',
        timeToPay: '1',
        description: 'Order 4172',
        serviceData: 'order-4172',  // your order id
    }),
    signal: AbortSignal.timeout(10_000),
});

const result = await response.json();

if (result.result !== 'success') {
    throw new Error(`API error: ${result.data}`);
}

const invoice = result.data;

// invoice.id  — invoice id, store it with the order
// invoice.url — payment page for the customer
```

**Python**

```python showLineNumbers
import requests

API_KEY = 'MSvL2ltaDZdWVjmZURURMVWhqSJLT2NURjhL2Fla1Z1T1IxQTltKs1T3Ay'
PROJECT_ID = '9deea1e2-0c08-41a3-bdc2-a34eada3892d'

response = requests.post(
    'https://api.bitsby.app/invoices/create',
    headers={'Authorization': f'Token {API_KEY}'},
    data={
        'projectId': PROJECT_ID,
        'amountFiat': '49.90',
        'currencyFiat': 'USD',
        'timeToPay': '1',
        'description': 'Order 4172',
        'serviceData': 'order-4172',  # your order id
    },
    timeout=10,
)

result = response.json()

if result['result'] != 'success':
    raise RuntimeError(f"API error: {result['data']}")

invoice = result['data']

# invoice['id']  — invoice id, store it with the order
# invoice['url'] — payment page for the customer
```

Відповідь:

```json
{
  "result": "success",
  "data": {
    "id": "ade9550d-3dc7-4fd3-b94e-3b4c12aaaa0c",
    "uid": "MXNj4m8HhcM4",
    "createDatetime": "2026-09-14 10:12:03",
    "timeToPayDatetime": "2026-09-14 11:12:03",
    "commissionFiatUSD": 0.5,
    "amountFiatUSD": 49.9,
    "url": "https://dash.bitsby.app/invoices/pay/MXNj4m8HhcM4"
  }
}
```

Збережіть `data.id` поруч із замовленням і відправте покупця на `data.url` — це платіжна сторінка. Посилання можна передати будь-яким способом: редиректом, листом, повідомленням у боті. Рахунок діє до `timeToPayDatetime` (UTC).

## Обробка сповіщення

Коли рахунок переходить у статус «Оплачений» (Paid), сервіс надсилає POST на Webhook URL проєкту. Тіло — JSON, підпис — у заголовках:

| Заголовок | Значення |
| --- | --- |
| `X-Timestamp` | Час надсилання, unix-час у секундах |
| `X-Signature` | `sha256=` + HMAC-SHA256 у hex від рядка `<timestamp>.<тіло запиту>` |

Ключ підпису — секрет вебхука. Підпис обчислюється від сирого тіла запиту, тому перевіряйте його до розбору JSON.

**PHP**

```php showLineNumbers
<?php
$secret = 'k7QwR2mZ9tXbN4vL8sJpH3dF6yA1cE0u';

$body      = file_get_contents('php://input');
$timestamp = $_SERVER['HTTP_X_TIMESTAMP'] ?? '';
$signature = $_SERVER['HTTP_X_SIGNATURE'] ?? '';

// Reject replayed requests: allow up to 5 minutes of clock drift
if (abs(time() - (int)$timestamp) > 300) {
    http_response_code(400);
    exit;
}

$expected = 'sha256='.hash_hmac('sha256', $timestamp.'.'.$body, $secret);

if (!hash_equals($expected, $signature)) {
    http_response_code(403);
    exit;
}

$invoice = json_decode($body, true)['invoice'];

if ($invoice['status'] === 'paid') {
    // $invoice['serviceData'] — the order id passed at creation: 'order-4172'
    // $invoice['amountFiat']  — the original invoice amount: 49.9
    // Issue the order here, see the next section
}

http_response_code(200);
```

**TypeScript**

```typescript showLineNumbers
import { createHmac, timingSafeEqual } from 'node:crypto';
import express, { type Request, type Response } from 'express';

const SECRET = 'k7QwR2mZ9tXbN4vL8sJpH3dF6yA1cE0u';
const app = express();

// express.raw: the signature is computed over the raw request body
app.post('/webhook', express.raw({ type: 'application/json' }), (req: Request, res: Response) => {
    const timestamp = req.get('X-Timestamp') ?? '';
    const signature = req.get('X-Signature') ?? '';
    const body = (req.body as Buffer).toString('utf8');

    // Reject replayed requests: allow up to 5 minutes of clock drift
    if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) {
        return res.sendStatus(400);
    }

    const expected = 'sha256=' + createHmac('sha256', SECRET)
        .update(`${timestamp}.${body}`, 'utf8')
        .digest('hex');

    const a = Buffer.from(expected);
    const b = Buffer.from(signature);

    if (a.length !== b.length || !timingSafeEqual(a, b)) {
        return res.sendStatus(403);
    }

    const { invoice } = JSON.parse(body);

    if (invoice.status === 'paid') {
        // invoice.serviceData — the order id passed at creation: 'order-4172'
        // invoice.amountFiat  — the original invoice amount: 49.9
        // Issue the order here, see the next section
    }

    res.sendStatus(200);
});

app.listen(8080);
```

**JavaScript**

```js showLineNumbers
import { createHmac, timingSafeEqual } from 'node:crypto';
import express from 'express';

const SECRET = 'k7QwR2mZ9tXbN4vL8sJpH3dF6yA1cE0u';
const app = express();

// express.raw: the signature is computed over the raw request body
app.post('/webhook', express.raw({ type: 'application/json' }), (req, res) => {
    const timestamp = req.get('X-Timestamp') ?? '';
    const signature = req.get('X-Signature') ?? '';
    const body = req.body.toString('utf8');

    // Reject replayed requests: allow up to 5 minutes of clock drift
    if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) {
        return res.sendStatus(400);
    }

    const expected = 'sha256=' + createHmac('sha256', SECRET)
        .update(`${timestamp}.${body}`, 'utf8')
        .digest('hex');

    const a = Buffer.from(expected);
    const b = Buffer.from(signature);

    if (a.length !== b.length || !timingSafeEqual(a, b)) {
        return res.sendStatus(403);
    }

    const { invoice } = JSON.parse(body);

    if (invoice.status === 'paid') {
        // invoice.serviceData — the order id passed at creation: 'order-4172'
        // invoice.amountFiat  — the original invoice amount: 49.9
        // Issue the order here, see the next section
    }

    res.sendStatus(200);
});

app.listen(8080);
```

**Python**

```python showLineNumbers
import hashlib
import hmac
import time

from flask import Flask, request

SECRET = 'k7QwR2mZ9tXbN4vL8sJpH3dF6yA1cE0u'
app = Flask(__name__)

@app.post('/webhook')
def webhook():
    timestamp = request.headers.get('X-Timestamp', '')
    signature = request.headers.get('X-Signature', '')
    # The signature is computed over the raw request body
    body = request.get_data(as_text=True)

    # Reject replayed requests: allow up to 5 minutes of clock drift
    if abs(time.time() - int(timestamp or 0)) > 300:
        return '', 400

    expected = 'sha256=' + hmac.new(
        SECRET.encode(),
        f'{timestamp}.{body}'.encode(),
        hashlib.sha256,
    ).hexdigest()

    if not hmac.compare_digest(expected, signature):
        return '', 403

    invoice = request.get_json()['invoice']

    if invoice['status'] == 'paid':
        # invoice['serviceData'] — the order id passed at creation: 'order-4172'
        # invoice['amountFiat']  — the original invoice amount: 49.9
        # Issue the order here, see the next section
        pass

    return '', 200
```

Відповідь — код 2xx протягом 10 секунд. Будь-який інший код, редирект або таймаут — невдала доставка: сервіс повторить запит зі щораз більшими інтервалами від 5 хвилин до 24 годин, потім припинить спроби. Довгу обробку виносьте в чергу: спочатку відповідь 200, потім робота із замовленням.

Повний формат сповіщення й опис усіх полів — у розділі «[Webhook URL](./webhook-url/index.md)».

## Видача товару

Перевірене сповіщення зі статусом `paid` підтверджує оплату. Порядок видачі:

1. **Знайдіть замовлення** за `invoice.serviceData` — це значення, передане під час створення рахунку (`order-4172`).
2. **Перевірте за `invoice.id`, чи не було вже видачі за цим рахунком.** Сповіщення з тим самим `invoice.id` може надійти повторно — видавайте товар один раз і зберігайте ознаку обробки.
3. **Звірте суму й валюту** за `invoice.amountFiat` і `invoice.currencyFiat` — це оригінальні значення рахунку, вони не змінюються. `amountFiatUSD` перезаписується фактично отриманою сумою. Порівнюйте суми як числа, а не рядки: незначущі нулі зникають, `49.90` надходить як `49.9`. У разі розбіжності із замовленням відправляйте рахунок на ручну перевірку, а не у видачу — розбір таких випадків у розділі «[Прив’язка платежів і розбіжність сум](./payment-matching.md)».
4. **Видайте товар і позначте замовлення обробленим.**

Строк оплати під час видачі не перевіряється: платіж міг підтвердитися в блокчейні після `timeToPayDatetime`, а продавець може прив’язати платіж до рахунку вручну. Факт оплати підтверджує саме сповіщення.

## Що далі

- [Документація API](./api/index.md) — список рахунків, скасування, статистика, баланси
- [Перевірка підпису вебхука](./webhook-url/signature-verification.md) — механіка підпису в деталях
- [Прив’язка платежів і розбіжність сум](./payment-matching.md) — недоплата, переплата, платежі поза рахунком
- [HTML форми](./creating-invoices/html-forms/index.md) — приймання оплати без API
