# Webhook 알림

> HMAC 서명된 webhook으로 실시간 결제 및 출금 상태 업데이트를 수신합니다.

2328.io 시스템은 결제 상태가 변경될 때마다 `url_callback`으로 webhook을 전송합니다. 이는 결제 성공 알림을 받기 위한 권장 방식입니다.

## 요청 형식

- **Method:** `POST`
- **Content-Type:** `application/json`
- **Signature:** 요청 본문의 `sign` 필드

## Payload

webhook 본문은 `/v1/payment/info` 응답 형식을 따르며 `tx_explorer_url`과 서명 검증에 사용하는 `sign` 필드를 추가합니다.

### 결제 성공

```json
{
  "uuid": "db17d490-15b6-47b9-9015-91d1d8b119f2",
  "order_id": "ORDER-12345",
  "amount": "180.00000000",
  "currency": "RUB",
  "url": "https://go.2328.io/db17d490-15b6-47b9-9015-91d1d8b119f2",
  "expires_at": "2026-05-09T16:56:58+03:00",
  "created_at": "2026-05-09T15:56:58+03:00",
  "payer_currency": "TON",
  "payer_amount": "0.95256917",
  "network": "TON",
  "address": "UQA0RevhkCQx-EltyNgPPeG8dqtnCz7ZslOzMdNQlLxVaNBb",
  "payment_status": "paid",
  "txid": "41c2a327323480af8e705d05deb09c238a41779928832abef4bb77c862357b11",
  "tx_explorer_url": "https://tonviewer.com/transaction/41c2a327323480af8e705d05deb09c238a41779928832abef4bb77c862357b11",
  "payment_amount": "0.95256917",
  "merchant_amount": "0.949711462490000000",
  "amount_usd": "2.41324380",
  "exchange_rate": "0.01340691",
  "sign": "6f8c15b6e53b506d5bfa38ed3fb3b50697af73434262153c02e412541372f04d"
}
```

### 취소 / 실패 결제

결제가 종료 상태인 `paid`가 아닐 경우 `txid`, `payment_amount`, `merchant_amount`는 `null`입니다:

```json
{
  "uuid": "48edaf2d-2c49-4638-8f86-88636f661c1f",
  "order_id": "ORDER-12345",
  "amount": "2800.00000000",
  "currency": "RUB",
  "url": "https://go.2328.io/48edaf2d-2c49-4638-8f86-88636f661c1f",
  "expires_at": "2026-05-09T06:19:04+03:00",
  "created_at": "2026-05-09T05:19:04+03:00",
  "payer_currency": "ETH",
  "payer_amount": "0.01620968",
  "network": "ETH-ERC20",
  "address": "0x37c20d6d96d130Bc5B33D832e43b8e16aACe0c59",
  "payment_status": "cancel",
  "txid": null,
  "tx_explorer_url": null,
  "payment_amount": null,
  "merchant_amount": null,
  "amount_usd": "37.53934800",
  "exchange_rate": "0.01340691",
  "sign": "40ce68ad9691ad54e684329d75ab5adaf5b01409a2d18d3e0110b8c1be605342"
}
```

### 필드 레퍼런스

| 필드 | 타입 | 설명 |
|-------|------|-------------|
| `uuid` | string | 결제 UUID |
| `order_id` | string | 가맹점 측 주문 ID |
| `amount` | decimal (8 dp) | `currency` 단위의 법정화폐 금액 |
| `currency` | string | 가맹점이 요청한 법정화폐 |
| `url` | string | 호스팅된 결제 페이지 URL |
| `expires_at` | string (ISO 8601) | 결제 세션 만료 시각 |
| `created_at` | string (ISO 8601) | 결제 세션 생성 시각 |
| `payer_currency` | string | 결제자가 사용하는 암호화폐 |
| `payer_amount` | decimal (8 dp) | 예상 암호화폐 금액 |
| `network` | string | 블록체인 네트워크 |
| `address` | string | 입금 주소 |
| `payment_status` | string | 다음 중 하나: `pending`, `check`, `paid`, `underpaid_check`, `underpaid`, `overpaid`, `cancel`, `aml_lock` ([References](/docs/references) 참고) |
| `txid` | string \| null | 블록체인 트랜잭션 해시. 결제 확인 후에만 존재 |
| `tx_explorer_url` | string \| null | 블록체인 탐색기의 트랜잭션 URL입니다. `txid`가 없거나 내부 P2P 전송인 경우 `null`입니다. |
| `payment_amount` | decimal \| null | 실제 결제 금액. 결제 후에만 존재 |
| `merchant_amount` | decimal (18 dp) \| null | 수수료 차감 후 가맹점에 반영된 금액 |
| `amount_usd` | decimal (8 dp) | 생성 시점의 USD 환산 금액 |
| `exchange_rate` | decimal | 사용된 암호화폐 / 법정화폐 환율 |
| `sign` | string (hex) | payload의 HMAC-SHA256 서명 |

