# Payout API

> 가맹점 잔액에서 임의의 블록체인 주소로 출금을 전송합니다.

Payout API를 사용하면 가맹점 잔액에서 임의의 블록체인 주소로 프로그래밍 방식으로 자금을 출금할 수 있습니다.

> **WARNING:** 모든 Payout endpoint에서는 `sign` 서명을 생성할 때 별도의 **Payout API key**를 사용해야 합니다. 이 키는 일반 API key와 다르며 프로젝트 설정에서 별도로 생성해야 합니다.

## 출금 생성

가맹점 잔액으로부터 출금 요청을 생성합니다.

`POST /v1/payout`

### 요청 매개변수

| 필드 | 타입 | 필수 | 설명 |
|-------|------|----------|-------------|
| `currency` | string | yes | 출금 통화 ([References](/docs/references) 참고) |
| `network` | string | yes | 네트워크 코드 ([References](/docs/references) 참고) |
| `amount` | string | yes | 출금 금액 |
| `to_address` | string | yes | 수신자 블록체인 주소 |
| `order_id` | string | no | **멱등성 키** — 프로젝트 내에서 고유. 동일한 `order_id`로 `POST` 요청을 반복해도 새로운 출금은 생성되지 않으며, 기존 출금이 반환됩니다 |
| `url_callback` | string | no | 출금 webhook URL. 이 출금에 대해 webhook을 비활성화하려면 생략하세요 |
| `memo` | string \| null | no | 목적지 태그 / memo. 현재 **TON**과 **SOL** 네트워크에서만 사용됩니다. 최대 255자 |
| `from_currency` | string | no | 출금 시점에 차감하여 `currency`로 자동 변환할 원천 잔액. `USDT` 같은 스테이블코인으로 잔액을 유지하면서 변동성 자산(`BTC`, `ETH`, …)으로 출금할 수 있게 해줍니다 — 변동성 암호화폐를 직접 보유할 필요가 없습니다. `"USDT"`를 전달하면 USDT 잔액에서 차감합니다 |
| `fee_option` | string | no | 수수료 부과 방식. `deduct`(기본) — 네트워크 + 플랫폼 수수료가 `amount`에서 차감되며 수신자는 `amount - fees`를 받음. `add` — 수수료가 추가로 부과되어 가맹점 측에서는 `amount + fees`가 차감되고 수신자는 정확히 `amount`를 받음 |

> **INFO:** **멱등성.** 프로젝트 내에서 출금은 `order_id`로 고유하게 식별됩니다. 동일한 `order_id`로 동일한 `POST`를 다시 보내도 **안전합니다** — API는 중복을 만들지 않고 기존 출금을 반환합니다. 프로덕션 출금에서는 항상 `order_id`를 전달하세요.

### 요청 예시

<CodeTabs langs="curl,php,js,python,go">

```bash
curl -X POST https://api.2328.io/api/v1/payout \
  -H "Content-Type: application/json" \
  -H "User-Agent: MyShop/1.0 (+https://myshop.example)" \
  -H "project: YOUR_PROJECT_UUID" \
  -H "sign: YOUR_HMAC_SIGNATURE" \
  -d '{"currency":"TRX","network":"TRX-TRC20","amount":"1.00","to_address":"TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t","order_id":"9ed25264-8be4-439f-acf5-2a8732538d27","url_callback":"https://your-site.com/webhook/payout","memo":null,"fee_option":"deduct"}'
```

```php
<?php
function apiSign(string $body, string $apiKey): string {
    return hash_hmac('sha256', base64_encode($body), $apiKey);
}

$project = 'YOUR_PROJECT_UUID';
$apiKey  = 'YOUR_PAYOUT_API_KEY';

$data = [
    'currency'     => 'TRX',
    'network'      => 'TRX-TRC20',
    'amount'       => '1.00',
    'to_address'   => 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t',
    'order_id'     => '9ed25264-8be4-439f-acf5-2a8732538d27',
    'url_callback' => 'https://your-site.com/webhook/payout',
    'memo'         => null,
    'fee_option'   => 'deduct',
];

$body = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$sign = apiSign($body, $apiKey);

$ch = curl_init('https://api.2328.io/api/v1/payout');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => $body,
    CURLOPT_HTTPHEADER     => [
        'Content-Type: application/json',
        'User-Agent: MyShop/1.0 (+https://myshop.example)',
        "project: $project",
        "sign: $sign",
    ],
]);
$response = json_decode(curl_exec($ch), true);
```

