# Mulai cepat

Integrasi pembayaran minimal: membuat tagihan melalui API dan menangani notifikasi pembayaran. Bagian terakhir membahas pengiriman pesanan. Contohnya berdiri sendiri; tidak ada SDK yang digunakan.

:::tip
**Bekerja dengan agen AI?** Berikan kepadanya [versi markdown halaman ini](/id/quick-start.md). Isinya cukup rinci untuk membangun integrasi bagi situs atau toko Anda.
:::

## Prasyarat

| Nilai | Tempat mendapatkannya |
| --- | --- |
| Kunci API | Bagian [Integrasi (Integrations)](https://dash.bitsby.app/integrations/list) |
| ID proyek | Bagian [Proyek (Projects)](https://dash.bitsby.app/projects/list) |
| Kunci rahasia webhook (Webhook secret) | Pengaturan proyek |

Di pengaturan proyek yang sama, atur **Webhook URL**—alamat penangan notifikasi di server Anda. Hanya HTTPS; pengalihan tidak diikuti.

Contoh-contoh ini menggunakan nilai uji—ganti dengan milik Anda.

## Membuat tagihan

`POST https://api.bitsby.app/invoices/create`, kunci API dikirim di header `Authorization`.

| Parameter | Wajib | Nilai |
| --- | --- | --- |
| `projectId` | ya | ID proyek, UUID |
| `amountFiat` | ya | Jumlah tagihan |
| `currencyFiat` | ya | Mata uang: USD, EUR, RUB |
| `timeToPay` | ya | Batas waktu pembayaran dalam jam: 0.5, 1, 3, 6, 12 |
| `description` | tidak | Deskripsi, ditampilkan kepada pembeli di halaman pembayaran |
| `serviceData` | tidak | Data layanan, tidak ditampilkan kepada pembeli. Kami menyarankan mengirim nomor pesanan: nilai ini dikembalikan dalam notifikasi pembayaran |

**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
```

Respons:

```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"
  }
}
```

Simpan `data.id` bersama pesanan dan arahkan pembeli ke `data.url`—halaman pembayaran. Sampaikan tautannya dengan cara apa pun: pengalihan, email, pesan bot. Tagihan berlaku hingga `timeToPayDatetime` (UTC).

## Menangani notifikasi

Saat tagihan beralih ke status Dibayar (Paid), layanan mengirim permintaan POST ke Webhook URL proyek. Isinya JSON; tanda tangannya ada di header:

| Header | Nilai |
| --- | --- |
| `X-Timestamp` | Waktu pengiriman, unix time dalam detik |
| `X-Signature` | `sha256=` + HMAC-SHA256 heksadesimal dari string `<timestamp>.<request body>` |

Kunci penandatanganannya adalah kunci rahasia webhook. Tanda tangan dihitung atas isi permintaan mentah, jadi verifikasi dulu sebelum mengurai 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
```

Balas dengan kode 2xx dalam 10 detik. Kode lain, pengalihan, atau waktu habis dihitung sebagai pengiriman gagal: layanan melakukan percobaan ulang dengan interval yang meningkat dari 5 menit hingga 24 jam, lalu berhenti. Alihkan pemrosesan yang lama ke antrean: balas 200 dulu, baru proses pesanannya.

Format lengkap notifikasi dan referensi field-nya ada di bagian [Webhook URL](./webhook-url/index.md).

## Pengiriman pesanan

Notifikasi terverifikasi dengan status `paid` mengonfirmasi pembayaran. Langkah pengirimannya:

1. **Temukan pesanan** berdasarkan `invoice.serviceData`—nilai yang dikirim saat pembuatan tagihan (`order-4172`).
2. **Periksa berdasarkan `invoice.id` apakah tagihan ini sudah pernah diproses.** Notifikasi dengan `invoice.id` yang sama dapat datang lebih dari sekali—kirim pesanan sekali saja dan simpan penanda telah diproses.
3. **Verifikasi jumlah dan mata uang** terhadap `invoice.amountFiat` dan `invoice.currencyFiat`—keduanya nilai asli tagihan dan tidak pernah berubah. `amountFiatUSD` ditimpa dengan jumlah yang benar-benar diterima. Bandingkan jumlah sebagai angka, bukan string: nol di belakang dibuang, sehingga `49.90` tiba sebagai `49.9`. Jika nilainya tidak cocok dengan pesanan, arahkan tagihan ke peninjauan manual alih-alih pengiriman—kasus seperti ini dibahas di [Pencocokan pembayaran dan selisih jumlah](./payment-matching.md).
4. **Kirim pesanan dan tandai sebagai telah diproses.**

Jangan memeriksa batas waktu pembayaran saat pengiriman: pembayaran bisa saja terkonfirmasi on-chain setelah `timeToPayDatetime`, dan merchant dapat mencocokkan pembayaran dengan tagihan secara manual. Notifikasi itu sendiri sudah mengonfirmasi pembayaran.

## Langkah selanjutnya

- [Referensi API](./api/index.md)—daftar tagihan, pembatalan, statistik, saldo
- [Verifikasi tanda tangan webhook](./webhook-url/signature-verification.md)—mekanisme tanda tangan secara terperinci
- [Pencocokan pembayaran dan selisih jumlah](./payment-matching.md)—kurang bayar, lebih bayar, pembayaran tak tercocokkan
- [Formulir HTML](./creating-invoices/html-forms/index.md)—menerima pembayaran tanpa API