## 서명 검증

webhook 서명을 검증하려면:

1. payload에서 `sign` 필드를 추출합니다
2. 객체에서 `sign` 필드를 제거합니다
3. 나머지 필드를 JSON으로 인코딩합니다
4. 그 JSON을 base64로 인코딩합니다
5. API_KEY를 사용해 base64 문자열에 대해 HMAC-SHA256을 계산합니다
6. 계산된 서명을 수신한 `sign` 값과 상수 시간 비교 함수로 비교합니다

#### php

```php
<?php
function verifyWebhookSign(array $data, string $apiKey): bool {
    $receivedSign = $data['sign'] ?? '';
    unset($data['sign']);

    $json = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    $base64 = base64_encode($json);
    $calculated = hash_hmac('sha256', $base64, $apiKey);

    return hash_equals($calculated, $receivedSign);
}

$apiKey = 'YOUR_API_KEY';
$payload = json_decode(file_get_contents('php://input'), true);

if (!verifyWebhookSign($payload, $apiKey)) {
    http_response_code(401);
    exit;
}

switch ($payload['payment_status']) {
    case 'paid':
    case 'overpaid':
        // Credit the order — check idempotency by order_id first
        break;
    case 'underpaid_check':
    case 'underpaid':
    case 'cancel':
        break;
}

http_response_code(200);
```

#### js

```js
import crypto from "crypto";
import express from "express";

const app = express();
app.use(express.json());

function verifyWebhookSign(payload, apiKey) {
  const { sign, ...rest } = payload;
  const json = JSON.stringify(rest);
  const base64 = Buffer.from(json).toString("base64");
  const calculated = crypto
    .createHmac("sha256", apiKey)
    .update(base64)
    .digest("hex");
  return crypto.timingSafeEqual(
    Buffer.from(calculated),
    Buffer.from(sign || ""),
  );
}

app.post("/webhook", (req, res) => {
  if (!verifyWebhookSign(req.body, process.env.API_KEY)) {
    return res.sendStatus(401);
  }

  const { order_id, payment_status, txid } = req.body;

  if (payment_status === "paid" || payment_status === "overpaid") {
    // Credit the order — check idempotency by order_id first
  }

  res.sendStatus(200);
});
```

#### python

```python
import json
import hmac
import hashlib
import base64
from fastapi import FastAPI, Request, HTTPException

app = FastAPI()
API_KEY = "YOUR_API_KEY"

def verify_webhook_sign(payload: dict, api_key: str) -> bool:
    received = payload.pop("sign", "")
    body = json.dumps(payload, separators=(",", ":"), ensure_ascii=False)
    b64 = base64.b64encode(body.encode("utf-8")).decode()
    calculated = hmac.new(api_key.encode(), b64.encode(), hashlib.sha256).hexdigest()
    return hmac.compare_digest(calculated, received)

@app.post("/webhook")
async def webhook(request: Request):
    payload = await request.json()
    if not verify_webhook_sign(payload, API_KEY):
        raise HTTPException(401)

    if payload["payment_status"] in ("paid", "overpaid"):
        # Credit the order — check idempotency by order_id first
        pass

    return {"ok": True}
```

#### go

```go
package main

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

func verifyWebhookSign(body []byte, apiKey string) (map[string]any, bool) {
    var payload map[string]any
    if err := json.Unmarshal(body, &payload); err != nil {
        return nil, false
    }
    received, _ := payload["sign"].(string)
    delete(payload, "sign")

    var buf bytes.Buffer
    enc := json.NewEncoder(&buf)
    enc.SetEscapeHTML(false)
    enc.Encode(payload)
    reencoded := bytes.TrimRight(buf.Bytes(), "\n")

    b64 := base64.StdEncoding.EncodeToString(reencoded)
    h := hmac.New(sha256.New, []byte(apiKey))
    h.Write([]byte(b64))
    calculated := hex.EncodeToString(h.Sum(nil))

    return payload, hmac.Equal([]byte(calculated), []byte(received))
}

func webhookHandler(w http.ResponseWriter, r *http.Request) {
    body, _ := io.ReadAll(r.Body)
    payload, ok := verifyWebhookSign(body, apiKey)
    if !ok {
        http.Error(w, "invalid signature", http.StatusUnauthorized)
        return
    }

    status, _ := payload["payment_status"].(string)
    if status == "paid" || status == "overpaid" {
        // Credit the order — check idempotency first
    }
    w.WriteHeader(http.StatusOK)
}
```