```javascript
import { createHmac } from "crypto";

function apiSign(body, apiKey) {
  const base64 = Buffer.from(body, "utf8").toString("base64");
  return createHmac("sha256", apiKey).update(base64).digest("hex");
}

const PROJECT_UUID    = "YOUR_PROJECT_UUID";
const PAYOUT_API_KEY  = process.env.PAYOUT_API_KEY;

const data = {
  currency:     "TRX",
  network:      "TRX-TRC20",
  amount:       "1.00",
  to_address:   "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
  order_id:     "9ed25264-8be4-439f-acf5-2a8732538d27",
  url_callback: "https://your-site.com/webhook/payout",
  memo:         null,
  fee_option:   "deduct",
};

const body = JSON.stringify(data);
const sign = apiSign(body, PAYOUT_API_KEY);

const res = await fetch("https://api.2328.io/api/v1/payout", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "User-Agent":   "MyShop/1.0 (+https://myshop.example)",
    project:        PROJECT_UUID,
    sign,
  },
  body,
});
const json = await res.json();
```

```python
import json
import hmac
import hashlib
import base64
import httpx


def api_sign(body: str, api_key: str) -> str:
    b64 = base64.b64encode(body.encode("utf-8")).decode()
    return hmac.new(api_key.encode(), b64.encode(), hashlib.sha256).hexdigest()


PROJECT_UUID    = "YOUR_PROJECT_UUID"
PAYOUT_API_KEY  = "YOUR_PAYOUT_API_KEY"

data = {
    "currency":     "TRX",
    "network":      "TRX-TRC20",
    "amount":       "1.00",
    "to_address":   "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
    "order_id":     "9ed25264-8be4-439f-acf5-2a8732538d27",
    "url_callback": "https://your-site.com/webhook/payout",
    "memo":         None,
    "fee_option":   "deduct",
}

body = json.dumps(data, separators=(",", ":"), ensure_ascii=False)
sign = api_sign(body, PAYOUT_API_KEY)

r = httpx.post(
    "https://api.2328.io/api/v1/payout",
    headers={
        "Content-Type": "application/json",
        "User-Agent":   "MyShop/1.0 (+https://myshop.example)",
        "project":      PROJECT_UUID,
        "sign":         sign,
    },
    content=body.encode("utf-8"),
)
response = r.json()
```

```go
package main

import (
    "bytes"
    "crypto/hmac"
    "crypto/sha256"
    "encoding/base64"
    "encoding/hex"
    "encoding/json"
    "net/http"
)

func apiSign(body []byte, apiKey string) string {
    b64 := base64.StdEncoding.EncodeToString(body)
    h := hmac.New(sha256.New, []byte(apiKey))
    h.Write([]byte(b64))
    return hex.EncodeToString(h.Sum(nil))
}

func marshalCanonical(v any) ([]byte, error) {
    var buf bytes.Buffer
    enc := json.NewEncoder(&buf)
    enc.SetEscapeHTML(false)
    if err := enc.Encode(v); err != nil {
        return nil, err
    }
    return bytes.TrimRight(buf.Bytes(), "\n"), nil
}

type CreatePayout struct {
    Currency    string  `json:"currency"`
    Network     string  `json:"network"`
    Amount      string  `json:"amount"`
    ToAddress   string  `json:"to_address"`
    OrderID     string  `json:"order_id"`
    URLCallback string  `json:"url_callback"`
    Memo        *string `json:"memo"`
    FeeOption   string  `json:"fee_option"`
}

func main() {
    const projectUUID   = "YOUR_PROJECT_UUID"
    const payoutAPIKey  = "YOUR_PAYOUT_API_KEY"

    data := CreatePayout{
        Currency:    "TRX",
        Network:     "TRX-TRC20",
        Amount:      "1.00",
        ToAddress:   "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
        OrderID:     "9ed25264-8be4-439f-acf5-2a8732538d27",
        URLCallback: "https://your-site.com/webhook/payout",
        Memo:        nil,
        FeeOption:   "deduct",
    }

    body, err := marshalCanonical(data)
    if err != nil {
        panic(err)
    }
    sign := apiSign(body, payoutAPIKey)

    req, _ := http.NewRequest("POST",
        "https://api.2328.io/api/v1/payout",
        bytes.NewReader(body))
    req.Header.Set("Content-Type", "application/json")
    req.Header.Set("User-Agent", "MyShop/1.0 (+https://myshop.example)")
    req.Header.Set("project", projectUUID)
    req.Header.Set("sign", sign)

    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()
}
```

</CodeTabs>

### 응답 예시

