# 결제 흐름

원문: https://developers.bootpay.ai/api/reference/payment-flow

> 결제 전체 흐름 설계 가이드 — 결제 요청부터 검증, 웹훅까지

결제 요청부터 승인, 검증, 웹훅 처리까지 전체 시퀀스를 정리합니다. 개별 API 사용법은 [결제 요청](https://developers.bootpay.ai/api/pg/window/integration#2-결제-요청), [결제 결과 수신](https://developers.bootpay.ai/api/pg/window/integration#5-결제-결과-수신), [결제 조회](https://developers.bootpay.ai/api/pg/server/verify)에서 확인합니다.

인증과 승인의 구분, 승인 전 상태(4 → 2 → 1), 서버 승인과 클라이언트 승인의 차이는 가이드 [결제 흐름 이해하기](https://developers.bootpay.ai/docs/start/concepts#인증과-승인)에 있습니다. 이 페이지는 두 승인 방식의 단계별 순서와 코드를 다룹니다.

::: selector id=approve-mode label="승인 방식" prompt="어떤 방식으로 승인할지 고르세요" rail
- server: 서버 승인 (권장)
- client: 클라이언트 승인
:::

:::: when approve-mode=server

## 서버 승인 흐름

:::canvas-sequence
{
  "participants": [
    { "id": "user", "label": "고객" },
    { "id": "fe", "label": "가맹점 프론트" },
    { "id": "be", "label": "가맹점 서버" },
    { "id": "bp", "label": "Bootpay" },
    { "id": "pg", "label": "PG사" }
  ],
  "messages": [
    { "from": "user", "to": "fe", "label": "1. 결제 요청", "type": "solid" },
    { "from": "fe", "to": "bp", "label": "2. requestPayment() separately_confirmed: true", "type": "solid" },
    { "from": "bp", "to": "pg", "label": "3. 결제 요청", "type": "solid" },
    { "from": "pg", "to": "bp", "label": "4. 결제 결과", "type": "dashed" },
    { "from": "bp", "to": "fe", "label": "5. onConfirm 이벤트", "type": "dashed" },
    { "from": "fe", "to": "be", "label": "6. receipt_id 전달", "type": "solid" },
    { "from": "be", "to": "be", "label": "7. 재고 확인 + 비즈니스 로직", "type": "solid" },
    { "from": "be", "to": "bp", "label": "8. 승인 API 호출", "type": "solid" },
    { "from": "bp", "to": "be", "label": "9. 승인 완료", "type": "dashed" },
    { "from": "be", "to": "be", "label": "10. DB 저장", "type": "solid" },
    { "from": "fe", "to": "user", "label": "11. 결과 페이지 (서버 DB 조회)", "type": "dashed" },
    { "from": "bp", "to": "be", "label": "12. 웹훅 (PAYMENT_COMPLETED)", "type": "solid" }
  ]
}
:::

### 핵심 포인트

1. **PG 승인 전에 서버 로직 실행** — `onConfirm` 시점에서 재고 확인, 쿠폰 차감 등을 처리한 뒤 승인 API를 호출해야 합니다
2. **클라이언트에 `onDone` 없음** — 서버가 승인하므로 클라이언트는 결제 결과를 직접 받지 못합니다. 결과 페이지에서 서버 DB 의 주문 상태를 주기적으로 조회해야 합니다

### 단계별 상세

#### 1단계: 결제 요청 (프론트엔드)

`extra.separately_confirmed: true`로 결제창을 엽니다.

```javascript
const response = await Bootpay.requestPayment({
    client_key: '[ Client Key ]',
    price: 1000,
    order_name: '상품명',
    order_id: 'order_' + Date.now(), // 테스트용. 실제로는 서버에서 생성한 주문번호 사용
    extra: {
        separately_confirmed: true
    }
})
```

#### 2단계: 서버 승인 (가맹점 서버)

`onConfirm`에서 받은 `receipt_id`를 서버로 전달해야 합니다. 서버는 비즈니스 로직을 처리한 뒤 Bootpay 승인 API를 호출해야 합니다.

```javascript [Node.js]
const confirmed = await Bootpay.confirmPayment(receipt_id)

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

주문 검증 · 금액 불일치 취소 · 가상계좌(`status: 5`)까지 넣은 7개 언어 코드는 [분리 승인 › 서버 승인](https://developers.bootpay.ai/api/pg/window/separately-confirmed#서버-승인)에 있습니다.

승인 API 호출에서 자주 만나는 응답입니다.

| error_code | HTTP | 의미와 처리 |
|---|:--:|---|
| `RC_NOT_CONFIRM_READY` | 400 | 승인 대기(`2`) 상태가 아닙니다. 결제 상태를 조회해 실제 흐름을 확인합니다 |
| `RC_CONFIRM_ALREADY_COMPLETE` | 201 | 승인 직후 10초 이내의 재요청입니다. **성공으로 간주**하고 결제 조회로 마무리합니다 |
| `RC_TIMEOUT` | 400 | 결제 유효시간이 지났습니다. 결제를 다시 요청해야 합니다 |
| `RC_COMPLETED` | 400 | 이미 결제 진행이 완료된 건입니다. 주문 상태를 확인합니다 |
| `RC_CONFIRM_NOT_PERMIT` | 401 | 결제 요청과 승인 요청의 인증 키가 같은 프로젝트가 아닙니다 |

전체 코드 목록은 [오류 코드](https://developers.bootpay.ai/api/reference/codes#결제-관련-에러)에서 확인합니다.

#### 3단계: 결과 표시 (프론트엔드)

결과 페이지에서 서버에 주문 상태를 조회해야 합니다.

```javascript
// 결과 페이지에서 polling
const checkResult = async (orderId) => {
    const res = await fetch(`/api/orders/${orderId}/status`)
    const data = await res.json()

    if (data.status === 'done') {
        // 결제 완료 표시
    } else {
        // 아직 처리 중 — 재조회
        setTimeout(() => checkResult(orderId), 1000)
    }
}
```

::::

:::: when approve-mode=client

## 클라이언트 승인 흐름

:::canvas-sequence
{
  "participants": [
    { "id": "user", "label": "고객" },
    { "id": "fe", "label": "가맹점 프론트" },
    { "id": "be", "label": "가맹점 서버" },
    { "id": "bp", "label": "Bootpay" },
    { "id": "pg", "label": "PG사" }
  ],
  "messages": [
    { "from": "user", "to": "fe", "label": "1. 결제 요청", "type": "solid" },
    { "from": "fe", "to": "bp", "label": "2. requestPayment()", "type": "solid" },
    { "from": "bp", "to": "pg", "label": "3. 결제 요청", "type": "solid" },
    { "from": "pg", "to": "bp", "label": "4. 결제 결과", "type": "dashed" },
    { "from": "bp", "to": "bp", "label": "5. 자동 승인", "type": "solid" },
    { "from": "bp", "to": "fe", "label": "6. onDone 이벤트", "type": "dashed" },
    { "from": "fe", "to": "be", "label": "7. receipt_id 전달", "type": "solid" },
    { "from": "be", "to": "bp", "label": "8. 결제 조회 (GET)", "type": "solid" },
    { "from": "bp", "to": "be", "label": "9. 검증 결과", "type": "dashed" },
    { "from": "be", "to": "be", "label": "10. DB 저장", "type": "solid" },
    { "from": "be", "to": "fe", "label": "11. 결과 반환", "type": "dashed" },
    { "from": "fe", "to": "user", "label": "12. 완료 페이지", "type": "dashed" },
    { "from": "bp", "to": "be", "label": "13. 웹훅 (PAYMENT_COMPLETED)", "type": "solid" }
  ]
}
:::

### 핵심 포인트

1. **SDK가 자동 승인** — 별도 설정 없이 PG 결제가 완료되면 SDK가 바로 승인합니다
2. **`done` 이후 서버 검증 필요** — 프론트엔드에서 받은 `receipt_id`를 백엔드로 전달하여 [결제 조회](https://developers.bootpay.ai/api/pg/server/verify)를 호출해야 합니다
3. **이벤트 누락에 대비** — 네트워크 문제, 앱 종료 등으로 `done` 처리가 누락될 수 있으므로 [웹훅](https://developers.bootpay.ai/api/common/webhook#1-웹훅-설정)을 함께 받아야 합니다

### 웹훅으로 이벤트 누락 보완

```
[정상]  프론트엔드 onDone → 백엔드 검증 → DB 저장
[누락]  부트페이 웹훅(PAYMENT_COMPLETED) → 서버 검증 → DB 저장
```

웹훅 본문에는 결제 조회 응답과 같은 필드에 더해 `webhook_type` · `application_id` · `billing_key`(빌링키 결제일 때만)가 들어옵니다. 필드와 `webhook_type` 값 전체는 [웹훅 › webhook_type 값](https://developers.bootpay.ai/api/common/webhook#webhook_type-값)에 있습니다.

::: warning 웹훅은 URL 설정이 있어야 발송됩니다
- 성공 웹훅도 결제 요청의 `extra.feedback_url` 또는 [관리자 > 개발자 설정](https://admin.bootpay.co.kr/setting/developer)에 등록한 Webhook URL 중 하나가 있어야 발송됩니다. 둘 다 없으면 아무것도 오지 않습니다.
- 오류 웹훅(`PAYMENT_CONFIRM_FAILED`, `PAYMENT_CANCEL_FAILED`, `PAYMENT_REQUEST_FAILED`)은 기본적으로 꺼져 있습니다. 결제 요청에 `extra.enable_error_webhook: true` 를 넣거나 프로젝트 설정에서 오류 웹훅을 켜야 받을 수 있습니다.
- `PAYMENT_EXPIRED` 도 기본은 꺼져 있습니다. `extra.common_event_webhook: true` 를 넣어야 발송됩니다.
- `webhook_type` 은 결제를 요청한 SDK 버전이 4.10.0 초과(베타 제외)이거나 5.1.6 초과일 때만 내려옵니다.
:::

::: warning
클라이언트 승인 방식은 승인과 검증 사이에 시간차가 있어, 그 사이에 재고가 변동될 수 있습니다. 승인 전에 재고·쿠폰을 확인하려면 서버 승인 방식을 사용합니다.
:::

::::
