bootpaydevelopers
관리자

웹훅 이벤트 처리

웹훅 이벤트별로 가맹점 서버가 할 처리를 정리합니다. URL 등록 · 페이로드 · webhook_type 값 · 재시도 정책 · 발신 IP 는 웹훅에 있고, 언어별 수신 코드는 이 문서에만 둡니다.

결제 웹훅

상태별 처리

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

오류 웹훅 처리

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

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

결제 웹훅 처리 코드

아래 언어별 예제는 모두 다음 원칙을 따릅니다. 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 })
})
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 })
})

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관리자에서 이벤트를 선택했는가?관리자 → 웹훅 설정에서 필요한 이벤트 체크
3응답 본문에 {"success": true}를 담았는가?이 값이 없으면 HTTP 200이어도 실패로 기록되고 재시도됨
4방화벽이 차단하지 않는가?Bootpay 발신 IP 대역 223.130.82.0/24 허용
5로컬 개발 환경인가?ngrok 등 터널링 도구 사용
6테스트 웹훅을 발송해봤는가?웹훅 설정에서 테스트 웹훅 발송 기능 사용
7샌드박스 모드인가?샌드박스에서도 웹훅은 정상 발송됨

로컬 개발 시 웹훅 받기

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

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

# 또는 localtunnel
npx localtunnel --port 3000