자동결제 전체 구현 예제

빌링키 발급·저장·첫 결제·회차 청구를 구현합니다. 빌링키 저장 설계·조회·삭제·청구 API 세부 옵션은 자동결제 상세 문서에서 확인합니다.

자동결제는 빌링키​​로 원하는 시점에 결제 승인을 요청하는 방식입니다. 고객이 결제창에 카유생비​(카드번호, 유효기간, 생년월일, 비밀번호 앞 2자리)를 입력하면 PG/카드사가 카드 정보를 확인하고 빌링키를 발급합니다. 가맹점 서버는 카드 정보를 직접 저장할 수 없으므로, 결제에 사용할 수 있는 암호화된 식별값인 빌링키를 저장합니다.

빌링키 발급 방식은 두 가지입니다. 프론트엔드에서 PG 결제창을 띄워 고객이 직접 입력하는 방식​​과, 일부 PG에서 지원하는 백엔드 REST API로 카드 정보를 전달해 직접 발급하는 방식​​입니다. 어느 방식이든 백엔드가 billing_key를 저장하고, 저장된 빌링키로 Bootpay API에 결제 승인을 요청합니다. 청구 금액과 요청 주기는 가맹점 정책에 맞게 정합니다.

회차 실행 방식

이 문서는 서버 cron 이 매 회차 Bootpay 승인 API 를 호출하는 방식입니다. 결제일마다 예약결제를 등록해 Bootpay 가 예약 시각에 빌링키 결제를 실행하게 하는 방식은 예약결제에서 다루고, 회차 관리·조정·해지를 Bootpay 에 맡기는 구독은 커머스 구독 가이드에서 다룹니다.

연동 흐름

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

저장 테이블

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

회차 관리 — recurring_payments

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

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)
);sql
컬럼 의미
next_payment_at 다음 청구 시각. 성공하면 다음 주기로 이동하고, 실패하면 재시도 시각으로 조정
status active → paused → cancelled 단방향 전이
retry_count 연속 실패 횟수. 3회 도달 시 paused로 전환
idx_next 스케줄러 조회 인덱스. (next_payment_at, status) 복합

status 전이

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

idx_next 가 없으면 청구 누락 위험

스케줄러가 매번 풀스캔해야 하므로 회원이 늘면 청구 시각을 놓칠 수 있습니다. (next_payment_at, status) 복합 인덱스는 처음부터 걸어둡니다.

구현 순서

빌링키 발급 A — PG 결제창에서 발급 (프론트엔드)

프론트엔드에서 Bootpay SDK로 PG 결제창을 띄우고, 고객이 결제창에 카유생비를 입력하면 빌링키 발급이 진행됩니다. 발급 완료 후에는 receipt_id를 백엔드로 보내고, 서버에서 빌링키를 조회해 저장해야 합니다.

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.receipt_id,
                plan: 'monthly',
            }),
        })
    }
}javascript

상세 문서: 빌링키 발급

빌링키 발급 B — REST API로 직접 발급 (백엔드, 선택)

일부 PG는 백엔드 REST API로 빌링키를 직접 발급할 수 있습니다. 이 방식은 가맹점 화면에서 카드 정보를 입력받아 서버로 전달하고, 서버가 Bootpay API에 빌링키 발급을 요청합니다.

REST API 직접 발급 지원 PG사

나이스페이먼츠, 페이앱, 웰컴페이먼츠, 토스페이먼츠, 키움페이, 라이트페이

카드번호·유효기간·생년월일·비밀번호 앞 2자리를 가맹점 시스템이 직접 취급하므로, 지원 PG 여부와 보안 책임을 먼저 확인해야 합니다.

app.post('/api/billing-key/issue', auth, async (req, res) => {
    const { card_no, card_pw, card_identity_no, card_expire_year, card_expire_month } = req.body

    const info = await Bootpay.requestSubscribeBillingKey({
        pg: 'nicepay',
        method: '카드자동(REST)',  // 생략하면 기본값 '카드자동'이 되어 RC_ONLY_REST_API(2058)로 거절됩니다
        subscription_id: `sub_${req.user.id}_${Date.now()}`,
        order_name: '정기결제 카드 등록',
        card_no,
        card_pw,
        card_identity_no,
        card_expire_year,
        card_expire_month,
    })

    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),
        status: 'active'
    })

    res.json({ success: true })
})javascript

상세 문서: 백엔드에서 발급하기

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

A 방식은 프론트엔드에서 받은 receipt_id로 빌링키를 조회한 뒤 저장해야 합니다. B 방식은 발급 API 응답에 billing_key가 들어오므로 조회 단계 없이 저장할 수 있습니다.

아래 예시는 A 방식 기준입니다. 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 })
    }
})javascript

상세 문서: 빌링키 조회 · 빌링키 결제 요청 — 7개 언어 예제를 확인합니다.

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

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

billing_key와 order_name은 회차 테이블에 없습니다

저장 테이블의 recurring_payments에는 billing_key·order_name 컬럼이 없습니다. billing_key는 billing_keys를 user_id로 조인해 활성 행에서 가져오고, order_name은 plan 값으로 플랜명을 만들어 넣어야 합니다.

// 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)
}javascript

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

자체 cron 대신 예약결제 반복

같은 빌링키로 결제일마다 예약결제를 등록하면 Bootpay 가 예약 시각에 빌링키 결제를 실행합니다. → 예약결제

구독 해지 (백엔드)

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: '구독이 해지되었습니다' })
})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
    })
})javascript

함께 보기