#### ruby

```ruby
require "json"
require "openssl"
require "base64"
require "sinatra"

API_KEY = "YOUR_API_KEY"

def verify_webhook_sign(payload, api_key)
  received = payload.delete("sign") || ""
  body = payload.to_json
  b64 = Base64.strict_encode64(body)
  calculated = OpenSSL::HMAC.hexdigest("SHA256", api_key, b64)
  OpenSSL.fixed_length_secure_compare(calculated, received)
end

post "/webhook" do
  payload = JSON.parse(request.body.read)
  halt 401 unless verify_webhook_sign(payload, API_KEY)

  if %w[paid overpaid].include?(payload["payment_status"])
    # Credit the order — check idempotency by order_id first
  end

  status 200
end
```

> **DANGER:** **자금을 사용자에게 반영하기 전에는 반드시 서명을 검증하세요.** 서명되지 않았거나 잘못 서명된 webhook은 위조 요청일 수 있습니다.

## 출금 webhook

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

> **WARNING:** 출금 webhook은 일반 API key가 아닌 **Payout API key**로 검증해야 합니다. 서명 알고리즘은 결제 webhook과 동일하며(`sign` 제거 → JSON 인코딩 → base64 → HMAC-SHA256), 사용하는 키만 다릅니다.

### 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",
  "tx_explorer_url": "https://tronscan.org/#/transaction/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"
}
```

### 필드 레퍼런스

| 필드 | 타입 | 설명 |
|-------|------|-------------|
| `uuid` | string | 출금 UUID |
| `order_id` | string | 가맹점이 제공한 멱등성 / 참조 ID (있는 경우) |
| `status` | string | `pending`, `completed`, `failed`, `cancelled` ([References](/docs/references) 참고) |
| `currency` | string | 출금 통화 |
| `network` | string | 블록체인 네트워크 |
| `amount` | decimal | 출금 금액 (`currency` 단위) |
| `merchant_amount` | decimal | 가맹점 잔액에서 차감된 금액 |
| `network_amount` | decimal | 실제로 온체인에 전송된 금액 |
| `amount_usd` | decimal | 출금 시점의 USD 환산 금액 |
| `to_address` | string | 수신자 블록체인 주소 |
| `memo` | string \| null | memo / 목적지 태그 (사용된 경우) |
| `txid` | string \| null | 블록체인 트랜잭션 해시. `completed`일 때 설정됨 |
| `tx_explorer_url` | string \| null | 블록체인 탐색기의 트랜잭션 URL입니다. `txid`가 없거나 내부 P2P 전송인 경우 `null`입니다. |
| `block_number` | integer \| null | 온체인 트랜잭션의 블록 높이 |
| `error_type` | string \| null | `status = failed`일 때 사유 (예: `aml_risk`, [References](/docs/references) 참고) |
| `created_at` | string (ISO 8601) | 출금 생성 시각 |
| `updated_at` | string (ISO 8601) | 마지막 상태 변경 시각 |
| `from_currency` | string | 자동 변환이 사용된 경우 출금이 차감된 원천 잔액 (예: `BTC` 출금에 대한 `USDT`) |
| `debited_amount` | decimal | `from_currency` 잔액에서 차감된 금액 |
| `debited_currency` | string | 차감된 통화 |
| `sign` | string (hex) | **Payout API key**로 서명된 payload의 HMAC-SHA256 서명 |

## 모범 사례

- **멱등성** — 결제가 이미 처리되었는지 항상 확인하세요(`order_id` 또는 `uuid` 기준). webhook은 여러 번 도착할 수 있습니다.
- **빠른 응답** — 가능한 빨리 HTTP 200을 반환하세요. 무거운 작업은 백그라운드 큐로 위임하세요.
- **재시도** — 시스템이 HTTP 200을 받지 못하면 2분 후 webhook이 재전송됩니다. 최대 5회까지 재시도합니다.
- **비동기 처리** — 응답 차단을 피하기 위해 webhook 이벤트를 비동기로 처리하세요.
- **보안** — payload를 신뢰하기 전에는 항상 `sign` 서명을 검증하세요.

> **WARNING:** webhook은 순서가 뒤바뀌어 도착할 수 있습니다. 가장 먼저 받은 webhook이 최종 상태라고 단정하지 마세요 — 확실해야 한다면 `/v1/payment/info`(또는 `/v1/payout/status/{uuid}`)로 다시 조회하세요.

## 배달 및 처리 계약

웹훅 엔드포인트 내에서 다음 순서를 사용하세요:

1. 비밀 정보나 전체 서명을 기록하지 않고 요청 본문을 읽으세요.
2. 결제/정적 지갑 이벤트인지 지급 이벤트인지 식별하여 올바른 API 키를 선택하세요.
3. `sign`를 제거하고 문서화된 JSON 바이트를 재현한 후 HMAC-SHA256을 계산하고 상수 시간으로 비교하세요.
4. 필수 식별자, 소수 문자열, 상태 값을 검증하세요.
5. 원자적으로 인박스/멱등성 기록을 삽입하세요. 이미 존재하면 부작용을 반복하지 않고 HTTP 200을 반환하세요.
6. 주문/원장 변화를 커밋하고 중요하지 않은 이메일, 분석 또는 알림을 대기열에 추가합니다.
7. HTTP 200을 빠르게 반환합니다.

멱등성 트랜잭션을 보유하는 동안 느린 서드파티 서비스를 호출하지 마십시오. 커밋한 후 반환하기 전에 타임아웃이 발생하면 재시도가 발생할 수 있습니다. 중복은 커밋된 인박스 키를 확인하고 무효화되어야 합니다.

### 권장 멱등성 키

| 이벤트 | 주요 신원 | 메모 |
|-------|------------------|-------|
| 결제 세션 | `uuid` + 상태/버전 증거 | 같은 송장은 여러 합법적인 상태 변화를 발생시킬 수 있습니다. |
| 부분 결제 충전 | 송장 `uuid` + `txid` | 하나의 미지급 송장에 여러 건의 송금이 속할 수 있습니다. |
| 정적 지갑 입금 | 네트워크 + `txid` | `order_id`는 해당 지갑에 대한 모든 입금에 재사용됩니다. |
| 지급 | 지급 `uuid` + 상태 | 웹훅 재시도 로직으로 두 번째 지급을 생성하지 마십시오. |

스키마에 이벤트 ID가 없는 경우, 추가 감사 증거로 검증된 페이로드 해시를 저장하되, 위의 비즈니스 식별자를 타임스탬프로 대체하지 마십시오.

## 주문 및 조정

배달은 최소 한 번 이상 이루어지며 상태 메시지가 경쟁할 수 있습니다. “마지막 요청이 승리”하는 방식보다 단조로운 비즈니스 규칙을 구현하십시오:

- 이전 이벤트가 늦게 도착했더라도 이미 완료된 주문을 `check`로 되돌리지 마십시오;
- `underpaid_check`가 이전 크레딧을 반복하지 않고 추가 txid를 받을 수 있도록 허용하십시오;
- `paid`와 `overpaid`를 서로 다른 금액을 유지하면서 성공적인 정산 상태로 취급하십시오;
- 권한 있는 API가 나중에 다른 상태를 보고하지 않는 한 `underpaid`를 최종 부분 결제 결과로 유지하십시오;
- `aml_lock`를 검토로 라우팅하고 일반 재시도 작업자가 이를 완료하지 못하게 하십시오;
- 전환이 불가능하거나, 컨텍스트가 없거나, 재무적으로 모호한 경우 결제/지급 정보를 조회하십시오.

웹훅 전달이 정상으로 보이더라도 예약된 조정을 실행하십시오. 로컬 터미널 상태와 `/v1/payment/info`, `/v1/static-wallet/transactions`, `/v1/payout/status/{uuid}`와 비교하여 차이가 발생하면 경고를 보내고, 원장 기록을 조용히 덮어쓰지 마십시오.

## 웹훅 엔드포인트 보안

- HTTPS를 요구하고 콜백을 공개적으로 접근 가능하게 유지하십시오; 결제 생성 중에 개인/루프백 콜백 대상은 거부됩니다.
- 작은 요청 본문 제한과 JSON 콘텐츠 유형을 적용하십시오.
- 비용이 많이 드는 작업 전에 속도 제한을 적용하되, 합법적인 급증과 재시도를 처리할 충분한 여유를 남겨두십시오.
- 소스 IP만으로 웹훅을 승인하지 마십시오. 네트워크 허용 목록은 다층 방어의 일부이며, HMAC 검증은 필수입니다.
- 정책상 필요할 경우 `sign`, API 키, 주소 및 개인 메타데이터를 애플리케이션 로그에서 가리십시오.
- 제어된 교체 기간 동안 현재 키와 명시적으로 스케줄된 교체 키를 모두 사용 가능하도록 유지하십시오; 어떤 키가 이벤트에 서명했는지 추측하지 마십시오.
- 잘못된 서명에 대해 일반적인 오류 본문을 반환하여 엔드포인트가 키 또는 계정 오라클이 되지 않도록 하십시오.