```json
{
  "state": 0,
  "result": {
    "uuid": "019dea62-1727-72aa-ac2c-eaf2ade193ef",
    "order_id": "9ed25264-8be4-439f-acf5-2a8732538d27",
    "status": "pending",
    "currency": "TRX",
    "network": "TRX-TRC20",
    "amount": "1.00",
    "merchant_amount": "1",
    "network_amount": "0.89",
    "amount_usd": "0.33",
    "to_address": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
    "memo": null,
    "txid": null,
    "block_number": null,
    "error_type": null,
    "created_at": "2026-05-02T23:29:50+03:00",
    "updated_at": "2026-05-02T23:29:50+03:00"
  }
}
```

> **INFO:** **수수료.** 기본값 `fee_option: deduct` — 네트워크 + 플랫폼 수수료가 `amount`에서 차감되어 수신자는 `amount - fees`를 받습니다. 수수료를 추가로 부과하려면 `fee_option: add`를 전달하세요. 이 경우 수신자는 정확히 `amount`를 받고 가맹점 측에서는 `amount + fees`가 차감됩니다.

## 출금 계산

**출금을 생성하지 않고** 잔액 차감도 없이 출금 금액과 수수료를 추정합니다. 확인 전에 사용자에게 실제로 받을(또는 지불할) 정확한 금액을 보여줄 때 사용합니다.

`POST /v1/payout/calc`

### 요청 매개변수

