# 분리 승인

원문: https://developers.bootpay.ai/api/pg/window/separately-confirmed

> 인증 완료 후 confirm 이벤트를 받아 서버에서 검증하고 승인하는 결제 연동 방법

`extra.separately_confirmed: true`는 구매자 인증이 끝난 뒤 **결제 승인 직전의 `confirm` 이벤트를 받기 위한 옵션**입니다. 이 시점에 서버가 주문 금액·주문 상태·재고·쿠폰·적립금 같은 조건을 다시 확인하고, 문제가 없을 때만 결제를 승인해야 합니다.

## 동작 방식

인증과 승인을 나누는 개념, 서버 승인과 클라이언트 승인(자동 승인 후 서버 검증)의 차이는 가이드 [결제 흐름 이해하기 › 승인은 서버가 합니다](https://developers.bootpay.ai/docs/start/concepts#서버-승인)에 있습니다. `confirm` 을 받은 서버는 승인 전에 아래 조건을 확인합니다.

- 주문 상태가 아직 결제 대기 상태인지
- 재고를 차감해도 되는지
- 쿠폰·적립금·프로모션 조건이 여전히 유효한지
- 이미 처리한 `receipt_id`가 아닌지

결제 금액은 승인 응답으로 확인합니다. 승인 API(`confirmPayment`)가 돌려준 `price`를 DB 주문 금액과 비교하고, 다르면 승인된 결제를 취소합니다.

승인 호출은 두 가지 방식이 있습니다. 기본은 백엔드가 Bootpay 승인 API를 호출하는 **서버 승인**입니다. 서버 승인 API를 지원하지 않는 PG에서는 서버가 먼저 검증하고 프론트엔드가 `Bootpay.confirm()` 또는 SDK별 승인 함수를 호출하는 [예외 흐름](#예외-프론트엔드-승인)을 사용합니다.

::: warning 분리 승인을 지원하지 않는 PG
페이앱·페이레터·키움페이는 현재 분리 승인을 기술적으로 지원하지 않습니다. 이런 PG를 쓸 때는 `separately_confirmed: false`로 두고 [결제 조회 API](https://developers.bootpay.ai/api/pg/server/verify)로 승인 결과를 한 번 더 조회해 확정하고, 검증에서 문제가 있으면 [결제 취소 API](https://developers.bootpay.ai/api/pg/server/cancel)로 즉시 환불합니다.
:::

## 분리 승인 흐름

분리 승인에서는 프론트엔드가 `done` 대신 `confirm` 을 받고, 백엔드가 승인 API 를 호출할 때 승인됩니다.

:::canvas-sequence
{
  "participants": [
    { "id": "user", "label": "구매자" },
    { "id": "fe", "label": "프론트엔드" },
    { "id": "be", "label": "백엔드" },
    { "id": "bp", "label": "Bootpay/PG" }
  ],
  "messages": [
    { "from": "user", "to": "fe", "label": "결제 버튼 클릭", "type": "solid" },
    { "from": "fe", "to": "bp", "label": "requestPayment(separately_confirmed)", "type": "solid" },
    { "from": "user", "to": "bp", "label": "카드 인증·본인 인증", "type": "solid" },
    { "from": "bp", "to": "fe", "label": "confirm (인증 완료, 승인 직전)", "type": "dashed" },
    { "from": "fe", "to": "be", "label": "receipt_id 전달", "type": "solid" },
    { "from": "be", "to": "be", "label": "주문 금액·상태·재고 검증", "type": "solid" },
    { "from": "be", "to": "bp", "label": "승인 API 호출", "type": "solid" },
    { "from": "bp", "to": "be", "label": "승인 결과 응답", "type": "dashed" },
    { "from": "be", "to": "be", "label": "주문 확정", "type": "solid" },
    { "from": "fe", "to": "be", "label": "결과 페이지에서 주문 상태 조회", "type": "solid" }
  ]
}
:::

분리 승인에서는 `confirm`이 결제 완료가 아닙니다. 서버가 승인 API를 호출하고 주문을 확정한 뒤에야 결제 완료로 봐야 합니다. 클라이언트와 웹훅이 둘 다 도착할 수 있으므로 `receipt_id` 기준으로 멱등 처리해야 합니다.

::: selector id=confirm-mode label="승인" prompt="누가 승인 API 를 부를지 고르세요" rail
- server: 서버 승인
- client: 프론트엔드 승인 (예외)
:::

:::: when confirm-mode=server

## 서버 승인

::: warning 통신 결과가 불명확할 때
승인 요청이 타임아웃되거나 네트워크 오류로 응답을 받지 못해도 즉시 다시 승인하거나 실패로 확정하면 안 됩니다. `confirm` 에서 받아 보관한 `receipt_id` 로 결제를 먼저 조회하고(결제 조회는 `receipt_id` 로만 합니다), 진행 중이면 웹훅과 재조회로 최종 상태를 확인합니다. Node SDK의 기본 HTTP timeout은 60초이며, 모든 SDK에 공통인 제한은 아닙니다.
:::

백엔드에서 Bootpay 승인 API를 호출해 결제를 확정하는 패턴입니다. 재고·적립금·쿠폰 차감을 결제 승인과 같은 트랜잭션에 묶을 때 씁니다.

::: steps

### confirm 이벤트 수신 및 서버 전달

**(프론트엔드)** 인증 완료 후 `confirm`을 받으면 `receipt_id`와 `order_id`를 서버로 전달합니다. 이 단계는 결제 완료가 아닙니다.

### 서버 검증

**(서버)** DB에 저장된 주문 금액·주문 상태·재고·쿠폰·적립금 조건을 확인합니다. 승인해도 되는 주문인지 먼저 판단해야 합니다.

### 서버 승인 수행

**(서버)** 검증을 통과한 경우에만 Bootpay 승인 API를 호출하고, 승인 결과를 DB에 반영합니다.

### 결제 결과 표시

**(프론트엔드)** 서버 승인 방식에서는 클라이언트의 `done`이 호출되지 않습니다. 결과 페이지에서 서버 DB의 주문 상태를 조회해 결제 결과를 표시합니다.

:::

::: tip 서버 승인만 허용하려면 `extra.confirm_only_rest_api`
결제 요청 시 `extra.confirm_only_rest_api: true`를 함께 보내면 REST API(Secret Key) 로 요청한 승인만 허용됩니다. 클라이언트 키로 승인을 시도하면 `RC_CONFIRM_ONLY_REST_API` 오류로 거절됩니다. 기본값은 `false`입니다.
:::

### 코드 예시

아래 예제는 승인 상태 `1`(결제완료)과 `5`(가상계좌 발급·입금 대기)를 모두 성공 경로로 처리합니다. 승인된 금액이 내부 주문 금액과 다르면 승인된 금액을 취소하고, 취소 요청도 실패하면 주문을 `cancel_confirmation_required` 같은 확인 필요 상태로 저장합니다.


```javascript
const orderId = 'order_' + Date.now()

try {
    const response = await Bootpay.requestPayment({
        client_key: '[ Client Key ]',
        price: 50000,
        order_name: '나이키 운동화 외 2건',
        order_id: orderId,
        // SDK 5.x 기본값은 redirect 라 confirm 을 이 코드에서 받으려면 iframe · popup 으로 엽니다
        extra: { separately_confirmed: true, open_type: 'iframe' }
    })

    if (response.event === 'confirm') {
        // confirm = 인증 완료, 승인 직전 상태입니다.
        // 서버가 주문 금액·상태·재고를 확인하고 승인 API를 호출해야 합니다.
        await requestBackendServerConfirm(response)
        location.href = `/orders/${response.order_id}/result`
    }
} catch (e) {
    if (e.event === 'cancel') keepOrderUnpaid(e)
    if (e.event === 'error') showPaymentError(e.message)
}

const requestBackendServerConfirm = async (response) => {
    const { receipt_id, order_id } = response
    return axios.post('/api/confirm', { receipt_id, order_id })
}
```

프론트엔드에서 `receipt_id`를 서버로 전송하면, 서버가 주문 조건을 검증하고 Bootpay 승인 API를 호출합니다. 서버는 승인 API를 호출하기 전에 DB에 저장해 둔 주문 금액·주문 상태·재고 조건을 먼저 확인해야 합니다.

::: code-group sync=backend

```javascript [Node.js]
app.post('/api/confirm', async (req, res) => {
    const { receipt_id, order_id } = req.body
    const order = await db.orders.findByPk(order_id)

    if (!order || order.status !== 'pending') {
        return res.status(400).json({ message: '승인할 수 없는 주문' })
    }

    if (!checkInventory(order)) {
        return res.status(400).json({ message: '재고가 부족합니다.' })
    }

    const confirmed = await Bootpay.confirmPayment(receipt_id)
    if ((confirmed.status !== 1 && confirmed.status !== 5) || confirmed.price !== order.price) {
        if (confirmed.status === 1 || confirmed.status === 5) {
            try { await Bootpay.cancelPayment({ receipt_id: receipt_id, cancel_price: confirmed.price, cancel_id: `${order_id}-amount-mismatch` }) }
            catch (cancelError) { await db.orders.update({ status: 'cancel_confirmation_required' }, { where: { id: order_id } }) }
        }
        return res.status(400).json({ message: '결제 승인 결과를 확인할 수 없습니다.' })
    }

    if (confirmed.status === 5) {
        await db.orders.update({ status: 'pending_deposit', bootpay_receipt_id: receipt_id }, { where: { id: order_id } })
        return res.json({ success: true, status: 5 })
    }

    await db.orders.update(
        { status: 'done', bootpay_receipt_id: receipt_id },
        { where: { id: order_id } }
    )

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

```python [Python]
@app.post('/api/confirm')
def confirm_payment():
    data = request.get_json()
    receipt_id = data['receipt_id']
    order_id = data['order_id']
    order = Order.get(order_id)

    if not order or order.status != 'pending':
        return jsonify({'message': '승인할 수 없는 주문'}), 400

    if not check_inventory(order):
        return jsonify({'message': '재고가 부족합니다.'}), 400

    # Python SDK 는 API 오류에 예외를 던지지 않고 { error_code, message } dict 를 돌려준다
    confirmed = bootpay.confirm_payment(receipt_id)
    if (confirmed.get('status') not in (1, 5)) or confirmed.get('price') != order.price:
        if confirmed.get('status') in (1, 5):
            cancelled = bootpay.cancel_payment(receipt_id, cancel_price=confirmed['price'], cancel_id=f"{order_id}-amount-mismatch")
            if 'error_code' in cancelled:
                Order.update(order_id, status='cancel_confirmation_required')
        return jsonify({'message': '결제 승인 결과를 확인할 수 없습니다.'}), 400
    if confirmed['status'] == 5:
        Order.update(order_id, status='pending_deposit', bootpay_receipt_id=receipt_id)
        return jsonify({'success': True, 'status': 5})

    order.update(status='done', bootpay_receipt_id=receipt_id)
    return jsonify({'success': True})
```

```php [PHP]
$data = json_decode(file_get_contents('php://input'), true);
$receiptId = $data['receipt_id'];
$orderId = $data['order_id'];
$order = Order::find($orderId);

if (!$order || $order->status !== 'pending') {
    http_response_code(400);
    echo json_encode(['message' => '승인할 수 없는 주문']);
    exit;
}

if (!checkInventory($order)) {
    http_response_code(400);
    echo json_encode(['message' => '재고가 부족합니다.']);
    exit;
}

// 응답은 json_decode 객체이고, 승인 실패도 예외가 아니라 error_code가 든 객체로 옵니다
$confirmed = BootpayApi::confirmPayment($receiptId);
$status = $confirmed->status ?? null;
if (($status !== 1 && $status !== 5) || $confirmed->price !== $order->price) {
    if ($status === 1 || $status === 5) {
        try {
            $cancelled = BootpayApi::cancelPayment(['receipt_id' => $receiptId, 'cancel_price' => $confirmed->price, 'cancel_id' => $orderId . '-amount-mismatch']);
            if (isset($cancelled->error_code)) $order->update(['status' => 'cancel_confirmation_required']);
        } catch (Throwable $e) { $order->update(['status' => 'cancel_confirmation_required']); }
    }
    http_response_code(400);
    echo json_encode(['message' => '결제 승인 결과를 확인할 수 없습니다.']);
    exit;
}
if ($status === 5) {
    $order->update(['status' => 'pending_deposit', 'bootpay_receipt_id' => $receiptId]);
    echo json_encode(['success' => true, 'status' => 5]);
    exit;
}

$order->update([
    'status' => 'done',
    'bootpay_receipt_id' => $receiptId,
]);

echo json_encode(['success' => true]);
```

```java [Java]
@PostMapping("/api/confirm")
public ResponseEntity<?> confirmPayment(@RequestBody ConfirmRequest body) throws Exception {
    var order = orderRepository.findById(body.orderId());
    if (order.isEmpty() || !"pending".equals(order.get().getStatus())) {
        return ResponseEntity.badRequest().body(Map.of("message", "승인할 수 없는 주문"));
    }

    if (!checkInventory(order.get())) {
        return ResponseEntity.badRequest().body(Map.of("message", "재고가 부족합니다."));
    }

    // Java SDK 는 승인 실패를 예외로 올리지 않고 error_code 가 담긴 응답으로 돌려줍니다 — 그 응답에는 status·price 가 없습니다
    var confirmed = bootpay.confirm(body.receiptId());
    Number statusValue = (Number) confirmed.get("status");
    Number priceValue = (Number) confirmed.get("price");
    int status = statusValue == null ? 0 : statusValue.intValue();
    double price = priceValue == null ? 0 : priceValue.doubleValue();

    if ((status != 1 && status != 5) || price != order.get().getPrice()) {
        if (status == 1 || status == 5) { boolean cancelled; try { Cancel cancel = new Cancel(); cancel.receiptId = body.receiptId(); cancel.cancelPrice = price; cancel.cancelId = body.orderId() + "-amount-mismatch"; cancelled = bootpay.receiptCancel(cancel).get("error_code") == null; } catch (Exception e) { cancelled = false; } if (!cancelled) { order.get().setStatus("cancel_confirmation_required"); orderRepository.save(order.get()); } }
        return ResponseEntity.badRequest().body(Map.of("message", "결제 승인 결과를 확인할 수 없습니다."));
    }
    if (status == 5) { order.get().setStatus("pending_deposit"); order.get().setBootpayReceiptId(body.receiptId()); orderRepository.save(order.get()); return ResponseEntity.ok(Map.of("success", true, "status", 5)); }

    order.get().setStatus("done");
    order.get().setBootpayReceiptId(body.receiptId());
    orderRepository.save(order.get());

    return ResponseEntity.ok(Map.of("success", true));
}
```

```ruby [Ruby]
post '/api/confirm' do
  payload = JSON.parse(request.body.read)
  receipt_id = payload['receipt_id']
  order = Order.find(payload['order_id'])

  halt 400, { message: '승인할 수 없는 주문' }.to_json unless order&.status == 'pending'
  halt 400, { message: '재고가 부족합니다.' }.to_json unless check_inventory(order)

  confirmed = bootpay.confirm_payment(receipt_id).data  # 응답 키는 심볼
  if ![1, 5].include?(confirmed[:status]) || confirmed[:price] != order.price
    if [1, 5].include?(confirmed[:status])
      cancelled = bootpay.cancel_payment(receipt_id: receipt_id, cancel_price: confirmed[:price], cancel_id: "#{payload['order_id']}-amount-mismatch")
      order.update(status: 'cancel_confirmation_required') unless cancelled.success?
    end
    halt 400, { message: '결제 승인 결과를 확인할 수 없습니다.' }.to_json
  end
  if confirmed[:status] == 5
    order.update(status: 'pending_deposit', bootpay_receipt_id: receipt_id)
    return({ success: true, status: 5 }.to_json)
  end

  order.update(status: 'done', bootpay_receipt_id: receipt_id)
  { success: true }.to_json
end
```

```go [Go]
func confirmPayment(w http.ResponseWriter, r *http.Request) {
	var body struct {
		ReceiptID string `json:"receipt_id"`
		OrderID   string `json:"order_id"`
	}
	json.NewDecoder(r.Body).Decode(&body)

	order, err := findOrder(body.OrderID)
	if err != nil || order.Status != "pending" {
		http.Error(w, "승인할 수 없는 주문", http.StatusBadRequest)
		return
	}

	if !checkInventory(order) {
		http.Error(w, "재고가 부족합니다.", http.StatusBadRequest)
		return
	}

	confirmed, err := api.ServerConfirm(body.ReceiptID)
	if err != nil {
		http.Error(w, "결제 조회에 실패했습니다.", http.StatusBadRequest)
		return
	}

	// 승인 실패는 err 가 아니라 error_code 가 담긴 응답으로 옵니다 — 그 응답에는 status·price 가 없어 comma-ok 로 읽습니다
	statusF, _ := confirmed["status"].(float64)
	status := int(statusF)
	price, _ := confirmed["price"].(float64)
	if (status != 1 && status != 5) || price != order.Price {
		if status == 1 || status == 5 { if res, err := api.ReceiptCancel(bootpay.CancelData{ReceiptId: body.ReceiptID, CancelPrice: price, CancelId: body.OrderID + "-amount-mismatch"}); err != nil || res["error_code"] != nil { markOrderCancelConfirmationRequired(body.OrderID) } }
		http.Error(w, "결제 승인 결과를 확인할 수 없습니다.", http.StatusBadRequest)
		return
	}
	if status == 5 { markOrderPendingDeposit(body.OrderID, body.ReceiptID); json.NewEncoder(w).Encode(map[string]interface{}{"success": true, "status": 5}); return }

	markOrderDone(body.OrderID, body.ReceiptID)
	json.NewEncoder(w).Encode(map[string]bool{"success": true})
}
```

```csharp [.NET]
[HttpPost("/api/confirm")]
public async Task<IActionResult> ConfirmPayment([FromBody] ConfirmRequest body)
{
    var order = await orderRepository.FindAsync(body.OrderId);
    if (order == null || order.Status != "pending") {
        return BadRequest(new { Message = "승인할 수 없는 주문" });
    }

    if (!CheckInventory(order)) {
        return BadRequest(new { Message = "재고가 부족합니다." });
    }

    var response = await bootpay.Confirm(body.ReceiptId);
    var confirmed = JsonConvert.DeserializeObject<Dictionary<string, object>>(
        await response.Content.ReadAsStringAsync()
    );

    // 승인 실패는 예외가 아니라 4xx 응답 + error_code 본문으로 옵니다 — 그 본문에는 status·price 가 없습니다
    var confirmedStatus = confirmed.TryGetValue("status", out var s) ? Convert.ToInt32(s) : 0;
    var confirmedPrice = confirmed.TryGetValue("price", out var p) ? Convert.ToDecimal(p) : 0m;
    if ((confirmedStatus != 1 && confirmedStatus != 5) || confirmedPrice != order.Price) {
        if (confirmedStatus == 1 || confirmedStatus == 5) { bool cancelled; try { var cancelResponse = await bootpay.ReceiptCancel(new Cancel { receiptId = body.ReceiptId, cancelPrice = (double) confirmedPrice, cancelId = body.OrderId + "-amount-mismatch" }); cancelled = cancelResponse.IsSuccessStatusCode; } catch { cancelled = false; } if (!cancelled) { order.Status = "cancel_confirmation_required"; await orderRepository.SaveAsync(order); } }
        return BadRequest(new { Message = "결제 승인 결과를 확인할 수 없습니다." });
    }
    if (confirmedStatus == 5) { order.Status = "pending_deposit"; order.BootpayReceiptId = body.ReceiptId; await orderRepository.SaveAsync(order); return Ok(new { Success = true, Status = 5 }); }

    order.Status = "done";
    order.BootpayReceiptId = body.ReceiptId;
    await orderRepository.SaveAsync(order);

    return Ok(new { Success = true });
}
```

:::

::: warning 승인 응답의 금액이 다르면 취소합니다
`confirmPayment`가 응답을 돌려준 시점에는 PG 승인이 이미 끝났으므로, 금액이 다르면 400을 돌려주는 것으로 끝내지 말고 위 코드처럼 [결제 취소 API](https://developers.bootpay.ai/api/pg/server/cancel)로 승인된 금액을 취소해야 합니다. 취소하지 않으면 구매자 결제수단에서 돈이 빠져나간 채 주문만 미결제로 남습니다.

가상계좌는 승인 응답의 `status`가 `5`(발급 완료)입니다. `status !== 1`로 걸러 내지 말고 주문을 입금 대기로 저장한 뒤 입금 웹훅에서 확정합니다.
:::

### 승인 API 응답 예시

아래 JSON은 가맹점의 `/api/confirm` 응답이 아니라, 서버 SDK의 `confirmPayment(receipt_id)`가 반환하는 Bootpay 승인 결과입니다. 승인 직후 이 값의 `status`, `price`, `order_id`를 내부 주문과 비교하고 결제수단 상세 정보가 필요하면 `card_data` 같은 객체를 저장합니다.

```json
{
  "receipt_id": "6244f60c1fc19202e42e8c4e",
  "order_id": "order_20260428_001",
  "price": 50000,
  "tax_free": 0,
  "cancelled_price": 0,
  "cancelled_tax_free": 0,
  "order_name": "나이키 운동화 외 2건",
  "company_name": "부트페이",
  "gateway_url": "https://gw.bootpay.co.kr",
  "metadata": {
    "order_source": "web"
  },
  "sandbox": true,
  "pg": "kcp",
  "method": "카드",
  "method_symbol": "card",
  "method_origin": "카드",
  "method_origin_symbol": "card",
  "currency": "KRW",
  "status": 1,
  "status_locale": "결제완료",
  "receipt_url": "https://receipt.bootpay.co.kr/receipt/6244f60c1fc19202e42e8c4e",
  "purchased_at": "2026-04-28T09:30:29+09:00",
  "requested_at": "2026-04-28T09:30:04+09:00",
  "card_data": {
    "tid": "20260428123456789012",
    "card_approve_no": "12345678",
    "card_no": "1234-****-****-5678",
    "card_quota": "00",
    "card_company_code": "08",
    "card_company": "하나카드",
    "card_interest": "0",
    "receipt_url": "https://receipt.pg.example/card/20260428123456789012"
  }
}
```

| 필드 | 승인 후 확인할 내용 |
| --- | --- |
| `status` | `1`이면 승인 완료, `5`이면 가상계좌 발급 후 입금 대기입니다 |
| `price` | 내부 주문의 최종 결제 금액과 일치해야 합니다 |
| `order_id` | 승인 요청을 시작한 내부 주문번호와 일치해야 합니다 |
| `receipt_id` | 주문에 저장하고 중복 승인·웹훅 멱등 처리 키로 사용합니다 |
| `method_origin` | 구매자가 **처음 선택한 상위 결제수단**입니다 (예: 카카오페이). 반면 `method`는 그 안에서 **실제 승인된 결제수단**입니다 (예: 카드) |
| `card_data.card_approve_no` | 카드 승인번호입니다 |
| `card_data.card_company` | 카드사명입니다 |
| `card_data.card_no` | PG 정책에 따라 마스킹된 카드번호입니다 |

카드가 아닌 결제수단은 `card_data` 대신 `bank_data`, `vbank_data`, `phone_data` 등이 내려올 수 있습니다. 각 객체의 상세 구조는 [결제 조회의 결제수단별 상세 객체](https://developers.bootpay.ai/api/pg/server/verify#payment-method-details)를 참고합니다.

::: warning PG별 응답 차이
결제수단 상세 객체 안의 일부 필드는 PG사에 따라 생략될 수 있습니다. 카드번호를 포함한 민감값은 마스킹된 응답만 저장하고, 전체 카드번호 복원을 전제로 처리하면 안 됩니다.
:::

::::

:::: when confirm-mode=client

## 예외: 프론트엔드 승인

프론트엔드 승인 방식은 `confirm`을 받은 뒤 클라이언트에서 `Bootpay.confirm()`을 호출해 최종 승인하는 패턴입니다. 서버 승인 API를 지원하지 않는 PG에서 사용하는 예외 흐름입니다.

**클라이언트가 `confirm`을 받자마자 `Bootpay.confirm()`을 호출하면 안 됩니다.** 먼저 서버에 `receipt_id`와 `order_id`를 보내 주문 금액·상태·재고를 검증하고, 서버가 승인 가능하다고 응답한 경우에만 클라이언트에서 `Bootpay.confirm()`을 호출해야 합니다.

::: steps

### confirm 이벤트 수신

**(프론트엔드)** 인증 결과로 `confirm`을 받습니다. 아직 결제 완료가 아니라 승인 직전 상태입니다.

### 서버 사전 검증

**(서버)** DB에 저장된 주문 금액·주문 상태·재고 조건을 확인하고 승인 가능 여부만 응답합니다. 이 단계에서는 Bootpay 승인 API를 호출하면 안 됩니다.

### 클라이언트 승인 요청

**(프론트엔드)** 서버가 승인 가능하다고 응답한 경우에만 `Bootpay.confirm()`을 호출해 결제 승인을 요청합니다.

### 서버 결제 조회

**(서버)** `Bootpay.confirm()` 이후에도 클라이언트 응답만으로 주문을 확정하면 안 됩니다. 서버에서 `receipt_id`로 결제 정보를 다시 조회하고, DB 주문 금액·상태와 비교한 뒤 주문을 확정해야 합니다.

:::

::: tip 웹훅은 클라이언트 승인 흐름에서 특히 중요합니다
웹훅은 `confirm` 단계에서 오는 이벤트가 아닙니다. `Bootpay.confirm()` 또는 SDK별 승인 함수로 결제가 완료된 뒤, Bootpay가 최종 결제 결과를 가맹점 백엔드로 전달할 때 사용합니다. 구매자가 승인 직후 브라우저나 앱을 닫으면 `/api/payment/complete` 요청이 누락될 수 있으므로, 클라이언트 승인 흐름에서는 웹훅도 함께 운영하고 `receipt_id` 기준으로 멱등 처리해야 합니다.
:::

### 코드 예시

::: code-group sync=client-confirm

```javascript [Client]
import { Bootpay } from '@bootpay/client-js'

try {
    const orderId = 'order_' + Date.now()

    const response = await Bootpay.requestPayment({
        client_key: '[ Client Key ]',
        price: 50000,
        order_name: '나이키 운동화 외 2건',
        order_id: orderId,
        pg: 'nicepay',
        method: 'card',
        extra: {
            separately_confirmed: true,
            open_type: 'popup'
        }
    })

    if (response.event === 'confirm') {
        // 1. 인증 완료 후 confirm을 받습니다. 아직 결제 승인 전입니다.
        const checked = await fetch('/api/payment/confirm-check', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                receipt_id: response.receipt_id,
                order_id: orderId
            })
        }).then((res) => res.json())

        if (!checked.can_confirm) {
            throw new Error(checked.message || '승인할 수 없는 주문입니다.')
        }

        // 2. 서버가 승인 가능하다고 응답한 경우에만 클라이언트에서 결제 승인 요청을 합니다.
        const confirmed = await Bootpay.confirm()

        if (confirmed.event === 'done') {
            // 3. 승인 완료 후에도 클라이언트 응답만으로 주문을 확정하면 안 됩니다.
            // 서버에서 receipt_id로 결제 상태·금액을 다시 조회하고 주문을 확정해야 합니다.
            await fetch('/api/payment/complete', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    receipt_id: confirmed.data.receipt_id, // done 은 data 아래에 옵니다
                    order_id: orderId
                })
            })
        }
    }
} catch (data) {
    if (data.event === 'cancel') keepOrderUnpaid(data)
    if (data.event === 'error') showPaymentError(data.message)
}
```

```javascript [Server · check only]
app.post('/api/payment/confirm-check', async (req, res) => {
    const { receipt_id, order_id } = req.body

    const order = await db.orders.findById(order_id)
    if (!order || order.status !== 'pending') {
        return res.json({ can_confirm: false, message: '승인할 수 없는 주문' })
    }

    if (!checkInventory(order)) {
        return res.json({ can_confirm: false, message: '재고가 부족합니다.' })
    }

    // 서버 승인 API를 호출하지 않습니다.
    // 여기서는 DB에 저장해 둔 주문 금액·상태·재고 기준으로 승인 가능 여부만 판단합니다.
    await db.paymentAttempts.create({
        order_id,
        bootpay_receipt_id: receipt_id,
        status: 'CONFIRM_CHECKED'
    })

    return res.json({ can_confirm: true })
})

