Webhook 알림
HMAC 서명된 webhook으로 실시간 결제 및 출금 상태 업데이트를 수신합니다.
2328.io 시스템은 결제 상태가 변경될 때마다 url_callback으로 webhook을 전송합니다. 이는 결제 성공 알림을 받기 위한 권장 방식입니다.
요청 형식
- Method:
POST - Content-Type:
application/json - Signature: 요청 본문의
sign필드
Payload
webhook 본문은 /v1/payment/info 응답과 동일하며, 서명 검증에 사용되는 sign 필드가 추가됩니다.
결제 성공
{
"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",
"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입니다:
{
"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,
"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 참고) |
txid | string | 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 서명을 검증하려면:
- payload에서
sign필드를 추출합니다 - 객체에서
sign필드를 제거합니다 - 나머지 필드를 JSON으로 인코딩합니다
- 그 JSON을 base64로 인코딩합니다
- API_KEY를 사용해 base64 문자열에 대해 HMAC-SHA256을 계산합니다
- 계산된 서명을 수신한
sign값과 상수 시간 비교 함수로 비교합니다
<?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);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);
});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}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)
}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자금을 사용자에게 반영하기 전에는 반드시 서명을 검증하세요. 서명되지 않았거나 잘못 서명된 webhook은 위조 요청일 수 있습니다.
출금 webhook
출금의 status가 변경되면 시스템은 출금 생성 시 전달된 url_callback URL로 POST webhook을 전송합니다. url_callback을 제공하지 않은 경우 해당 출금에 대한 webhook은 전송되지 않습니다.
출금 webhook은 일반 API key가 아닌 Payout API key로 검증해야 합니다. 서명 알고리즘은 결제 webhook과 동일하며(sign 제거 → JSON 인코딩 → base64 → HMAC-SHA256), 사용하는 키만 다릅니다.
Payload
{
"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"
}필드 레퍼런스
| 필드 | 타입 | 설명 |
|---|---|---|
uuid | string | 출금 UUID |
order_id | string | 가맹점이 제공한 멱등성 / 참조 ID (있는 경우) |
status | string | pending, completed, failed, cancelled (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일 때 설정됨 |
block_number | integer | null | 온체인 트랜잭션의 블록 높이 |
error_type | string | null | status = failed일 때 사유 (예: aml_risk, 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서명을 검증하세요.
webhook은 순서가 뒤바뀌어 도착할 수 있습니다. 가장 먼저 받은 webhook이 최종 상태라고 단정하지 마세요 — 확실해야 한다면 /v1/payment/info(또는 /v1/payout/status/{uuid})로 다시 조회하세요.