bootpaydevelopers
관리자

예약결제 전체 구현 예제

빌링키를 발급·저장하고 원하는 시점의 결제를 예약한 뒤, 실행 결과를 웹훅으로 받아 확정하는 예제입니다. 예약결제 · 예약 상태 · 만료 처리의 개념은 가이드 예약결제에 있고, API별 파라미터 · 에러는 결제 예약 · 예약 조회 · 예약 취소에 있습니다.

연동 흐름

1. 빌링키 발급

구매자프론트엔드백엔드Bootpay/PGA. PG 결제창에 카유생비 입력A. requestSubscription()A. receipt_id 응답A. receipt_id 전달A. 빌링키 조회A. billing_key 응답B. 가맹점 화면에 카유생비 입력B. 카드 정보 전달B. REST API로 빌링키 발급 요청B. billing_key 응답billing_key 저장

2. 예약 등록과 실행

백엔드Bootpay/PG가맹점 DB저장된 billing_key 조회예약 결제 등록reserve_id 응답예약 시각에 결제 실행웹훅 전송예약 상태·receipt_id 저장

빌링키 발급과 예약 등록은 별개의 단계입니다. 먼저 둘 중 한 방식으로 빌링키를 발급·저장하고, 이후 서버에서 저장된 billing_key로 예약 결제 API를 호출해야 합니다.