app.post('/api/payment/complete', async (req, res) => {
    const { receipt_id, order_id } = req.body

    // Bootpay.confirm() 이후에도 클라이언트 응답만으로 주문을 확정하면 안 됩니다.
    // 서버에서 receipt_id로 결제 정보를 다시 조회하고 DB 주문 금액·상태와 비교해야 합니다.
    const payment = await verifyPayment(receipt_id)
    const order = await db.orders.findById(order_id)

    if (!order || payment.status !== 1 || payment.price !== order.price) {
        return res.status(400).json({ message: '결제 조회에 실패했습니다.' })
    }

    await db.orders.update(
        { status: 'done', bootpay_receipt_id: receipt_id },
        { where: { id: order_id } }
    )

    return res.json({ success: true })
})
```

:::

::::

## 설정 방법

결제 요청 시 `extra.separately_confirmed`를 `true`로 설정합니다. 이 옵션을 켜면 인증 완료 후 `confirm` 이벤트를 받을 수 있습니다.

```javascript
const response = await Bootpay.requestPayment({
    client_key: "[ Client Key ]",
    price: 1000,
    order_name: "테스트 상품",
    order_id: "test_order_001",
    extra: {
        separately_confirmed: true  // 인증 완료 후 confirm 이벤트 수신
    }
})
```
