# 웹훅 이벤트 처리

원문: https://developers.bootpay.ai/api/common/webhook-events

> 웹훅 이벤트별 가맹점 처리 — 상태별 분기, 오류 웹훅, 부분취소, webhook_type 전략, 안 올 때 디버깅

웹훅 이벤트별로 가맹점 서버가 할 처리를 정리합니다. URL 등록 · 페이로드 · `webhook_type` 값 · 재시도 정책 · 발신 IP 는 [웹훅](https://developers.bootpay.ai/api/common/webhook#1-웹훅-설정)에 있고, 언어별 수신 코드는 이 문서에만 둡니다.

::: danger 웹훅 응답 필수 조건 — HTTP 200 과 본문 success: true
| # | 조건 | 예시 |
|:---:|------|------|
| **1** | HTTP 200 으로 응답하고 JSON 본문에 **`{ "success": true }`** 포함 | `res.json({ success: true })` |

부트페이는 응답 본문의 `success` 값으로 성공 여부를 판정합니다. HTTP 상태 코드는 로그에만 남고 판정에 쓰지 않습니다. HTTP 200을 반환해도 본문에 `success: true`가 없으면 실패로 기록되고 재시도됩니다. (`success`는 boolean `true` 또는 문자열 `"true"` 모두 인정됩니다.)

처리 완료 또는 내구성 있는 큐·DB 인계 뒤에만 `success: true`를 반환합니다. 처리·저장·조회 실패는 `success: false` 또는 HTTP 5xx로 응답해 재전송받습니다.
:::

## 결제 웹훅

### 상태별 처리

| status | webhook_type | 설명 | 가맹점이 할 일 | 중요도 |
|:---:|---|------|--------------|:---:|
| 1 | `PAYMENT_COMPLETED` | 결제완료 | 주문 상태 업데이트, 서비스 활성화 | 필수 |
| 20 | `PAYMENT_CANCELLED` | 결제 전체 취소 (잔액 0) | 취소 상태 반영, 서비스 비활성화, 재고 복구 | 필수 |
| 1 | `PAYMENT_PARTIAL_CANCELLED` | 결제 부분 취소 (잔액 남음) | 잔여 금액 갱신, 부분 환불 내역 기록 | 필수 |
| 5 | `PAYMENT_VIRTUAL_ACCOUNT_ISSUED` | 가상계좌발급완료 (입금 대기) | 입금 안내 표시 | 권장 |

::: warning status로는 부분취소를 포착할 수 없습니다
부분취소는 잔액이 남아 있어 결제 상태가 유지됩니다. 그래서 `PAYMENT_PARTIAL_CANCELLED` 웹훅은 `status: 1`(결제완료) 로 도착하고, `status: 20`은 잔액이 0이 되는 전액 취소에서만 나옵니다.

`status` fallback 경로에서는 부분취소가 결제완료 이벤트와 구분되지 않아, 부분취소가 일어난 사실 자체를 놓칩니다. 부분취소를 처리해야 한다면 반드시 `webhook_type`으로 분기하거나, 조회 응답의 `cancelled_price > 0 && price > 0` 조건으로 판정합니다.
:::

### 오류 웹훅 처리

관리자 → 웹훅 설정에서 "오류 웹훅 수신"을 켜면 다음 이벤트도 함께 받습니다. 오류 웹훅에는 별도 `status` 코드가 없으므로 `webhook_type`으로만 식별합니다.

| webhook_type | 발생 시점 | 권장 처리 |
|---|---|---|
| `PAYMENT_CONFIRM_FAILED` | 결제 승인 단계에서 PG 거절·통신 오류 | 주문을 `failed` 처리, 사용자에게 재시도 안내 |
| `PAYMENT_CANCEL_FAILED` | 취소 요청 실패 | 취소 상태를 되돌리고 운영팀 알림, 수동 취소 큐로 이동 |
| `PAYMENT_REQUEST_FAILED` | 결제창 호출 단계에서 실패 | 주문을 정리(또는 보류), 재시도 가능 여부를 사용자에게 안내 |
| `ERROR` | 위 케이스에 해당하지 않는 기타 오류 | 로그·Sentry 등에 캡처 후 운영팀이 직접 확인 |

::: tip 오류 페이로드 차이
오류 웹훅 본문은 `{ error_code, pg_error_code, message, payload, webhook_type }` 구조입니다. 정상 페이로드와 달리 `order_id`·`receipt_id`·`status`가 최상위에 없고 `payload` 안에 들어오므로, `data['order_id']`처럼 최상위에서 읽으면 값을 얻지 못합니다.

`payload`에는 PG 연동 정보가 있으면 PG 원본 응답이, 없으면 최소한의 영수증 정보가 담깁니다. `error_code`·`pg_error_code`·`message`와 함께 통째로 로깅합니다.
:::

### 결제 웹훅 처리 코드

아래 언어별 예제는 모두 다음 원칙을 따릅니다. `receipt_id + webhook_type + cancel_id` 같은 이벤트 고유키에 DB UNIQUE 제약을 두고, 고유키 등록·주문 상태·재고 증감·환불 원장을 하나의 트랜잭션으로 커밋합니다. 처리 또는 완료 기록이 실패하면 `success: false`/5xx를 반환합니다. 주문은 본문 `order_id`가 아니라 서버 조회 영수증의 `order_id`로 찾고, DB에 저장한 예상 금액과 영수증 금액을 비교합니다. 본문 금액으로 DB 금액을 덮어쓰지 않습니다.

부분취소는 주문의 누적 취소액 스냅샷과 개별 원장을 분리합니다. 원장에는 이번 취소액(현재 `cancelled_price`에서 직전 스냅샷을 뺀 값)과 `cancel_id`를 저장합니다.

아래 코드는 중복 수신을 걸러 내고, 중요한 데이터는 Bootpay API로 다시 확인한 뒤 처리하는 기본 형태입니다. `receipt_id` 만으로, 또는 `receipt_id:status` 만으로 묶으면 부분취소 웹훅(취소 후에도 `status`가 1로 유지됩니다)이 중복으로 걸러져 누락됩니다.

```javascript
// 웹훅 수신 시 기본 보안
app.post('/webhooks/bootpay', async (req, res) => {
    const { receipt_id, status, webhook_type, cancel_id } = req.body
    // receipt_id:status 만으로 묶으면 부분취소 웹훅(status가 1로 유지됩니다)이 삼켜집니다
    const dedupeKey = `${receipt_id}:${webhook_type ?? status}:${cancel_id ?? ''}`

    // 이벤트 고유키에는 UNIQUE 제약을 둡니다. 중복 수신은 이미 커밋된 경우에만 ACK합니다.
    if (await isProcessed(dedupeKey)) {
        return res.status(200).json({ success: true })
    }

    // 1. 중요한 데이터는 Bootpay API로 재확인
    const receipt = await Bootpay.receiptPayment(receipt_id)

    // 2. 주문·재고 처리와 완료 기록을 같은 트랜잭션으로 커밋합니다.
    //    처리 중 실패하면 예외를 반환해 재전송되도록 합니다.
    await db.transaction(async (tx) => {
        await processWebhook(status, receipt, { tx })
        await markProcessed(dedupeKey, { tx })
    })
    res.status(200).json({ success: true })
})
```

::: code-group sync=backend

```javascript [Node.js]
app.post('/webhook/bootpay', async (req, res) => {
    const { receipt_id, status, price, order_id, webhook_type } = req.body

    // 1. 오류 웹훅은 별도 status가 없으므로 webhook_type만으로 분기
    //    오류 본문은 { error_code, pg_error_code, message, payload, webhook_type } 구조라
    //    order_id / receipt_id / status는 최상위가 아니라 payload 안에 들어옵니다
    if (webhook_type && (webhook_type.endsWith('_FAILED') || webhook_type === 'ERROR')) {
        const { payload = {}, error_code, pg_error_code, message } = req.body
        if (webhook_type === 'PAYMENT_CANCEL_FAILED') {
            await db.refundRequests.update({ status: 'confirmation_required', failure_reason: error_code || webhook_type }, { where: { order_id: payload.order_id } })
            return res.status(200).json({ success: true })
        }
        await db.orders.update(
            {
                status: 'failed',
                failure_reason: error_code || webhook_type,
                pg_error_code,
                failure_message: message,
                failed_at: new Date()
            },
            { where: { order_id: payload.order_id } }
        )
        return res.status(200).json({ success: true })
    }

    // 2. 결제 조회 API로 검증 (위변조 방지)
    const receipt = await Bootpay.receiptPayment(receipt_id)
    const verifiedOrderId = receipt.order_id
    const order = await db.orders.findOne({ where: { order_id: verifiedOrderId } })

    // 취소 웹훅의 price 는 취소하고 남은 금액이다 — 원금은 price + cancelled_price
    const originalPrice = receipt.price + (receipt.cancelled_price || 0)
    if (!order || verifiedOrderId !== order_id || receipt.status !== status || originalPrice !== order.expected_amount) {
        return res.status(500).json({ success: false })
    }

    // 3. webhook_type 우선, 없으면 status로 fallback
    switch (webhook_type) {
        case 'PAYMENT_COMPLETED': // 결제 완료
            await db.orders.update({
                bootpay_receipt_id: receipt_id,
                amount: order.expected_amount,
                method: receipt.method,
                status: 'done',
                paid_at: new Date()
            }, { where: { order_id: verifiedOrderId } })

            // 재고 차감 — 위에서 조회한 order 를 그대로 씁니다
            for (const item of order.items) {
                await db.products.decrement('stock', {
                    by: item.quantity, where: { id: item.product_id }
                })
            }
            break

        case 'PAYMENT_CANCELLED': // 전체 취소 — 주문 전체를 환불 처리
            await db.orders.update(
                { status: 'refunded' },
                { where: { bootpay_receipt_id: receipt_id } }
            )
            // 재고 복구
            const refundOrder = await db.orders.findOne({
                where: { bootpay_receipt_id: receipt_id }
            })
            for (const item of refundOrder.items) {
                await db.products.increment('stock', {
                    by: item.quantity, where: { id: item.product_id }
                })
            }
            break

        case 'PAYMENT_PARTIAL_CANCELLED': // 부분 취소 — 잔여 금액만 갱신, 주문은 유지
            await db.orders.update(
                {
                    status: 'partially_refunded',
                    // 잔여 금액은 별도 필드가 아니라 receipt.price 자체입니다 (원금 − 누적취소)
                    remaining_amount: receipt.price,
                    cancelled_amount: receipt.cancelled_price
                },
                { where: { bootpay_receipt_id: receipt_id } }
            )
            const thisCancelAmount = receipt.cancelled_price - (order.cancelled_amount || 0)
            await db.refundLogs.create({ bootpay_receipt_id: receipt_id, cancel_id: req.body.cancel_id, amount: thisCancelAmount, refunded_at: new Date() })
            break

        case 'PAYMENT_VIRTUAL_ACCOUNT_ISSUED': // 가상계좌 발급 (입금 대기)
            await db.orders.update(
                { status: 'pending', bootpay_receipt_id: receipt_id },
                { where: { order_id } }
            )
            break

        default:
            // 구버전 SDK 대비 — webhook_type이 없으면 status 기반으로 처리
            if (status === 1) {/* 결제 완료 */}
            else if (status === 20) {/* 취소 (부분/전체 구분 불가) */}
            else if (status === 5) {/* 가상계좌 발급 */}
    }

    res.status(200).json({ success: true })
})
```

```python [Python]
@app.post('/webhook/bootpay')
def payment_webhook():
    data = request.get_json()
    webhook_type = data.get('webhook_type')

    # 오류 웹훅은 검증 전에 처리 — order_id는 최상위가 아니라 payload 안에 있습니다
    if webhook_type and (webhook_type.endswith('_FAILED') or webhook_type == 'ERROR'):
        payload = data.get('payload') or {}
        if webhook_type == 'PAYMENT_CANCEL_FAILED':
            RefundRequest.mark_failed_or_confirmation_required(payload.get('order_id'), reason=data.get('error_code'))
        else:
            Order.mark_failed(payload.get('order_id'), reason=data.get('error_code') or webhook_type, message=data.get('message'))
        return jsonify({'success': True})

    receipt = bootpay.receipt_payment(data['receipt_id'])

    if receipt['status'] != data['status'] or receipt['price'] != data['price']:
        return jsonify({'success': False}), 500

    if webhook_type == 'PAYMENT_COMPLETED':
        Order.mark_paid(receipt['order_id'], receipt)  # 조회 영수증의 order_id 사용
    elif webhook_type == 'PAYMENT_CANCELLED':
        Order.mark_refunded_by_receipt(data['receipt_id'])
    elif webhook_type == 'PAYMENT_PARTIAL_CANCELLED':
        Order.mark_partially_refunded(
            data['receipt_id'],
            # 잔여 금액은 별도 필드가 아니라 receipt['price'] 자체입니다 (원금 − 누적취소)
            remaining=receipt['price'],
            amount=receipt.get('cancelled_price', 0) - Order.previous_cancelled_amount(data['receipt_id']), cancel_id=data.get('cancel_id'))
    elif webhook_type == 'PAYMENT_VIRTUAL_ACCOUNT_ISSUED':
        Order.mark_pending_deposit(data['order_id'], data['receipt_id'])
    else:  # 구버전 SDK fallback
        if data['status'] == 1:
            Order.mark_paid(receipt['order_id'], receipt)  # 조회 영수증의 order_id 사용
        elif data['status'] == 20:
            Order.mark_refunded_by_receipt(data['receipt_id'])
        elif data['status'] == 5:
            Order.mark_pending_deposit(data['order_id'], data['receipt_id'])

    return jsonify({'success': True})
```

```php [PHP]
$data = json_decode(file_get_contents('php://input'), true);
$webhookType = $data['webhook_type'] ?? null;

// 오류 웹훅은 검증 전에 처리 — order_id는 최상위가 아니라 payload 안에 있습니다
if ($webhookType && (str_ends_with($webhookType, '_FAILED') || $webhookType === 'ERROR')) {
    $payload = $data['payload'] ?? [];
    if ($webhookType === 'PAYMENT_CANCEL_FAILED') { RefundRequest::markConfirmationRequired($payload['order_id'] ?? null, $data['error_code'] ?? $webhookType); } else { Order::markFailed($payload['order_id'] ?? null, $data['error_code'] ?? $webhookType, $data['message'] ?? null); }
    echo json_encode(['success' => true]);
    exit;
}

$receipt = BootpayApi::receiptPayment($data['receipt_id']);

// receiptPayment()는 json_decode 객체를 돌려줍니다 — $receipt->status 처럼 읽습니다
if ($receipt->status !== $data['status'] || $receipt->price !== $data['price']) {
    http_response_code(500); echo json_encode(['success' => false]);
    exit;
}

switch ($webhookType) {
    case 'PAYMENT_COMPLETED':
        Order::markPaid($receipt->order_id, $receipt);
        break;
    case 'PAYMENT_CANCELLED':
        Order::markRefundedByReceipt($data['receipt_id']);
        break;
    case 'PAYMENT_PARTIAL_CANCELLED':
        // 잔여 금액은 별도 필드가 아니라 price 자체입니다 (원금 − 누적취소)
        Order::markPartiallyRefunded($data['receipt_id'], $receipt->price); // 주문 스냅샷
        RefundRequest::record($data['receipt_id'], $data['cancel_id'] ?? null, $receipt->cancelled_price - Order::previousCancelledAmount($data['receipt_id']));
        break;
    case 'PAYMENT_VIRTUAL_ACCOUNT_ISSUED':
        Order::markPendingDeposit($data['order_id'], $data['receipt_id']);
        break;
    default: // 구버전 SDK fallback
        if ($data['status'] === 1) Order::markPaid($receipt->order_id, $receipt);
        elseif ($data['status'] === 20) Order::markRefundedByReceipt($data['receipt_id']);
        elseif ($data['status'] === 5) Order::markPendingDeposit($data['order_id'], $data['receipt_id']);
}

echo json_encode(['success' => true]);
```

```java [Java]
@PostMapping("/webhook/bootpay")
public Map<String, Boolean> paymentWebhook(@RequestBody Map<String, Object> data) throws Exception {
    String webhookType = (String) data.get("webhook_type");

    // 오류 웹훅은 검증 전에 처리 — order_id는 최상위가 아니라 payload 안에 있습니다
    if (webhookType != null && (webhookType.endsWith("_FAILED") || webhookType.equals("ERROR"))) {
        @SuppressWarnings("unchecked")
        Map<String, Object> payload = (Map<String, Object>) data.getOrDefault("payload", Map.of());
        if ("PAYMENT_CANCEL_FAILED".equals(webhookType)) orderService.markRefundConfirmationRequired((String) payload.get("order_id"), (String) data.get("error_code")); else orderService.markFailed((String) payload.get("order_id"), (String) data.get("error_code"));
        return Map.of("success", true);
    }

    String orderId = (String) data.get("order_id");
    String receiptId = (String) data.get("receipt_id");

    var receipt = bootpay.getReceipt(receiptId);
    int status = ((Number) data.get("status")).intValue();
    double price = ((Number) data.get("price")).doubleValue();

    if (((Number) receipt.get("status")).intValue() != status ||
        ((Number) receipt.get("price")).doubleValue() != price) {
        return Map.of("success", false);
    }

    switch (webhookType == null ? "" : webhookType) {
        case "PAYMENT_COMPLETED" -> orderService.markPaid((String) receipt.get("order_id"), receipt);
        case "PAYMENT_CANCELLED" -> orderService.markRefundedByReceipt(receiptId);
        case "PAYMENT_PARTIAL_CANCELLED" -> {
            orderService.markPartiallyRefunded(receiptId, ((Number) receipt.get("price")).doubleValue()); // 주문 스냅샷
            orderService.recordRefund(receiptId, (String) data.get("cancel_id"), ((Number) receipt.get("cancelled_price")).doubleValue() - orderService.previousCancelledAmount(receiptId));
        }
        case "PAYMENT_VIRTUAL_ACCOUNT_ISSUED" -> orderService.markPendingDeposit(orderId, receiptId);
        default -> { // 구버전 SDK fallback
            if (status == 1) orderService.markPaid((String) receipt.get("order_id"), receipt);
            else if (status == 20) orderService.markRefundedByReceipt(receiptId);
            else if (status == 5) orderService.markPendingDeposit(orderId, receiptId);
        }
    }

    return Map.of("success", true);
}
```

```ruby [Ruby]
post '/webhook/bootpay' do
  data = JSON.parse(request.body.read)
  webhook_type = data['webhook_type']

  # 오류 웹훅은 검증 전에 처리 — order_id는 최상위가 아니라 payload 안에 있습니다
  if webhook_type && (webhook_type.end_with?('_FAILED') || webhook_type == 'ERROR')
    payload = data['payload'] || {}
    if webhook_type == 'PAYMENT_CANCEL_FAILED'
      RefundRequest.mark_confirmation_required(payload['order_id'], reason: data['error_code'])
    else
      Order.mark_failed(payload['order_id'], reason: data['error_code'] || webhook_type, message: data['message'])
    end
    return { success: true }.to_json
  end

  receipt = bootpay.receipt_payment(data['receipt_id']).data  # SDK 응답은 심볼 키, 웹훅 본문(data)은 문자열 키

  unless receipt[:status] == data['status'] && receipt[:price] == data['price']
    return { success: false }.to_json
  end

  case webhook_type
  when 'PAYMENT_COMPLETED'
    Order.mark_paid(receipt[:order_id], receipt)  # 조회 영수증의 order_id 사용
  when 'PAYMENT_CANCELLED'
    Order.mark_refunded_by_receipt(data['receipt_id'])
  when 'PAYMENT_PARTIAL_CANCELLED'
    # 잔여 금액은 별도 필드가 아니라 price 자체입니다 (원금 − 누적취소)
    Order.mark_partially_refunded(data['receipt_id'], remaining: receipt[:price]) # 주문 스냅샷
    RefundRequest.record(data['receipt_id'], data['cancel_id'], receipt[:cancelled_price] - Order.previous_cancelled_amount(data['receipt_id']))
  when 'PAYMENT_VIRTUAL_ACCOUNT_ISSUED'
    Order.mark_pending_deposit(data['order_id'], data['receipt_id'])
  else # 구버전 SDK fallback
    case data['status']
    when 1 then Order.mark_paid(receipt[:order_id], receipt)  # 조회 영수증의 order_id 사용
    when 20 then Order.mark_refunded_by_receipt(data['receipt_id'])
    when 5 then Order.mark_pending_deposit(data['order_id'], data['receipt_id'])
    end
  end

  { success: true }.to_json
end
```

```go [Go]
func paymentWebhook(w http.ResponseWriter, r *http.Request) {
	var data struct {
		ReceiptID   string  `json:"receipt_id"`
		OrderID     string  `json:"order_id"`
		Status      int     `json:"status"`
		Price       float64 `json:"price"`
		WebhookType string  `json:"webhook_type"`
		CancelID    string  `json:"cancel_id"`
		// 오류 웹훅은 order_id / receipt_id / status가 payload 안에 들어옵니다
		ErrorCode string `json:"error_code"`
		Message   string `json:"message"`
		Payload   struct {
			ReceiptID string `json:"receipt_id"`
			OrderID   string `json:"order_id"`
			Status    int    `json:"status"`
		} `json:"payload"`
	}
	json.NewDecoder(r.Body).Decode(&data)

	// 오류 웹훅은 검증 전에 처리
	if strings.HasSuffix(data.WebhookType, "_FAILED") || data.WebhookType == "ERROR" {
		if data.WebhookType == "PAYMENT_CANCEL_FAILED" { markRefundConfirmationRequired(data.Payload.OrderID, data.ErrorCode) } else { markOrderFailed(data.Payload.OrderID, data.ErrorCode) }
		json.NewEncoder(w).Encode(map[string]bool{"success": true})
		return
	}

	receipt, err := api.GetReceipt(data.ReceiptID)
	if err != nil {
		http.Error(w, "receipt 조회 실패", http.StatusInternalServerError)
		return
	}
	// 조회 실패 응답(error_code)에는 status·price 가 없으므로 comma-ok 로 읽습니다
	statusF, _ := receipt["status"].(float64)
	status := int(statusF)
	price, _ := receipt["price"].(float64)
	if status != data.Status || price != data.Price {
		http.Error(w, "웹훅 검증 실패", http.StatusInternalServerError)
		return
	}

	switch data.WebhookType {
	case "PAYMENT_COMPLETED":
		markOrderPaid(receipt["order_id"].(string), receipt)
	case "PAYMENT_CANCELLED":
		markOrderRefundedByReceipt(data.ReceiptID)
	case "PAYMENT_PARTIAL_CANCELLED":
		// 잔여 금액은 별도 필드가 아니라 price 자체입니다 (원금 − 누적취소)
		remain, _ := receipt["price"].(float64)
		markOrderPartiallyRefunded(data.ReceiptID, remain) // 주문 스냅샷
		markRefund(data.ReceiptID, data.CancelID, receipt["cancelled_price"].(float64)-previousCancelledAmount(data.ReceiptID))
	case "PAYMENT_VIRTUAL_ACCOUNT_ISSUED":
		markOrderPendingDeposit(data.OrderID, data.ReceiptID)
	default: // 구버전 SDK fallback
		switch data.Status {
		case 1:
			markOrderPaid(receipt["order_id"].(string), receipt)
		case 20:
			markOrderRefundedByReceipt(data.ReceiptID)
		case 5:
			markOrderPendingDeposit(data.OrderID, data.ReceiptID)
		}
	}

	json.NewEncoder(w).Encode(map[string]bool{"success": true})
}
```

```csharp [.NET]
[HttpPost("/webhook/bootpay")]
public async Task<IActionResult> PaymentWebhook([FromBody] BootpayWebhook data)
{
    // 오류 웹훅은 검증 전에 처리 — OrderId는 최상위가 아니라 Payload 안에 있습니다
    if (data.WebhookType != null && (data.WebhookType.EndsWith("_FAILED") || data.WebhookType == "ERROR")) {
        if (data.WebhookType == "PAYMENT_CANCEL_FAILED") await orderService.MarkRefundConfirmationRequiredAsync(data.Payload?.OrderId, data.ErrorCode ?? data.WebhookType); else await orderService.MarkFailedAsync(data.Payload?.OrderId, data.ErrorCode ?? data.WebhookType);
        return Ok(new { Success = true });
    }

    var response = await bootpay.GetReceipt(data.ReceiptId);
    var body = await response.Content.ReadAsStringAsync();
    var receipt = JsonConvert.DeserializeObject<Dictionary<string, object>>(body);

    if (Convert.ToInt32(receipt["status"]) != data.Status ||
        Convert.ToDouble(receipt["price"]) != data.Price) {
        return StatusCode(500, new { Success = false });
    }

    switch (data.WebhookType) {
        case "PAYMENT_COMPLETED":
            await orderService.MarkPaidAsync((string) receipt["order_id"], receipt);
            break;
        case "PAYMENT_CANCELLED":
            await orderService.MarkRefundedByReceiptAsync(data.ReceiptId);
            break;
        case "PAYMENT_PARTIAL_CANCELLED":
            // 잔여 금액은 별도 필드가 아니라 price 자체입니다 (원금 − 누적취소)
            var remain = Convert.ToDouble(receipt["price"]);
            await orderService.MarkPartiallyRefundedAsync(data.ReceiptId, remain); // 주문 스냅샷
            await orderService.RecordRefundAsync(data.ReceiptId, data.CancelId, Convert.ToDouble(receipt["cancelled_price"]) - await orderService.PreviousCancelledAmountAsync(data.ReceiptId));
            break;
        case "PAYMENT_VIRTUAL_ACCOUNT_ISSUED":
            await orderService.MarkPendingDepositAsync(data.OrderId, data.ReceiptId);
            break;
        default: // 구버전 SDK fallback
            if (data.Status == 1) await orderService.MarkPaidAsync((string) receipt["order_id"], receipt);
            else if (data.Status == 20) await orderService.MarkRefundedByReceiptAsync(data.ReceiptId);
            else if (data.Status == 5) await orderService.MarkPendingDepositAsync(data.OrderId, data.ReceiptId);
            break;
    }

    return Ok(new { Success = true });
}
```

:::

::: warning 반드시 결제 조회 API로 검증합니다
결제 웹훅의 `receipt_id`로 Bootpay 서버에서 영수증을 직접 조회해, 금액(`price`)과 상태(`status`)가 일치하는지 확인합니다.
:::

::: tip 가상계좌 흐름
가상계좌는 웹훅이 두 번 올 수 있습니다: 발급 시(`status: 5`, `webhook_type: PAYMENT_VIRTUAL_ACCOUNT_ISSUED`) → 입금 완료 시(`status: 1`, `webhook_type: PAYMENT_COMPLETED`). 두 이벤트를 모두 처리해야 합니다.
:::

### webhook_type 처리 권장 전략

1. **`webhook_type`을 1차 분기 기준으로 사용합니다.** 결제를 요청한 SDK 버전이 4.10.0 초과(베타 제외) 또는 5.1.6 초과이면 항상 채워져 들어옵니다. `status`만으로는 부분취소를 포착할 수 없습니다.
2. **`default`(fallback)로 `status` 분기를 남겨 둡니다.** 낮은 SDK 버전과 정의되지 않은 이벤트에 대비합니다. 단, 부분취소는 `status: 1`로 도착하므로 이 경로에서는 결제완료와 구분되지 않아 **부분취소 발생 자체를 포착할 수 없습니다**.
3. **오류 웹훅(`*_FAILED`, `ERROR`)은 결제 조회 API 검증 전에 분기합니다.** `PAYMENT_CANCEL_FAILED`는 결제 주문 상태를 유지하고 환불 요청만 `failed` 또는 `confirmation_required`로 기록합니다. 승인 실패(`PAYMENT_CONFIRM_FAILED`)와 같은 주문 실패 경로로 합치면 안 됩니다. 오류 처리와 저장이 끝난 뒤에만 `success: true`를 반환합니다.
4. **`webhook_type`을 로깅 키로 사용합니다.** 운영 모니터링·알림에서 이벤트별 수신량을 집계합니다.

## 디버깅: 웹훅이 안 올 때

| # | 확인 사항 | 해결 방법 |
|---|----------|----------|
| 1 | 웹훅 URL이 HTTPS인가? | HTTP도 등록은 되지만 운영에서는 HTTPS를 사용합니다. SSL 인증서가 유효한지 확인 |
| 2 | 관리자에서 이벤트를 선택했는가? | 관리자 → [웹훅 설정](https://admin.bootpay.co.kr/setting/developer?tab=webhook)에서 필요한 이벤트 체크 |
| 3 | 응답 본문에 `{"success": true}`를 담았는가? | 이 값이 없으면 HTTP 200이어도 실패로 기록되고 재시도됨 |
| 4 | 방화벽이 차단하지 않는가? | Bootpay 발신 IP 대역 `223.130.82.0/24` 허용 |
| 5 | 로컬 개발 환경인가? | ngrok 등 터널링 도구 사용 |
| 6 | 테스트 웹훅을 발송해봤는가? | [웹훅 설정](https://admin.bootpay.co.kr/setting/developer?tab=webhook)에서 테스트 웹훅 발송 기능 사용 |
| 7 | 샌드박스 모드인가? | 샌드박스에서도 웹훅은 정상 발송됨 |

## 로컬 개발 시 웹훅 받기

로컬 개발 환경에서는 외부에서 접근할 수 없으므로 터널링 도구를 사용합니다.

```bash
# ngrok 사용
ngrok http 3000
# → https://abc123.ngrok.io 주소를 웹훅 URL로 등록

# 또는 localtunnel
npx localtunnel --port 3000
```

::: tip
터널링 URL을 Bootpay 관리자 [웹훅 설정](https://admin.bootpay.co.kr/setting/developer?tab=webhook)에 등록하면 로컬에서도 웹훅을 수신할 수 있습니다.
:::