[출금 생성](#create-payout) 과 동일합니다 — 동일한 필드, 동일한 서명. `order_id`, `url_callback`, `to_address`, `memo` 도 허용되지만 무시됩니다: 출금은 저장되지 않으며 callback 도 전송되지 않습니다.

### 요청 예시

```bash
curl -X POST https://api.2328.io/api/v1/payout/calc \
  -H "Content-Type: application/json" \
  -H "User-Agent: MyShop/1.0 (+https://myshop.example)" \
  -H "project: YOUR_PROJECT_UUID" \
  -H "sign: YOUR_HMAC_SIGNATURE" \
  -d '{"currency":"USDT","network":"TRX-TRC20","amount":"100","fee_option":"add"}'
```

### 응답 예시

```json
{
  "state": 0,
  "result": {
    "currency": "USDT",
    "network": "TRX-TRC20",
    "amount": "100",
    "fee_option": "add",
    "merchant_amount": "103.00000000",
    "network_amount": "100",
    "total_fee": "3.00000000",
    "total_fee_usd": "3.00000000"
  }
}
```

> **INFO:** **미리보기 전용.** 이 엔드포인트는 읽기 전용입니다 — 잔액이 차감되지 않으며 출금 레코드도 생성되지 않습니다. UI 에 수수료 내역을 표시하기 위해 필요한 만큼 호출해도 됩니다.

## 출금 상태

출금 요청의 상태를 조회합니다.

`GET /v1/payout/status/{uuid}`

### Path 매개변수

| 필드 | 타입 | 필수 | 설명 |
|-------|------|----------|-------------|
| `uuid` | string | yes | 출금 UUID (생성 시 `result.uuid`) |

### 응답 예시

```json
{
  "state": 0,
  "result": {
    "uuid": "019dff1f-0dbd-7277-8d45-271e7775388f",
    "order_id": "4dfdcc84402b1185b71cbe399321533e",
    "status": "completed",
    "currency": "TRX",
    "network": "TRX-TRC20",
    "amount": "3.00",
    "merchant_amount": "3.00",
    "network_amount": "3.00",
    "amount_usd": "1.04",
    "to_address": "THauRv5tcucQRohXg8NiyGTk16DX1XQG5x",
    "memo": null,
    "txid": "9242e533703704ef3eaba840f70b4a26333e72c943377ee375fea17badb53def",
    "block_number": null,
    "error_type": null,
    "created_at": "2026-05-07T00:08:38+03:00",
    "updated_at": "2026-05-07T00:08:54+03:00",
    "from_currency": "USDT",
    "debited_amount": "1.050735",
    "debited_currency": "USDT"
  }
}
```

> **INFO:** 이 GET 요청에서는 빈 본문에 대해 서명을 계산합니다:
`hash_hmac('sha256', base64_encode(''), $apiKey)`

## 응답 필드

`POST /v1/payout`과 `GET /v1/payout/status/{uuid}`의 `result`에서 반환되는 필드:

| 필드 | 타입 | 설명 |
|-------|------|-------------|
| `uuid` | string | 시스템이 부여한 출금 UUID |
| `order_id` | string | 가맹점 측 내부 출금 식별자 (프로젝트 내 고유) |
| `status` | string | 현재 출금 상태 (아래 참고) |
| `currency` | string | 출금 통화 |
| `network` | string | 네트워크 코드 |
| `amount` | string | 요청한 출금 금액 |
| `merchant_amount` | string | 가맹점 잔액에서 차감된 금액 |
| `network_amount` | string | 실제로 온체인에 전송된 금액 (네트워크 + 플랫폼 수수료 차감 후) |
| `amount_usd` | string | 출금 금액의 USD 환산 |
| `to_address` | string | 수신자 블록체인 주소 |
| `memo` | string \| null | 목적지 태그 / memo (TON, SOL). 그 외에는 `null` |
| `txid` | string \| null | 블록체인 트랜잭션 해시. 트랜잭션이 전송되기 전까지 `null` |
| `block_number` | int \| null | 트랜잭션이 포함된 블록 번호. 포함 전까지 `null` |
| `error_type` | string \| null | `status = failed`일 때 실패 사유 (아래 Error types 참고). 그 외에는 `null` |
| `created_at` | string (ISO 8601) | 출금 생성 시각 |
| `updated_at` | string (ISO 8601) | 마지막 상태 변경 시각 |
| `from_currency` | string \| null | 자동 변환이 사용된 경우 출금이 차감된 원천 잔액 (예: `BTC` 출금에 대한 `USDT`). 변환이 발생하지 않은 경우 `null` |
| `debited_amount` | string \| null | 변환 후 원천 잔액에서 실제로 차감된 금액. 자동 변환을 사용한 경우에만 존재 |
| `debited_currency` | string \| null | `debited_amount`의 통화 — 자금이 차감된 잔액의 통화 |

## 출금 상태

`status` 필드는 다음 값을 가질 수 있습니다:

| Status | 설명 |
|--------|-------------|
| `pending` | 생성됨, 처리 대기 중 |
| `completed` | 정상적으로 완료됨 — `txid`가 설정됨 |
| `failed` | 전송 오류 — `error_type` 참조 |
| `cancelled` | 취소됨 |

## 오류 유형

`status = failed`일 때 `error_type` 필드는 사유를 설명합니다:

| Code | 설명 |
|------|-------------|
| `aml_risk` | AML 리스크 검사로 인해 출금이 차단됨 (수신자 주소가 고위험으로 표시됨) |

## Webhook 알림

출금의 상태가 변경되면 시스템은 출금 생성 시 전달된 `url_callback` URL로 `POST` webhook을 보냅니다. `url_callback`을 제공하지 않은 경우 해당 출금에 대한 webhook은 전송되지 않습니다.

- **Method:** `POST`
- **Content-Type:** `application/json`
- **Signature:** 요청 본문의 `sign` 필드. 출금 요청을 서명할 때 사용한 동일한 **Payout API key**로 계산됩니다.

payload는 `GET /v1/payout/status/{uuid}`의 `result` 객체에 검증용 `sign` 필드를 더한 것과 동일합니다.

### Payload

```json
{
  "uuid": "019dff1f-0dbd-7277-8d45-271e7775388f",
  "order_id": "4dfdcc84402b1185b71cbe399321533e",
  "status": "completed",
  "currency": "TRX",
  "network": "TRX-TRC20",
  "amount": "3.00",
  "merchant_amount": "3.00",
  "network_amount": "3.00",
  "amount_usd": "1.04",
  "to_address": "THauRv5tcucQRohXg8NiyGTk16DX1XQG5x",
  "memo": null,
  "txid": "9242e533703704ef3eaba840f70b4a26333e72c943377ee375fea17badb53def",
  "block_number": null,
  "error_type": null,
  "created_at": "2026-05-07T00:08:38+03:00",
  "updated_at": "2026-05-07T00:08:54+03:00",
  "from_currency": "USDT",
  "debited_amount": "1.050735",
  "debited_currency": "USDT",
  "sign": "925ad7bf3d6841864101f7cc2c7e30652e70a06cdb04dbe07a0129480000ce4a"
}
```

> **WARNING:** **서명 검증.** [결제 webhook](/docs/webhooks)과 동일한 알고리즘을 사용하되 일반 API key 대신 **Payout API key**로 서명합니다. `sign` 필드를 제거하고 나머지 payload를 JSON으로 인코딩한 뒤 base64로 인코딩하고 `hash_hmac('sha256', $base64, $payoutApiKey)`를 계산해 수신한 `sign`과 비교하세요.