# 예약결제 전체 구현 예제

원문: https://developers.bootpay.ai/api/reserve/example

> 빌링키로 원하는 시점의 결제를 예약하는 매뉴얼

빌링키를 발급·저장하고 원하는 시점의 결제를 예약한 뒤, 실행 결과를 웹훅으로 받아 확정하는 예제입니다. 예약결제 · 예약 상태 · 만료 처리의 개념은 가이드 [예약결제](https://developers.bootpay.ai/docs/reserve)에 있고, API별 파라미터 · 에러는 [결제 예약](https://developers.bootpay.ai/api/reserve/charge) · [예약 조회](https://developers.bootpay.ai/api/reserve/lookup) · [예약 취소](https://developers.bootpay.ai/api/reserve/cancel)에 있습니다.

## 연동 흐름

### 1. 빌링키 발급

:::canvas-sequence
{
  "participants": [
    { "id": "user", "label": "구매자" },
    { "id": "fe", "label": "프론트엔드" },
    { "id": "be", "label": "백엔드" },
    { "id": "bp", "label": "Bootpay/PG" }
  ],
  "messages": [
    { "from": "user", "to": "fe", "label": "A. PG 결제창에 카유생비 입력", "type": "solid" },
    { "from": "fe", "to": "bp", "label": "A. requestSubscription()", "type": "solid" },
    { "from": "bp", "to": "fe", "label": "A. receipt_id 응답", "type": "dashed" },
    { "from": "fe", "to": "be", "label": "A. receipt_id 전달", "type": "solid" },
    { "from": "be", "to": "bp", "label": "A. 빌링키 조회", "type": "solid" },
    { "from": "bp", "to": "be", "label": "A. billing_key 응답", "type": "dashed" },
    { "from": "user", "to": "fe", "label": "B. 가맹점 화면에 카유생비 입력", "type": "solid" },
    { "from": "fe", "to": "be", "label": "B. 카드 정보 전달", "type": "solid" },
    { "from": "be", "to": "bp", "label": "B. REST API로 빌링키 발급 요청", "type": "solid" },
    { "from": "bp", "to": "be", "label": "B. billing_key 응답", "type": "dashed" },
    { "from": "be", "to": "be", "label": "billing_key 저장", "type": "solid" }
  ]
}
:::

### 2. 예약 등록과 실행

:::canvas-sequence
{
  "participants": [
    { "id": "be", "label": "백엔드" },
    { "id": "bp", "label": "Bootpay/PG" },
    { "id": "db", "label": "가맹점 DB" }
  ],
  "messages": [
    { "from": "be", "to": "db", "label": "저장된 billing_key 조회", "type": "solid" },
    { "from": "be", "to": "bp", "label": "예약 결제 등록", "type": "solid" },
    { "from": "bp", "to": "be", "label": "reserve_id 응답", "type": "dashed" },
    { "from": "bp", "to": "bp", "label": "예약 시각에 결제 실행", "type": "solid" },
    { "from": "bp", "to": "be", "label": "웹훅 전송", "type": "dashed" },
    { "from": "be", "to": "db", "label": "예약 상태·receipt_id 저장", "type": "solid" }
  ]
}
:::

빌링키 발급과 예약 등록은 별개의 단계입니다. 먼저 둘 중 한 방식으로 빌링키를 발급·저장하고, 이후 서버에서 저장된 `billing_key`로 예약 결제 API를 호출해야 합니다.

## 구현 순서

:::: steps

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

프론트엔드에서 PG 결제창을 띄워 고객이 카유생비를 입력하면 빌링키가 발급됩니다. 발급이 끝나면 `receipt_id`를 백엔드로 보냅니다. 빌링키 발급은 자동결제와 같아서, iOS · Android · Flutter · React Native 코드와 파라미터는 [빌링키 발급 › 프론트엔드에서 발급하기](https://developers.bootpay.ai/api/billing/key-issue#프론트엔드에서-발급하기)에 있습니다.

```javascript
async 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 · 코드 · 보안 주의는 [백엔드에서 발급하기](https://developers.bootpay.ai/api/billing/key-issue#백엔드에서-발급하기)에 있습니다.

### 빌링키 저장 (백엔드)

`billing_keys` 테이블 스키마는 자동결제와 같습니다([빌링키 발급 › 발급 결과 저장](https://developers.bootpay.ai/api/billing/key-issue#발급-결과-저장)).

아래 코드는 프론트엔드 결제창에서 받은 `receipt_id`로 빌링키를 조회해 저장하는 흐름입니다.

Node.js는 저장 핸들러까지 포함하고, 다른 언어는 빌링키 조회 SDK 호출부만 보여줍니다. 토큰 발급·DB 저장·라우팅은 각 프레임워크 컨벤션에 맞게 연결합니다.

::: code-group sync=backend

```javascript [Node.js]
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 })
})
```

```python [Python]
# 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에 저장
```

```php [PHP]
// Bootpay SDK 호출 (Laravel·Slim 등 컨트롤러 안에서)
$info = BootpayApi::lookupSubscribeBillingKey($receiptId);
// $info->billing_key / $info->billing_data->card_company / $info->billing_data->card_no 를 DB에 저장
```

```java [Java]
// 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에 저장
```

```ruby [Ruby]
# 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에 저장 (응답 키는 심볼)
```

```go [Go]
// 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에 저장
```

```csharp [.NET]
// 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에 저장
```

:::

상세 문서: [빌링키 조회](https://developers.bootpay.ai/api/billing/key-lookup) — 7개 언어 SDK 초기화와 응답 스키마를 확인합니다.

### 예약 결제 등록 (백엔드)

::: warning 등록 전에 확인할 것
- `feedback_url`(또는 관리자 통합 웹훅 URL)이 없으면 예약 등록이 `SR_WEBHOOK_URL_BLANK`로 거절됩니다.
- `reserve_execute_at`은 현재로부터 2개월 이내여야 하고, 빌링키 만료일보다 뒤일 수 없습니다.
- `order_id`는 같은 빌링키 안에서 재사용할 수 없습니다. 취소·완료된 예약의 값도 마찬가지입니다.
:::

::: code-group sync=backend

```javascript [Node.js]
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
    })
})
```

```python [Python]
# 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 테이블에 저장
```

```php [PHP]
// 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 테이블에 저장
```

```java [Java]
// 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 테이블에 저장
```

```ruby [Ruby]
# 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 테이블에 저장
```

```go [Go]
// 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{})
```

```csharp [.NET]
// 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 테이블에 저장
```

:::

상세 문서: [결제 예약](https://developers.bootpay.ai/api/reserve/charge) — 7개 언어 예제와 응답 스키마를 확인합니다.

### 웹훅 수신 — 예약 실행 결과 (백엔드)

예약 시간이 되면 부트페이가 저장된 빌링키로 PG사에 결제를 요청하고, 그 결과를 가맹점 서버로 웹훅으로 보냅니다.

웹훅 본문은 `event`·`data`로 감싸여 오지 않고 **평면 객체**로 옵니다. 성공과 실패는 서로 다른 형태로 오기 때문에, `error_code`가 있는지로 먼저 구분해야 합니다.

```javascript
app.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` 취소)는 [예약 조회](https://developers.bootpay.ai/api/reserve/lookup)로 확인하는 값이라 서로 다른 체계입니다.

::: warning 실패는 웹훅만 믿지 말고 조회로 보완합니다
실행에 실패하면 위처럼 `error_code`가 담긴 웹훅이 오지만, 이 본문에는 `receipt_id`가 없고 매칭 키가 `payload.reserve_id`에 들어 있습니다. 관리자에서 오류 웹훅을 켰는지에 따라 본문을 만드는 주체와 세부 필드도 달라집니다.

실패한 예약은 자동으로 재시도되지 않습니다. 상태가 `-1`로 고정되므로, 실행 예정 시각이 지난 예약을 [예약 조회](https://developers.bootpay.ai/api/reserve/lookup)로 확인해 `status`가 `-1`인 건을 찾아내는 폴링을 함께 둡니다. 재청구가 필요하면 새 `order_id`로 예약을 다시 등록하거나 빌링키 결제를 직접 호출해야 합니다.
:::

상세 문서: [웹훅 처리 가이드](https://developers.bootpay.ai/api/common/webhook-events)

### 예약 취소 (백엔드, 선택)

예약 취소는 **부트페이에 예약된 실행 작업을 삭제하는 것**입니다. 아직 실행되지 않은 예약에만 쓸 수 있고, 이미 결제가 실행된 뒤에는 예약 취소가 아니라 `receipt_id` 기준 [결제 취소](https://developers.bootpay.ai/api/pg/server/cancel)를 호출해야 합니다.

::: code-group sync=backend

```javascript [Node.js]
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 })
})
```

```python [Python]
# Bootpay SDK 호출
response = bootpay.cancel_subscribe_reserve(reserve_id)
```

```php [PHP]
// Bootpay SDK 호출
$response = BootpayApi::cancelSubscribeReserve($reserveId);
```

```java [Java]
// Bootpay SDK 호출
var response = bootpay.reserveCancelSubscribe(reserveId);
```

```ruby [Ruby]
# Bootpay SDK 호출
response = bootpay.cancel_subscribe_reserve(reserve_id).data
```

```go [Go]
// Bootpay SDK 호출
response, err := api.ReserveCancelSubscribe(reserveID)
if err != nil {
    log.Fatal(err)
}
```

```csharp [.NET]
// Bootpay SDK 호출
var response = await bootpay.ReserveCancelSubscribe(reserveId);
```

:::

상세 문서: [예약 취소](https://developers.bootpay.ai/api/reserve/cancel) — 7개 언어 예제와 에러 코드를 확인합니다.

::::

## 함께 보기

- [예약결제](https://developers.bootpay.ai/docs/reserve) — 예약 상태 · 만료 · 해지 순서의 개념
- [예약결제 운영 주의사항](https://developers.bootpay.ai/api/reserve/operations) — 결제수단 변경·빌링키 삭제 순서를 정리하려면
- [자동결제](https://developers.bootpay.ai/api/billing/example) — 매월 자동으로 반복 결제하려면
