빌링키 발급·저장·첫 결제·회차 청구를 구현합니다. 빌링키 저장 설계·조회·삭제·청구 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로 올립니다. 자동 복구는 하지 않고, 카드 변경 의사가 확인된 후에만 결제를 재개합니다.
스케줄러가 매번 풀스캔해야 하므로 회원이 늘면 청구 시각을 놓칠 수 있습니다. (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',
}),
})
}
}javascriptlet payload = Payload()
payload.applicationId = BootpayConfig.applicationId
payload.pg = "nicepay"
payload.method = "카드자동"
payload.subscriptionId = String(Date().timeIntervalSince1970)
payload.price = 0
payload.orderName = "정기결제 카드 등록"
payload.extra = BootExtra()
payload.extra?.subscribeTestPayment = true
Bootpay.requestSubscription(viewController: self, payload: payload)
.onDone { data in
// receipt_id를 백엔드 /api/recurring/register로 전송 (plan 포함)
self.registerRecurring(receiptId: data["receipt_id"] as? String ?? "", plan: "monthly")
}
.onError { _ in }
.onCancel { _ in }swiftval extra = BootExtra().setSubscribeTestPayment(true)
val payload = Payload()
.setApplicationId(BootpayConfig.applicationId)
.setOrderName("정기결제 카드 등록")
.setPg("nicepay")
.setMethod("카드자동")
.setSubscriptionId("sub_${System.currentTimeMillis()}")
.setPrice(0.0)
.setExtra(extra)
Bootpay.init(this).setPayload(payload)
.setEventListener(object : BootpayEventListener {
override fun onDone(data: String) {
// data의 receipt_id + plan을 /api/recurring/register로 전송
registerRecurring(data, "monthly")
}
override fun onError(data: String) {}
override fun onCancel(data: String) {}
override fun onClose() { Bootpay.removePaymentWindow() }
override fun onIssued(data: String) {}
override fun onConfirm(data: String) = true
}).requestSubscription()kotlinfinal payload = Payload()
..webApplicationId = BootpayEnvConfig.webApplicationId
..androidApplicationId = BootpayEnvConfig.androidApplicationId
..iosApplicationId = BootpayEnvConfig.iosApplicationId
..pg = 'nicepay'
..method = '카드자동'
..subscriptionId = DateTime.now().millisecondsSinceEpoch.toString()
..price = 0
..orderName = '정기결제 카드 등록'
..extra = (Extra()..subscribeTestPayment = 1);
Bootpay().requestSubscription(
context: context,
payload: payload,
onDone: (data) {
// receipt_id를 백엔드 /api/recurring/register로 전송 (plan 포함)
registerRecurring(data, 'monthly');
},
onError: (data) => debugPrint('error: $data'),
onCancel: (data) => debugPrint('cancel: $data'),
onClose: () {},
);dartconst payload = {
pg: 'nicepay',
method: '카드자동',
order_name: '정기결제 카드 등록',
subscription_id: `sub_${Date.now()}`,
price: 0,
}
const user = { username: '홍길동', phone: '01012345678' }
const extra = { subscribe_test_payment: true }
bootpay.current?.requestSubscription(payload, [], user, extra)
function onDone(data) {
// receipt_id를 백엔드 /api/recurring/register로 전송 (plan 포함)
registerRecurring(data.receipt_id, 'monthly')
}javascript상세 문서: 빌링키 발급
빌링키 발급 B — REST API로 직접 발급 (백엔드, 선택)
일부 PG는 백엔드 REST API로 빌링키를 직접 발급할 수 있습니다. 이 방식은 가맹점 화면에서 카드 정보를 입력받아 서버로 전달하고, 서버가 Bootpay API에 빌링키 발급을 요청합니다.
나이스페이먼츠, 페이앱, 웰컴페이먼츠, 토스페이먼츠, 키움페이, 라이트페이
카드번호·유효기간·생년월일·비밀번호 앞 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# 1) 빌링키 조회
info = bootpay.lookup_subscribe_billing_key(receipt_id)
# info['billing_key'] / info['billing_data']['card_company'] / info['billing_data']['card_no']를 DB에 저장
# 2) 첫 결제 실행 — 승인 실패는 예외로 올라오므로 try/except로 감쌉니다
try:
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())}',
)
# 성공 → payment['receipt_id'] 저장 후 다음 결제일 등록
except Exception as e:
# error_code == 'RC_CONFIRM_FAILED'이면 PG 승인 거절
handle_first_payment_failure(e)python// 1) 빌링키 조회
$info = BootpayApi::lookupSubscribeBillingKey($receiptId);
// $info['billing_key'] / $info['billing_data']['card_company'] / $info['billing_data']['card_no']를 DB에 저장
// 2) 첫 결제 실행 — 승인 실패는 예외로 올라오므로 try/catch로 감쌉니다
try {
$payment = BootpayApi::requestSubscribePayment([
'billing_key' => $info['billing_key'],
'price' => $planInfo['price'],
'order_name' => $planInfo['name'],
'order_id' => 'recurring_' . $userId . '_' . time(),
]);
// 성공 → $payment['receipt_id'] 저장 후 다음 결제일 등록
} catch (Exception $e) {
// error_code == 'RC_CONFIRM_FAILED'이면 PG 승인 거절
handleFirstPaymentFailure($e);
}php// 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) 첫 결제 실행 — 승인 실패는 예외로 올라오므로 try/catch로 감쌉니다
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);
// 성공 → payment.get("receipt_id") 저장 후 다음 결제일 등록
} catch (Exception e) {
// error_code가 RC_CONFIRM_FAILED이면 PG 승인 거절
handleFirstPaymentFailure(e);
}java# 1) 빌링키 조회
info = bootpay.request(method: :get, uri: "subscribe/billing_key/#{receipt_id}").data
# info['billing_key'] / info['billing_data']['card_company'] / info['billing_data']['card_no']를 DB에 저장
# 2) 첫 결제 실행 — 승인 실패는 예외로 올라오므로 begin/rescue로 감쌉니다
begin
payment = bootpay.request(
uri: 'subscribe/payment',
payload: {
billing_key: info['billing_key'],
price: plan_info[:price],
order_name: plan_info[:name],
order_id: "recurring_#{user_id}_#{Time.now.to_i}"
}
).data
# 성공 → payment['receipt_id'] 저장 후 다음 결제일 등록
rescue => e
# error_code가 RC_CONFIRM_FAILED이면 PG 승인 거절
handle_first_payment_failure(e)
endruby// 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로 돌아옵니다
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 {
// error_code가 RC_CONFIRM_FAILED이면 PG 승인 거절
handleFirstPaymentFailure(err)
return
}
// 성공 → payment["receipt_id"] 저장 후 다음 결제일 등록go// 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를 저장하고 다음 결제일을 등록합니다csharp상세 문서: 빌링키 조회 · 빌링키 결제 요청 — 7개 언어 예제를 확인합니다.
회차 자동 결제 — 스케줄러 (백엔드)
매일 실행되는 스케줄러(cron)로 결제일이 된 건을 처리해야 합니다. 스케줄러·큐·재시도·이메일·일시정지 정책은 각 백엔드 프레임워크의 방식대로 구현하고, 스케줄러 안에서는 저장된 billing_key로 결제 요청 API를 호출해야 합니다.
저장 테이블의 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# billing_key는 billing_keys에서 조인해 가져옵니다
billing_key = find_active_billing_key(recurring['user_id'])
if billing_key is None:
handle_payment_failure(recurring)
return
try:
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())}",
)
# receipt_id 저장, 다음 결제일 갱신
mark_recurring_paid(recurring, payment['receipt_id'])
except Exception as e:
handle_payment_failure(recurring, e)python// 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(),
]);
// receipt_id 저장, 다음 결제일 갱신
markRecurringPaid($recurring, $payment['receipt_id']);
} catch (Exception $e) {
handlePaymentFailure($recurring, $e);
}php// 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);
// receipt_id 저장, 다음 결제일 갱신
markRecurringPaid(recurring, (String) payment.get("receipt_id"));
} catch (Exception e) {
handlePaymentFailure(recurring, e);
}java# billing_key는 billing_keys에서 조인해 가져옵니다
billing_key = find_active_billing_key(recurring[:user_id])
return handle_payment_failure(recurring, nil) if billing_key.nil?
begin
payment = bootpay.request(
uri: 'subscribe/payment',
payload: {
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}"
}
).data
# receipt_id 저장, 다음 결제일 갱신
mark_recurring_paid(recurring, payment['receipt_id'])
rescue => e
handle_payment_failure(recurring, e)
endruby// 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
}
// receipt_id 저장, 다음 결제일 갱신
receiptID, _ := payment["receipt_id"].(string)
markRecurringPaid(recurring, receiptID)go// 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를 저장하고 다음 결제일을 갱신합니다.csharp스케줄러는 서버 스택의 표준 도구를 사용합니다. Python은 APScheduler나 Celery beat, Java는 Spring @Scheduled나 Quartz, Ruby는 whenever나 Sidekiq, Go는 robfig/cron, .NET은 IHostedService를 사용할 수 있습니다.
같은 빌링키로 결제일마다 예약결제를 등록하면 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

