bootpaydevelopers
관리자

자동결제 전체 구현 예제

빌링키 발급·저장·첫 결제·회차 청구·해지를 서버 cron 으로 구현하는 예제입니다. 빌링키 · 발급 방식 · 회차 상태 · 실패 처리의 개념은 가이드 자동결제에 있고, API별 파라미터 · 에러는 각 API 문서(빌링키 발급 · 조회 · 결제 요청 · 삭제)에 있습니다.

연동 흐름

구매자프론트엔드백엔드Bootpay/PG가맹점 DBA. PG 결제창에 카유생비 입력A. requestSubscription()A. receipt_id 응답A. receipt_id 전달A. 빌링키 조회B. 가맹점 화면에 카유생비 입력B. 카드 정보 전달B. REST API로 빌링키 발급billing_key 응답billing_key 저장첫 결제 또는 회차 결제 요청결제 결과 응답다음 결제일·재시도 상태 저장

빌링키 발급은 A 또는 B 중 하나를 선택합니다. 그 뒤로는 서버가 스케줄러·청구·재시도·해지를 모두 직접 처리해야 합니다. 예약결제와 달리 Bootpay 가 회차 결제를 자동 실행하지 않습니다.

저장 테이블

아래 코드는 테이블 두 개를 사용한다고 가정합니다. 빌링키 저장 테이블 billing_keys 는 빌링키 발급 › 발급 결과 저장과 같습니다. 결제 실패 재시도와 해지는 빌링키가 아니라 회차 테이블의 상태로 처리합니다.

회차 관리 — recurring_payments

매월 청구 회차의 상태와 재시도 카운트를 추적합니다. 스케줄러가 next_payment_at <= NOW() AND status = 'active' 인 행을 골라 빌링키 결제를 요청합니다.

SQL
CREATE TABLE recurring_payments (
    id              BIGINT PRIMARY KEY AUTO_INCREMENT,
    user_id         BIGINT NOT NULL,
    plan            VARCHAR(50) NOT NULL,     -- 'monthly', 'yearly' 등
    amount          INTEGER NOT NULL,
    next_payment_at DATETIME NOT NULL,
    receipt_id      VARCHAR(100),
    status          VARCHAR(20) DEFAULT 'active',
    retry_count     INTEGER DEFAULT 0,
    created_at      DATETIME DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_next (next_payment_at, status)
);
컬럼의미
next_payment_at다음 청구 시각. 성공하면 다음 주기로 이동하고, 실패하면 재시도 시각으로 조정
statusactive → paused → cancelled 단방향 전이
retry_count연속 실패 횟수. 3회 도달 시 paused로 전환
idx_next스케줄러 조회 인덱스. (next_payment_at, status) 복합

status 전이

activepausedcancelled결제 실패 누적해지 요청복구 포기카드 재등록 후 명시적 복구

paused로 바뀌면 카드 변경 안내 메일을 보내고, 사용자가 카드를 재등록한 시점에 명시적으로 active로 되돌립니다. 자동 복구는 하지 않고, 카드 변경 의사가 확인된 후에만 결제를 재개합니다.

