자동결제 전체 구현 예제
빌링키 발급·저장·첫 결제·회차 청구·해지를 서버 cron 으로 구현하는 예제입니다. 빌링키 · 발급 방식 · 회차 상태 · 실패 처리의 개념은 가이드 자동결제에 있고, API별 파라미터 · 에러는 각 API 문서(빌링키 발급 · 조회 · 결제 요청 · 삭제)에 있습니다.
연동 흐름
빌링키 발급은 A 또는 B 중 하나를 선택합니다. 그 뒤로는 서버가 스케줄러·청구·재시도·해지를 모두 직접 처리해야 합니다. 예약결제와 달리 Bootpay 가 회차 결제를 자동 실행하지 않습니다.
저장 테이블
아래 코드는 테이블 두 개를 사용한다고 가정합니다. 빌링키 저장 테이블 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)
);| 컬럼 | 의미 |
|---|---|
next_payment_at | 다음 청구 시각. 성공하면 다음 주기로 이동하고, 실패하면 재시도 시각으로 조정 |
status | active → paused → cancelled 단방향 전이 |
retry_count | 연속 실패 횟수. 3회 도달 시 paused로 전환 |
idx_next | 스케줄러 조회 인덱스. (next_payment_at, status) 복합 |
status 전이
paused로 바뀌면 카드 변경 안내 메일을 보내고, 사용자가 카드를 재등록한 시점에 명시적으로 active로 되돌립니다. 자동 복구는 하지 않고, 카드 변경 의사가 확인된 후에만 결제를 재개합니다.
구현 순서
빌링키 발급 (프론트엔드)
프론트엔드에서 PG 결제창을 띄워 고객이 카유생비를 입력하면 빌링키가 발급됩니다. 발급 완료 후에는
receipt_id를 백엔드로 보내고, 서버에서 빌링키를 조회해 저장해야 합니다. 아래는 Web 예시이고, iOS · Android · Flutter · React Native 코드와 파라미터는 빌링키 발급 › 프론트엔드에서 발급하기에 있습니다.JavaScriptasync 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 · 코드 · 보안 주의는 백엔드에서 발급하기에 있습니다.빌링키 저장 + 첫 결제 (백엔드)
프론트엔드에서 받은
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 }) } })# 1) 빌링키 조회 info = bootpay.lookup_subscribe_billing_key(receipt_id) # info['billing_key'] / info['billing_data']['card_company'] / info['billing_data']['card_no']를 DB에 저장 # 2) 첫 결제 실행 — Python SDK 는 승인 실패에 예외를 던지지 않고 # { error_code, message, ... } dict 를 돌려주므로 error_code 로 가릅니다 payment = bootpay.request_subscribe_payment( billing_key=info['billing_key'], price=plan_info['price'], order_name=plan_info['name'], order_id=f'recurring_{user_id}_{int(time.time())}', ) if 'error_code' in payment: # error_code == 'RC_CONFIRM_FAILED'이면 PG 승인 거절 handle_first_payment_failure(payment) else: # 성공 → payment['receipt_id'] 저장 후 다음 결제일 등록 ...// 1) 빌링키 조회 $info = BootpayApi::lookupSubscribeBillingKey($receiptId); // 응답은 json_decode 객체입니다 — $info->billing_key / $info->billing_data->card_company / $info->billing_data->card_no를 DB에 저장 // 2) 첫 결제 실행 — PHP SDK는 승인 실패를 예외로 던지지 않고 { error_code, message } 객체로 돌려줍니다 // (예외는 네트워크 오류 · 필수값 누락일 때만) try { $payment = BootpayApi::requestSubscribePayment([ 'billing_key' => $info->billing_key, 'price' => $planInfo['price'], 'order_name' => $planInfo['name'], 'order_id' => 'recurring_' . $userId . '_' . time(), ]); if (isset($payment->error_code)) { // error_code == 'RC_CONFIRM_FAILED'이면 PG 승인 거절 handleFirstPaymentFailure($payment); } else { // 성공 → $payment->receipt_id 저장 후 다음 결제일 등록 } } catch (Exception $e) { handleFirstPaymentFailure($e); }// 1) 빌링키 조회 var info = bootpay.lookupBillingKey(receiptId); var billingData = (Map<String, Object>) info.get("billing_data"); // info.get("billing_key") / billingData.get("card_company") / billingData.get("card_no")를 DB에 저장 // 2) 첫 결제 실행 — Java SDK 는 승인 실패를 예외로 올리지 않고 error_code 가 담긴 응답으로 돌려줍니다 // (예외는 필수값 누락 · 네트워크 오류일 때만) SubscribePayload payload = new SubscribePayload(); payload.billingKey = (String) info.get("billing_key"); payload.price = planInfo.price; payload.orderName = planInfo.name; payload.orderId = "recurring_" + userId + "_" + System.currentTimeMillis(); try { var payment = bootpay.requestSubscribe(payload); if (payment.get("error_code") != null) { // error_code가 RC_CONFIRM_FAILED이면 PG 승인 거절 handleFirstPaymentFailure(payment); } else { // 성공 → payment.get("receipt_id") 저장 후 다음 결제일 등록 } } catch (Exception e) { handleFirstPaymentFailure(e); }# 1) 빌링키 조회 info = bootpay.lookup_subscribe_billing_key(receipt_id).data # info[:billing_key] / info[:billing_data][:card_company] / info[:billing_data][:card_no]를 DB에 저장 (응답 키는 심볼) # 2) 첫 결제 실행 — Ruby SDK 는 승인 실패를 예외로 올리지 않고 success? 가 false 인 응답으로 돌려줍니다 response = bootpay.request_subscribe_payment( billing_key: info[:billing_key], price: plan_info[:price], order_name: plan_info[:name], order_id: "recurring_#{user_id}_#{Time.now.to_i}" ) if response.success? # 성공 → response.data[:receipt_id] 저장 후 다음 결제일 등록 else # response.data[:error_code]가 RC_CONFIRM_FAILED이면 PG 승인 거절 handle_first_payment_failure(response.data) end// 1) 빌링키 조회 info, err := api.LookupBillingKey(receiptID) if err != nil { log.Fatal(err) } billingKey, _ := info["billing_key"].(string) billingData, _ := info["billing_data"].(map[string]interface{}) // info["billing_key"] / billingData["card_company"] / billingData["card_no"]를 DB에 저장 // 2) 첫 결제 실행 — err 는 네트워크 오류일 때만 옵니다. 승인 실패는 응답의 error_code 로 옵니다 payment, err := api.RequestSubscribe(bootpay.SubscribePayload{ BillingKey: billingKey, Price: planInfo.Price, OrderName: planInfo.Name, OrderId: fmt.Sprintf("recurring_%d_%d", userID, time.Now().Unix()), }) if err != nil { handleFirstPaymentFailure(err) return } if errorCode, ok := payment["error_code"].(string); ok { // error_code가 RC_CONFIRM_FAILED이면 PG 승인 거절 handleFirstPaymentFailure(errors.New(errorCode)) return } // 성공 → payment["receipt_id"] 저장 후 다음 결제일 등록// 1) 빌링키 조회 var infoResponse = await bootpay.LookupBillingKey(receiptId); var infoJson = await infoResponse.Content.ReadAsStringAsync(); // infoJson에서 billing_key / billing_data.card_company / billing_data.card_no를 추출해 DB에 저장 var billingKey = "[ parsed billing_key ]"; // 2) 첫 결제 실행 — 승인 실패는 HTTP 4xx/5xx + { error_code, ... } 본문으로 옵니다 var paymentResponse = await bootpay.RequestSubscribe(new SubscribePayload { billingKey = billingKey, price = planInfo.Price, orderName = planInfo.Name, orderId = $"recurring_{userId}_{DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}", }); var paymentJson = await paymentResponse.Content.ReadAsStringAsync(); if (!paymentResponse.IsSuccessStatusCode) { // paymentJson의 error_code가 RC_CONFIRM_FAILED이면 PG 승인 거절 HandleFirstPaymentFailure(paymentJson); return; } // 성공 → paymentJson의 receipt_id를 저장하고 다음 결제일을 등록합니다회차 자동 결제 — 스케줄러 (백엔드)
매일 실행되는 스케줄러(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) }# billing_key는 billing_keys에서 조인해 가져옵니다 billing_key = find_active_billing_key(recurring['user_id']) if billing_key is None: handle_payment_failure(recurring) return payment = bootpay.request_subscribe_payment( billing_key=billing_key['billing_key'], price=recurring['amount'], order_name=PLANS[recurring['plan']]['name'], # order_name은 플랜명으로 생성 order_id=f"recurring_{recurring['user_id']}_{int(time.time())}", ) # Python SDK 는 실패를 예외가 아니라 error_code 가 든 dict 로 돌려줍니다 if 'error_code' in payment: handle_payment_failure(recurring, payment) else: # receipt_id 저장, 다음 결제일 갱신 mark_recurring_paid(recurring, payment['receipt_id'])// billing_key는 billing_keys에서 조인해 가져옵니다 $billingKey = findActiveBillingKey($recurring['user_id']); if ($billingKey === null) { handlePaymentFailure($recurring, null); return; } try { $payment = BootpayApi::requestSubscribePayment([ 'billing_key' => $billingKey['billing_key'], 'price' => $recurring['amount'], 'order_name' => PLANS[$recurring['plan']]['name'], // order_name은 플랜명으로 생성 'order_id' => 'recurring_' . $recurring['user_id'] . '_' . time(), ]); // 승인 실패는 예외가 아니라 error_code가 든 응답 객체로 옵니다 if (isset($payment->error_code)) { handlePaymentFailure($recurring, $payment); return; } // receipt_id 저장, 다음 결제일 갱신 markRecurringPaid($recurring, $payment->receipt_id); } catch (Exception $e) { handlePaymentFailure($recurring, $e); }// billing_key는 billing_keys에서 조인해 가져옵니다 var billingKey = findActiveBillingKey(recurring.getUserId()); if (billingKey == null) { handlePaymentFailure(recurring, null); return; } SubscribePayload payload = new SubscribePayload(); payload.billingKey = billingKey.getBillingKey(); payload.price = recurring.getAmount(); payload.orderName = PLANS.get(recurring.getPlan()).name; // order_name은 플랜명으로 생성 payload.orderId = "recurring_" + recurring.getUserId() + "_" + System.currentTimeMillis(); try { var payment = bootpay.requestSubscribe(payload); if (payment.get("error_code") != null) { // 승인 실패는 예외가 아니라 error_code 로 옵니다 handlePaymentFailure(recurring, payment); return; } // receipt_id 저장, 다음 결제일 갱신 markRecurringPaid(recurring, (String) payment.get("receipt_id")); } catch (Exception e) { handlePaymentFailure(recurring, e); }# billing_key는 billing_keys에서 조인해 가져옵니다 billing_key = find_active_billing_key(recurring[:user_id]) return handle_payment_failure(recurring, nil) if billing_key.nil? response = bootpay.request_subscribe_payment( billing_key: billing_key[:billing_key], price: recurring[:amount], order_name: PLANS[recurring[:plan]][:name], # order_name은 플랜명으로 생성 order_id: "recurring_#{recurring[:user_id]}_#{Time.now.to_i}" ) if response.success? # receipt_id 저장, 다음 결제일 갱신 mark_recurring_paid(recurring, response.data[:receipt_id]) else handle_payment_failure(recurring, response.data) end// billing_key는 billing_keys에서 조인해 가져옵니다 billingKey, err := findActiveBillingKey(recurring.UserID) if err != nil { handlePaymentFailure(recurring, err) return } payment, err := api.RequestSubscribe(bootpay.SubscribePayload{ BillingKey: billingKey.BillingKey, Price: recurring.Amount, OrderName: plans[recurring.Plan].Name, // order_name은 플랜명으로 생성 OrderId: fmt.Sprintf("recurring_%d_%d", recurring.UserID, time.Now().Unix()), }) if err != nil { handlePaymentFailure(recurring, err) return } if errorCode, ok := payment["error_code"].(string); ok { // 승인 실패는 err 가 아니라 error_code 로 옵니다 handlePaymentFailure(recurring, errors.New(errorCode)) return } // receipt_id 저장, 다음 결제일 갱신 receiptID, _ := payment["receipt_id"].(string) markRecurringPaid(recurring, receiptID)// billing_key는 billing_keys에서 조인해 가져옵니다 var billingKey = await FindActiveBillingKey(recurring.UserId); if (billingKey == null) { await HandlePaymentFailure(recurring, null); return; } var paymentResponse = await bootpay.RequestSubscribe(new SubscribePayload { billingKey = billingKey.BillingKey, price = recurring.Amount, orderName = Plans[recurring.Plan].Name, // order_name은 플랜명으로 생성 orderId = $"recurring_{recurring.UserId}_{DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}", }); var paymentJson = await paymentResponse.Content.ReadAsStringAsync(); // 승인 실패는 HTTP 4xx/5xx + { error_code, ... } 본문으로 옵니다. // 성공이면 paymentJson의 receipt_id를 저장하고 다음 결제일을 갱신합니다.스케줄러는 서버 스택의 표준 도구를 사용합니다. Python은
APScheduler나Celery beat, Java는 Spring@Scheduled나Quartz, Ruby는whenever나Sidekiq, Go는robfig/cron, .NET은IHostedService를 사용할 수 있습니다.구독 해지 (백엔드)
JavaScriptapp.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: '구독이 해지되었습니다' }) })상세 문서: 빌링키 삭제
마이페이지 — 구독 조회 (백엔드)
JavaScriptapp.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 }) })