예약결제 전체 구현 예제
빌링키를 발급·저장하고 원하는 시점의 결제를 예약한 뒤, 실행 결과를 웹훅으로 받아 확정하는 예제입니다. 예약결제 · 예약 상태 · 만료 처리의 개념은 가이드 예약결제에 있고, API별 파라미터 · 에러는 결제 예약 · 예약 조회 · 예약 취소에 있습니다.
연동 흐름
1. 빌링키 발급
2. 예약 등록과 실행
빌링키 발급과 예약 등록은 별개의 단계입니다. 먼저 둘 중 한 방식으로 빌링키를 발급·저장하고, 이후 서버에서 저장된 billing_key로 예약 결제 API를 호출해야 합니다.
구현 순서
빌링키 발급 (프론트엔드)
프론트엔드에서 PG 결제창을 띄워 고객이 카유생비를 입력하면 빌링키가 발급됩니다. 발급이 끝나면
receipt_id를 백엔드로 보냅니다. 빌링키 발급은 자동결제와 같아서, iOS · Android · Flutter · React Native 코드와 파라미터는 빌링키 발급 › 프론트엔드에서 발급하기에 있습니다.JavaScriptasync 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 · 코드 · 보안 주의는 백엔드에서 발급하기에 있습니다.빌링키 저장 (백엔드)
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 }) })# Bootpay SDK 호출 (Flask·Django 등 핸들러 안에서) info = bootpay.lookup_subscribe_billing_key(receipt_id) # info['billing_key'] / info['billing_data']['card_company'] / info['billing_data']['card_no']를 DB에 저장// Bootpay SDK 호출 (Laravel·Slim 등 컨트롤러 안에서) $info = BootpayApi::lookupSubscribeBillingKey($receiptId); // $info->billing_key / $info->billing_data->card_company / $info->billing_data->card_no 를 DB에 저장// Bootpay SDK 호출 (Spring 컨트롤러 안에서) 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에 저장# Bootpay SDK 호출 (Rails 컨트롤러 안에서) info = bootpay.lookup_subscribe_billing_key(receipt_id).data # info[:billing_key] / info[:billing_data][:card_company] / info[:billing_data][:card_no]를 DB에 저장 (응답 키는 심볼)// Bootpay SDK 호출 (net/http·Gin 핸들러 안에서) info, err := api.LookupBillingKey(receiptID) if err != nil { log.Fatal(err) } billingData, _ := info["billing_data"].(map[string]interface{}) // info["billing_key"] / billingData["card_company"] / billingData["card_no"]를 DB에 저장// Bootpay SDK 호출 (ASP.NET Core 컨트롤러 안에서) var infoResponse = await bootpay.LookupBillingKey(receiptId); var infoJson = await infoResponse.Content.ReadAsStringAsync(); // infoJson에서 billing_key / billing_data.card_company / billing_data.card_no를 추출해 DB에 저장상세 문서: 빌링키 조회 — 7개 언어 SDK 초기화와 응답 스키마를 확인합니다.
예약 결제 등록 (백엔드)
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 }) })# Bootpay SDK 호출 (Flask·Django 핸들러 안에서) result = bootpay.subscribe_payment_reserve( billing_key=billing_key, price=amount, order_name=description, order_id=f'reserve_{int(time.time())}', reserve_execute_at=execute_at, ) # result['reserve_id']를 reserve_payments 테이블에 저장// Bootpay SDK 호출 (Laravel·Slim 컨트롤러 안에서) $result = BootpayApi::subscribePaymentReserve([ 'billing_key' => $billingKey, 'price' => $amount, 'order_name' => $description, 'order_id' => 'reserve_' . time(), 'reserve_execute_at' => $executeAt, ]); // $result->reserve_id 를 reserve_payments 테이블에 저장// Bootpay SDK 호출 (Spring 컨트롤러 안에서) SubscribePayload payload = new SubscribePayload(); payload.billingKey = billingKey; payload.price = amount; payload.orderName = description; payload.orderId = "reserve_" + System.currentTimeMillis(); payload.reserveExecuteAt = executeAt; var result = bootpay.reserveSubscribe(payload); // result.get("reserve_id")를 reserve_payments 테이블에 저장# Bootpay SDK 호출 (Rails 컨트롤러 안에서) result = bootpay.subscribe_payment_reserve( billing_key: billing_key, price: amount, order_name: description, order_id: "reserve_#{Time.now.to_i}", reserve_execute_at: execute_at ).data # result[:reserve_id]를 reserve_payments 테이블에 저장// Bootpay SDK 호출 (net/http·Gin 핸들러 안에서) result, err := api.ReserveSubscribe(bootpay.SubscribePayload{ BillingKey: billingKey, Price: amount, OrderName: description, OrderId: fmt.Sprintf("reserve_%d", time.Now().Unix()), ReserveExecuteAt: executeAt, }) if err != nil { log.Fatal(err) } // result["reserve_id"]를 reserve_payments 테이블에 저장 (result 는 map[string]interface{})// Bootpay SDK 호출 (ASP.NET Core 컨트롤러 안에서) var result = await bootpay.ReserveSubscribe(new SubscribePayload { billingKey = billingKey, price = amount, orderName = description, orderId = $"reserve_{DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}", reserveExecuteAt = executeAt, }); // result 는 HttpResponseMessage 입니다 — await result.Content.ReadAsStringAsync() 본문의 reserve_id 를 reserve_payments 테이블에 저장상세 문서: 결제 예약 — 7개 언어 예제와 응답 스키마를 확인합니다.
웹훅 수신 — 예약 실행 결과 (백엔드)
예약 시간이 되면 부트페이가 저장된 빌링키로 PG사에 결제를 요청하고, 그 결과를 가맹점 서버로 웹훅으로 보냅니다.
웹훅 본문은
event·data로 감싸여 오지 않고 평면 객체로 옵니다. 성공과 실패는 서로 다른 형태로 오기 때문에,error_code가 있는지로 먼저 구분해야 합니다.JavaScriptapp.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취소)는 예약 조회로 확인하는 값이라 서로 다른 체계입니다.상세 문서: 웹훅 처리 가이드
예약 취소 (백엔드, 선택)
예약 취소는 부트페이에 예약된 실행 작업을 삭제하는 것입니다. 아직 실행되지 않은 예약에만 쓸 수 있고, 이미 결제가 실행된 뒤에는 예약 취소가 아니라
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 }) })# Bootpay SDK 호출 response = bootpay.cancel_subscribe_reserve(reserve_id)// Bootpay SDK 호출 $response = BootpayApi::cancelSubscribeReserve($reserveId);// Bootpay SDK 호출 var response = bootpay.reserveCancelSubscribe(reserveId);# Bootpay SDK 호출 response = bootpay.cancel_subscribe_reserve(reserve_id).data// Bootpay SDK 호출 response, err := api.ReserveCancelSubscribe(reserveID) if err != nil { log.Fatal(err) }// Bootpay SDK 호출 var response = await bootpay.ReserveCancelSubscribe(reserveId);상세 문서: 예약 취소 — 7개 언어 예제와 에러 코드를 확인합니다.