구현 순서

  1. 빌링키 발급 (프론트엔드)

    프론트엔드에서 PG 결제창을 띄워 고객이 카유생비를 입력하면 빌링키가 발급됩니다. 발급이 끝나면 receipt_id를 백엔드로 보냅니다. 빌링키 발급은 자동결제와 같아서, iOS · Android · Flutter · React Native 코드와 파라미터는 빌링키 발급 › 프론트엔드에서 발급하기에 있습니다.

    JavaScript
    async function registerCard() {
        const response = await Bootpay.requestSubscription({
            client_key: '[ Client Key ]',
            pg: '나이스페이',
            method: '카드자동',
            subscription_id: 'sub_' + Date.now(),  // 고유 ID
            price: 0,  // 0원 = 빌링키만 발급 (결제 없음)
            order_name: '카드 등록',
            user: { username: '홍길동', phone: '01012345678' },
            extra: { subscribe_test_payment: true },  // 100원 테스트 결제 후 자동 취소
        })
    
        if (response.event === 'done') {
            await fetch('/api/billing-key/save', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ receipt_id: response.data.receipt_id }),
            })
        }
    }

    일부 PG는 가맹점 화면에서 카드 정보를 받아 서버가 REST API로 직접 발급할 수도 있습니다. 이때는 method: '카드자동(REST)' 를 반드시 보내고, 응답에 billing_key가 바로 들어와 아래 조회 단계 없이 저장합니다. 지원 PG · 코드 · 보안 주의는 백엔드에서 발급하기에 있습니다.

  2. 빌링키 저장 (백엔드)

    billing_keys 테이블 스키마는 자동결제와 같습니다(빌링키 발급 › 발급 결과 저장).

    아래 코드는 프론트엔드 결제창에서 받은 receipt_id로 빌링키를 조회해 저장하는 흐름입니다.

    Node.js는 저장 핸들러까지 포함하고, 다른 언어는 빌링키 조회 SDK 호출부만 보여줍니다. 토큰 발급·DB 저장·라우팅은 각 프레임워크 컨벤션에 맞게 연결합니다.

    app.post('/api/billing-key/save', auth, async (req, res) => {
        const { receipt_id } = req.body
    
        // Bootpay에서 빌링키 조회 — 카드 표시 정보는 billing_data 안에 들어있습니다
        const info = await Bootpay.lookupSubscribeBillingKey(receipt_id)
    
        // DB에 빌링키 저장
        await db.billingKeys.create({
            user_id: req.user.id,
            billing_key: info.billing_key,
            card_name: info.billing_data.card_company,   // "신한카드"
            card_no_last4: info.billing_data.card_no.slice(-4),
            status: 'active'
        })
    
        res.json({ success: true })
    })

    상세 문서: 빌링키 조회 — 7개 언어 SDK 초기화와 응답 스키마를 확인합니다.

  3. 예약 결제 등록 (백엔드)

    app.post('/api/reserve-payment', auth, async (req, res) => {
        const { amount, execute_at, description } = req.body
    
        // 사용자의 빌링키 조회
        const billingKey = await db.billingKeys.findOne({
            where: { user_id: req.user.id, status: 'active' }
        })
        if (!billingKey) {
            return res.status(400).json({ error: '등록된 카드가 없습니다' })
        }
    
        // Bootpay API 호출 → 부트페이가 예약을 보관했다가 예약 시각에 실행
        const result = await Bootpay.subscribePaymentReserve({
            billing_key: billingKey.billing_key,
            price: amount,
            order_name: description,
            order_id: 'reserve_' + Date.now(),
            reserve_execute_at: execute_at,  // '2025-03-01T09:00:00 +0900', 2개월 이내
            feedback_url: 'https://example.com/webhooks/bootpay'
        })
    
        // 예약 정보 저장
        await db.reservePayments.create({
            user_id: req.user.id,
            reserve_id: result.reserve_id,
            amount,
            execute_at,
            description,
            status: 'reserved'
        })
    
        res.json({
            success: true,
            reserve_id: result.reserve_id,
            execute_at: result.reserve_execute_at
        })
    })

    상세 문서: 결제 예약 — 7개 언어 예제와 응답 스키마를 확인합니다.

  4. 웹훅 수신 — 예약 실행 결과 (백엔드)

    예약 시간이 되면 부트페이가 저장된 빌링키로 PG사에 결제를 요청하고, 그 결과를 가맹점 서버로 웹훅으로 보냅니다.

    웹훅 본문은 event·data로 감싸여 오지 않고 평면 객체로 옵니다. 성공과 실패는 서로 다른 형태로 오기 때문에, error_code가 있는지로 먼저 구분해야 합니다.

    JavaScript
    app.post('/webhooks/bootpay', async (req, res) => {
        res.status(200).json({ success: true })
    
        // 실패: { error_code, pg_error_code, message, payload: { order_id, reserve_id, metadata } }
        if (req.body.error_code) {
            const { reserve_id } = req.body.payload || {}
            await db.reservePayments.update(
                { status: 'failed', fail_reason: req.body.message },
                { where: { reserve_id } }
            )
            // 고객에게 결제 실패 알림 — 부트페이는 자동으로 재시도하지 않습니다
            return
        }
    
        // 성공: { receipt_id, reserve_id, order_id, price, status, ... }
        const { receipt_id, reserve_id, status } = req.body
    
        if (reserve_id && status === 1) {
            // receipt_id로 결제를 다시 조회해 금액을 검증한 뒤 확정합니다
            await db.reservePayments.update(
                {
                    status: 'done',
                    receipt_id,
                    paid_at: new Date()
                },
                { where: { reserve_id } }
            )
        }
    })

    성공 본문의 status는 결제 상태값으로 1이 결제 완료입니다. 예약 자체의 상태(0 대기 / 1 완료 / -1 실패 / 3 취소)는 예약 조회로 확인하는 값이라 서로 다른 체계입니다.

    상세 문서: 웹훅 처리 가이드

  5. 예약 취소 (백엔드, 선택)

    예약 취소는 부트페이에 예약된 실행 작업을 삭제하는 것입니다. 아직 실행되지 않은 예약에만 쓸 수 있고, 이미 결제가 실행된 뒤에는 예약 취소가 아니라 receipt_id 기준 결제 취소를 호출해야 합니다.

    app.post('/api/reserve-payment/:id/cancel', auth, async (req, res) => {
        const reserve = await db.reservePayments.findByPk(req.params.id)
        if (!reserve || reserve.user_id !== req.user.id) {
            return res.status(404).json({ error: '예약을 찾을 수 없음' })
        }
        if (reserve.status !== 'reserved') {
            return res.status(400).json({ error: '취소할 수 없는 상태' })
        }
    
        await Bootpay.cancelSubscribeReserve(reserve.reserve_id)
    
        await db.reservePayments.update(
            { status: 'cancelled' },
            { where: { id: reserve.id } }
        )
    
        res.json({ success: true })
    })

    상세 문서: 예약 취소 — 7개 언어 예제와 에러 코드를 확인합니다.

함께 보기