구현 순서

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

    프론트엔드에서 PG 결제창을 띄워 고객이 카유생비를 입력하면 빌링키가 발급됩니다. 발급 완료 후에는 receipt_id를 백엔드로 보내고, 서버에서 빌링키를 조회해 저장해야 합니다. 아래는 Web 예시이고, iOS · Android · Flutter · React Native 코드와 파라미터는 빌링키 발급 › 프론트엔드에서 발급하기에 있습니다.

    JavaScript
    async function registerCard() {
        const response = await Bootpay.requestSubscription({
            client_key: '[ Client Key ]',
            pg: 'nicepay',
            method: '카드자동',
            subscription_id: 'sub_' + Date.now(),
            price: 0,  // 빌링키만 발급
            order_name: '정기결제 카드 등록',
            user: { username: '홍길동', phone: '01012345678' },
            extra: { subscribe_test_payment: true },
        })
    
        if (response.event === 'done') {
            await fetch('/api/recurring/register', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    receipt_id: response.data.receipt_id,
                    plan: 'monthly',
                }),
            })
        }
    }

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

  2. 빌링키 저장 + 첫 결제 (백엔드)

    프론트엔드에서 받은 receipt_id로 빌링키를 조회한 뒤 저장합니다. lookupSubscribeBillingKey로 발급된 빌링키를 조회하고, requestSubscribePayment로 첫 결제를 실행합니다.

    const PLANS = {
        monthly: { name: '월간 구독', price: 9900, interval_days: 30 },
        yearly: { name: '연간 구독', price: 99000, interval_days: 365 }
    }
    
    app.post('/api/recurring/register', auth, async (req, res) => {
        const { receipt_id, plan } = req.body
        const planInfo = PLANS[plan]
        if (!planInfo) return res.status(400).json({ error: '잘못된 플랜' })
    
        // 빌링키 조회·저장 — 카드 표시 정보는 billing_data 안에 들어있습니다
        const info = await Bootpay.lookupSubscribeBillingKey(receipt_id)
    
        await db.billingKeys.create({
            user_id: req.user.id,
            billing_key: info.billing_key,
            card_name: info.billing_data.card_company,
            card_last4: info.billing_data.card_no.slice(-4)
        })
    
        // 첫 결제 실행 — 승인 실패는 HTTP 4xx/5xx + { error_code, ... }로 오므로 예외로 잡아야 합니다
        try {
            const payment = await Bootpay.requestSubscribePayment({
                billing_key: info.billing_key,
                price: planInfo.price,
                order_name: planInfo.name,
                order_id: `recurring_${req.user.id}_${Date.now()}`
            })
    
            // 다음 결제일 등록
            const nextDate = new Date()
            nextDate.setDate(nextDate.getDate() + planInfo.interval_days)
    
            await db.recurringPayments.create({
                user_id: req.user.id,
                plan,
                amount: planInfo.price,
                next_payment_at: nextDate,
                receipt_id: payment.receipt_id,
                status: 'active'
            })
    
            res.json({ success: true, next_payment_at: nextDate })
        } catch (e) {
            // e.error_code === 'RC_CONFIRM_FAILED'이면 PG 승인 거절 (한도초과·잔액부족 등)
            res.json({ success: false, error: '첫 결제 실패', error_code: e.error_code })
        }
    })

    7개 언어 예제는 빌링키 조회와 빌링키 결제 요청에 있습니다.

  3. 회차 자동 결제 — 스케줄러 (백엔드)

    매일 실행되는 스케줄러(cron)로 결제일이 된 건을 처리해야 합니다. 스케줄러·큐·재시도·이메일·일시정지 정책은 각 백엔드 프레임워크의 방식대로 구현하고, 스케줄러 안에서는 저장된 billing_key로 결제 요청 API를 호출해야 합니다.

    // billing_key는 billing_keys에서 조인해 가져옵니다
    const billingKey = await db.billingKeys.findOne({
        where: { user_id: recurring.user_id, status: 'active' }
    })
    if (!billingKey) return await handlePaymentFailure(recurring)
    
    try {
        const payment = await Bootpay.requestSubscribePayment({
            billing_key: billingKey.billing_key,
            price: recurring.amount,
            order_name: PLANS[recurring.plan].name,  // order_name은 플랜명으로 생성
            order_id: `recurring_${recurring.user_id}_${Date.now()}`
        })
        // receipt_id 저장, 다음 결제일 갱신
        await markRecurringPaid(recurring, payment.receipt_id)
    } catch (e) {
        await handlePaymentFailure(recurring, e)
    }

    스케줄러는 서버 스택의 표준 도구를 사용합니다. Python은 APScheduler나 Celery beat, Java는 Spring @Scheduled나 Quartz, Ruby는 whenever나 Sidekiq, Go는 robfig/cron, .NET은 IHostedService를 사용할 수 있습니다.

  4. 구독 해지 (백엔드)

    JavaScript
    app.post('/api/recurring/cancel', auth, async (req, res) => {
        const recurring = await db.recurringPayments.findOne({
            where: { user_id: req.user.id, status: ['active', 'paused'] }
        })
        if (!recurring) return res.status(404).json({ error: '활성 구독 없음' })
    
        // 구독 상태 변경 (현재 주기 끝까지는 서비스 유지 가능)
        await recurring.update({ status: 'cancelled' })
    
        // 빌링키 삭제 (선택 — 재구독 가능하게 하려면 유지)
        // await Bootpay.destroyBillingKey(billingKey.billing_key)
    
        res.json({ success: true, message: '구독이 해지되었습니다' })
    })

    상세 문서: 빌링키 삭제

  5. 마이페이지 — 구독 조회 (백엔드)

    JavaScript
    app.get('/api/my/recurring', auth, async (req, res) => {
        const recurring = await db.recurringPayments.findOne({
            where: { user_id: req.user.id, status: ['active', 'paused'] }
        })
    
        if (!recurring) return res.json({ active: false })
    
        const billingKey = await db.billingKeys.findOne({
            where: { user_id: req.user.id, status: 'active' }
        })
    
        res.json({
            active: true,
            plan: recurring.plan,
            amount: recurring.amount,
            status: recurring.status,
            next_payment_at: recurring.next_payment_at,
            card: billingKey ? {
                name: billingKey.card_name,
                last4: billingKey.card_last4
            } : null
        })
    })

함께 보기