# 주문서 요청

원문: https://commerce.bootpay.ai/api/checkout/create

> 커머스 SDK 로 주문서를 열고, 결제가 끝나 돌아온 order_number 로 서버에서 주문을 검증합니다. 이후 주문 상태 변화는 웹훅으로 한 번 더 맞춥니다.

Commerce SDK로 주문서를 열고 결제 결과를 서버에서 검증합니다.

서버에서 청구서를 직접 만들거나 조회할 때는 [청구서 API](https://commerce.bootpay.ai/api/reference/v1/invoices)를 참고합니다. `POST /v1/invoices`는 Basic 인증과 공개 `client_key` 호출의 응답 형태가 다릅니다.

::: info Next.js 서버에서 v1 API를 연결할 때
이 페이지의 브라우저 체크아웃 호출과 서버 REST 주문 준비는 입력 계약이 다릅니다. 서버 BFF에서는 [서버 주문 준비](https://commerce.bootpay.ai/api/checkout/prepare)의 `products[].option.product_option_id`, 상품 선결제 금액, URL 응답 계약을 사용합니다.

회원이 다른 도메인의 Bootpay 주문서로 이동할 때는 서버 prepare 요청에 고객 `Bootpay-User-JWT` 헤더와 `response_type: 'url'`, `use_auto_login: true`를 함께 전달합니다. API가 기존 `/b/{client_key}` 세션 경유 URL을 반환하면 브라우저는 그 URL로 이동합니다. 가맹점이 암호화나 경유 URL 생성을 구현할 필요는 없습니다. [자동 로그인 계약과 배포 확인](https://commerce.bootpay.ai/api/checkout/prepare#다른-도메인의-주문서에서도-로그인-유지하기)을 참고합니다.

범용 `/b`는 기존 청구서 전용 `/i/.../session`과 다릅니다. 일반 주문번호로 청구서 경로를 조합하면 안 되고, `__s`가 포함된 API 응답 URL도 재작성하면 안 됩니다. "세션 만료" 문구가 보이더라도 실제 오류가 `ORDER_NOT_PAYMENT_READY`이면 주문 상태를 확인합니다. [경로·식별자 구분](https://commerce.bootpay.ai/api/checkout/prepare#일반-주문-url과-청구서-세션-경유-url)과 [만료 후 재시도](https://commerce.bootpay.ai/api/checkout/prepare#만료된-주문서로-다시-이동하지-않기)를 참고합니다.
:::

## 연동 흐름

:::canvas-sequence
{
  "participants": [
    { "id": "admin", "label": "관리자" },
    { "id": "user", "label": "고객" },
    { "id": "fe", "label": "프론트엔드" },
    { "id": "be", "label": "백엔드" },
    { "id": "bp", "label": "BOOTPAY" }
  ],
  "messages": [
    { "from": "admin", "to": "bp", "label": "상품 등록 / product_id 발급", "type": "solid" },
    { "from": "be", "to": "be", "label": "주문 초안 생성 / 할인·프로모션 반영", "type": "solid" },
    { "from": "fe", "to": "be", "label": "주문서 데이터 요청", "type": "solid" },
    { "from": "be", "to": "fe", "label": "가맹점 주문번호(request_id) · 금액", "type": "dashed" },
    { "from": "fe", "to": "bp", "label": "requestCheckout() 호출", "type": "solid" },
    { "from": "user", "to": "bp", "label": "주문서에서 결제 진행", "type": "solid" },
    { "from": "bp", "to": "fe", "label": "redirect_url 로 이동 · order_number", "type": "dashed" },
    { "from": "fe", "to": "be", "label": "order_number 로 서버 검증 요청", "type": "solid" },
    { "from": "be", "to": "bp", "label": "GET /v1/orders/{order_number}", "type": "solid" },
    { "from": "bp", "to": "be", "label": "주문 · 결제 상태", "type": "dashed" },
    { "from": "be", "to": "be", "label": "주문 완료 처리", "type": "solid" }
  ]
}
:::

### 상품 등록 (관리자)

상품은 [관리자 상품 대시보드](https://admin.bootpay.co.kr/product)에서 등록하면 `product_id` 가 발급됩니다. 관리자 화면 순서는 매뉴얼 [쇼핑몰 상품 등록](https://blog.bootpay.ai/articles/shop-products)에, API 로 등록하는 방법은 [상품 등록](https://commerce.bootpay.ai/api/catalog/create)에 있습니다.

### 주문서 요청 (개발자 · 프론트엔드)

::: warning 패키지 이름을 확인합니다
커머스 클라이언트 SDK는 `@bootpay/bp-commerce-sdk` 입니다. 결제 SDK(`@bootpay/client-js`)와 다른 패키지이며 default export 이므로 중괄호 없이 가져옵니다.
:::

::: code-group

```javascript [Web (NPM)]
// npm install @bootpay/bp-commerce-sdk
import BootpayCommerce from '@bootpay/bp-commerce-sdk'

const CLIENT_KEY = 'your-client-key'

async function selectPlan(planKey) {
    // 서버에 주문 생성 요청 (위변조 방지)
    const orderRes = await fetch('/api/orders/plan', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ plan_key: planKey })
    })
    const orderData = await orderRes.json()

    // Commerce 주문서 요청
    const response = await BootpayCommerce.requestCheckout({
        client_key: CLIENT_KEY,
        request_id: orderData.order_id,
        name: orderData.order_name,
        price: orderData.price,
        redirect_url: window.location.origin + '/result',
        user: {
            membership_type: 'guest',
            user_id: 'user_1234',
            name: '홍길동',
            phone: '01012345678',
            email: 'user@example.com'
        },
        products: [
            {
                product_id: 'product_id_here',
                quantity: 1
            }
        ],
        metadata: {
            order_id: orderData.order_id,
            plan_key: planKey
        },
        extra: {
            open_type: 'redirect',
            separately_confirmed: false,
            create_order_immediately: true
        }
    })
}
```

```html [Web (CDN)]
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>요금제 선택</title>
    <script src="https://js.bootpay.co.kr/commerce/bp-commerce-sdk-1.0.7.min.js"></script>
</head>
<body>
    <script>
        const CLIENT_KEY = 'your-client-key'

        async function selectPlan(planKey) {
            try {
                // 서버에 주문 생성 요청 (위변조 방지)
                const orderRes = await fetch('/api/orders/plan', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ plan_key: planKey })
                })
                const orderData = await orderRes.json()

                // Commerce 주문서 요청
                const response = await BootpayCommerce.requestCheckout({
                    client_key: CLIENT_KEY,
                    request_id: orderData.order_id,
                    name: orderData.order_name,
                    price: orderData.price,
                    redirect_url: window.location.origin + '/result.html',
                    user: {
                        membership_type: 'guest',
                        user_id: 'user_1234',
                        name: '홍길동',
                        phone: '01012345678',
                        email: 'user@example.com'
                    },
                    products: [
                        {
                            product_id: 'product_id_here',
                            quantity: 1
                        }
                    ],
                    metadata: {
                        order_id: orderData.order_id,
                        plan_key: planKey
                    },
                    extra: {
                        open_type: 'redirect',
                        separately_confirmed: false,
                        create_order_immediately: true
                    }
                })
            } catch (error) {
                console.error('주문서 요청 오류:', error)
            }
        }
    </script>
</body>
</html>
```

```dart [Flutter Web]
// web/index.html <head>에 Commerce JS SDK 추가 필수:
// <script src="https://js.bootpay.co.kr/commerce/bp-commerce-sdk-1.0.7.min.js"></script>

import 'dart:js_interop';

@JS('BootpayCommerce.requestCheckout')
external JSPromise<JSAny> _requestCheckout(JSAny options);

Future<void> selectPlan(String planKey) async {
    // 서버에 주문 생성 요청 (위변조 방지)
    final orderData = await api.createOrder(planKey);

    final options = {
        'client_key': 'your-client-key',
        'request_id': orderData['order_id'],
        'name': orderData['order_name'],
        'price': orderData['price'],
        'redirect_url': '${Uri.base.origin}/result',
        'user': {
            'membership_type': 'guest',
            'user_id': 'user_1234',
            'name': '홍길동',
            'phone': '01012345678',
            'email': 'user@example.com',
        },
        'products': [
            {
                'product_id': 'product_id_here',
                'quantity': 1,
            }
        ],
        'metadata': {
            'order_id': orderData['order_id'],
            'plan_key': planKey,
        },
        'extra': {
            'open_type': 'redirect',
            'separately_confirmed': false,
            'create_order_immediately': true,
        },
    }.jsify()!;

    await _requestCheckout(options).toDart;
}
```

:::

::: warning 구독 주문은 상품 1종만 담을 수 있습니다
구독 상품이 들어 있는데 `products` 가 두 줄 이상이면 `INVOICE_SUBSCRIPTION_REQUEST_ONLY_ONE` 으로 거절됩니다. 같은 상품을 두 줄로 나눠 넣어도 마찬가지입니다 — 한 줄에 `quantity` 로 수량을 조절합니다. 일반 주문에는 이 제약이 없습니다.
:::

::: info 모바일 앱 (Android · iOS · Flutter · React Native)
Commerce 주문서는 웹 리디렉트 방식입니다. 모바일 앱에서는 WebView로 주문서 페이지를 열거나, [결제 요청](https://developers.bootpay.ai/payment-window/integration)에서 일반 결제 SDK를 사용합니다.

앱의 WebView로 열 때는 기본 WebView 대신 [부트페이 웹뷰](https://developers.bootpay.ai/more/webview)를 씁니다. 기본 WebView는 카드사·간편결제 앱 호출을 처리하지 못합니다. 또 앱에서 http 통신을 허용해야 카드사 인증 화면에서 결제가 멈추지 않습니다(iOS `Info.plist`의 `NSAllowsArbitraryLoadsInWebContent`, Android `usesCleartextTraffic`). 설정 방법은 [웹뷰 결제 › 앱 설정하기](https://developers.bootpay.ai/more/webview#3-앱-설정하기)에 있습니다.
:::

#### 요청 파라미터

::: parameters

| 파라미터 | 타입 | 필수 | 설명 |
|---------|------|------|------|
| client_key | String | Y | Commerce 클라이언트 키 |
| request_id | String | Y | 가맹점 고유 식별자. 웹훅·주문 응답에 그대로 실려 옵니다 |
| name | String | Y | 주문명 (예: "Professional 플랜") |
| price | Integer | N | 서버에서 계산한 결제 금액. 생략하면 상품 기준으로 계산합니다. 등록된 상품 가격으로 계산한 금액과 대조되므로 [주문 미리보기](https://commerce.bootpay.ai/api/checkout/prepare)의 `total_order_price` 를 그대로 넘기면 일치합니다 |
| tax_free_price | Integer | N | 비과세 금액 |
| delivery_price | Integer | N | 배송비 |
| memo | String | N | 내부 메모 |
| redirect_url | String | N | 결제 완료 후 이동 URL. `open_type: 'redirect'` 면 사실상 필수입니다 |
| expired_at | String | N | 주문서 만료 시각 (ISO 8601) |
| usage_api_url | String | N | 사용량 기반 구독의 사용량 조회 URL |
| use_auto_login | Boolean | N | 링크 진입 시 자동 로그인 여부 |
| products | Array | N | 주문 상품 배열 |
| &nbsp;&nbsp;└─ product_id | String | N | 상품 ID |
| &nbsp;&nbsp;└─ product_option_id | String | N | 상품 옵션 ID. 옵션이 있는 상품이면 필수(`INVOICE_PRODUCT_OPTION_ID_REQUIRED`) |
| &nbsp;&nbsp;└─ quantity | Integer | N | 수량 (1 이상) |
| &nbsp;&nbsp;└─ duration | Integer | N | 구독 회차 수. 구독 기간이 설정된 구독 상품이면 필수 — 상품에 등록된 회차 중 하나여야 합니다(`INVOICE_PRODUCT_SUBSCRIPTION_DURATION_NOT_FOUND`). 수시결제·사용량 구독은 생략합니다 |
| user | Object | Y | 구매자 정보. 없으면 `INVOICE_TARGET_NOT_FOUND` |
| &nbsp;&nbsp;└─ membership_type | String | N | 회원 유형 (`member` 기본 / `guest`) |
| &nbsp;&nbsp;└─ user_id | String | Y | `member` 면 부트페이에 [등록된 고객](https://commerce.bootpay.ai/api/customer/register)의 `user_id`(몰 설정에 따라 로그인 ID·이메일도 가능) — 없는 회원이면 `INVOICE_TARGET_NOT_FOUND`. `guest` 면 가맹점 쪽 식별자이고, 처음 보는 값이면 비회원 고객을 새로 만듭니다 |
| &nbsp;&nbsp;└─ corporate_type | String | N | `member` 일 때 개인·기업 구분 (`individual` 기본 / `corporate`) |
| &nbsp;&nbsp;└─ name | String | N | 구매자 이름 |
| &nbsp;&nbsp;└─ phone | String | N | 구매자 전화번호 |
| &nbsp;&nbsp;└─ email | String | N | 구매자 이메일 |
| metadata | Object | N | 가맹점 커스텀 데이터 |
| extra | Object | N | 추가 옵션 |
| &nbsp;&nbsp;└─ open_type | String | **Y** | 주문서를 여는 방식 (`popup` / `iframe` / `redirect`) |
| &nbsp;&nbsp;└─ separately_confirmed | Boolean | N | 분리 승인 모드. 켜면 결제창이 끝난 뒤 서버가 [결제 승인](https://commerce.bootpay.ai/api/orders/confirm)을 불러야 결제가 확정됩니다 |
| &nbsp;&nbsp;└─ create_order_immediately | Boolean | N | 즉시 주문 생성 여부 |
:::

### 결제 완료 처리 (개발자 · 프론트엔드)

결제가 끝나면 `redirect_url`로 이동하고, 결과는 URL 파라미터로 옵니다.

| 파라미터 | 설명 |
|---------|------|
| `order_number` | Commerce 주문 고유 번호 |
| `event` | 성공 시에만 옵니다. `done`(결제 완료) · `confirm`(분리 승인 대기 — 서버가 [결제 승인](https://commerce.bootpay.ai/api/orders/confirm) 호출) |
| `request_id` | 주문서 요청 때 넘긴 가맹점 식별자 |
| `metadata` | 주문서 요청 때 넘긴 커스텀 데이터 (JSON 문자열) |
| `error_code` · `message` | 실패·취소 시에만 옵니다 (`event` 없이). 결제창을 닫으면 `error_code=ORDER_CLOSED` 입니다 |

::: warning
프론트엔드 결과만으로 주문을 완료하면 안 됩니다. 서버에서 주문을 반드시 검증합니다.
:::

### 서버 검증 (개발자 · 서버)

::: endpoint
method: GET
url: https://api.bootapi.com/v1/orders/{order_number}
auth: [Basic Auth](https://commerce.bootpay.ai/api/server/authentication)
:::

::: warning `order_id` 가 아니라 `order_number` 입니다
리다이렉트 쿼리로 돌아온 `order_number`(예: `25071182085082524116`)를 그대로 넣습니다.
24자리 `order_id` 를 넣으면 `ORDER_NOT_FOUND` 가 돌아옵니다.
:::

::: code-group

```bash [cURL]
curl -X GET "https://api.bootapi.com/v1/orders/25071182085082524116" \
  -H "Authorization: Basic {base64(client_key:secret_key)}"
```

```javascript [Node.js]
const { BootpayCommerce } = require('@bootpay/backend-js')

const commerce = new BootpayCommerce({
    client_key: 'your-commerce-client-key',
    secret_key: 'your-commerce-secret-key',
    mode: 'production'
})

app.post('/api/orders/verify', async (req, res) => {
    const { order_number } = req.body

    const order = await commerce.order.detail(order_number)
    const draft = await getOrderDraft(order.request_id)  // 주문서 요청 때 넘긴 request_id

    // 금액·상태 검증 (위변조 방지)
    if (order.price !== draft.price) {
        return res.json({ success: false, message: '금액 불일치' })
    }
    if (order.status !== 'payment_completed') {
        return res.json({ success: false, message: '결제 완료 주문이 아니에요' })
    }

    await markOrderPaid(order.order_number)
    res.json({ success: true })
})
```

```python [Python]
from bootpay_backend import BootpayCommerce

commerce = BootpayCommerce(
    client_key='your-commerce-client-key',
    secret_key='your-commerce-secret-key',
    mode='production'
)

@app.route('/api/orders/verify', methods=['POST'])
def verify_order():
    order_number = request.get_json()['order_number']

    order = commerce.order.detail(order_number)
    draft = get_order_draft(order['request_id'])

    if order['price'] != draft['price']:
        return jsonify({'success': False, 'message': '금액 불일치'})
    if order['status'] != 'payment_completed':
        return jsonify({'success': False, 'message': '결제 완료 주문이 아니에요'})

    mark_order_paid(order['order_number'])
    return jsonify({'success': True})
```

```php [PHP]
use Bootpay\ServerPhp\BootpayCommerceApi;

$commerce = new BootpayCommerceApi('your-commerce-client-key', 'your-commerce-secret-key');
$order = $commerce->order->detail($orderNumber);
$draft = getOrderDraft($order->request_id);

if ($order->price !== $draft['price'] || $order->status !== 'payment_completed') {
    echo json_encode(['success' => false]);
    exit;
}

markOrderPaid($order->order_number);
echo json_encode(['success' => true]);
```

```java [Java]
import kr.co.bootpay.store.BootpayStore;
import kr.co.bootpay.store.model.request.TokenPayload;
import kr.co.bootpay.store.model.response.BootpayStoreResponse;

TokenPayload tp = new TokenPayload("your-commerce-client-key", "your-commerce-secret-key");
BootpayStore commerce = new BootpayStore(tp).withToken();

BootpayStoreResponse response = commerce.order.detail(orderNumber);
System.out.println(response);
// response 의 price · status 를 내부 주문 초안과 대조합니다 (status == "payment_completed")
```

```ruby [Ruby]
require 'bootpay'

commerce = BootpayStore::RestClient.new(client_key: 'your-commerce-client-key', secret_key: 'your-commerce-secret-key')
response = commerce.order_detail(order_number: order_number)
order    = response.data # BootpayStore::Response — 본문은 심볼 키 Hash

raise '금액 불일치' if order[:price] != draft_price
raise '결제 완료 주문이 아니에요' if order[:status] != 'payment_completed'
```

```go [Go]
import "github.com/bootpay/backend-go/v2"

commerce := bootpay.NewCommerceAPI("your-commerce-client-key", "your-commerce-secret-key", nil, "production")
order, err := commerce.Order.Detail(orderNumber) // map[string]interface{} 로 돌아옵니다
if err != nil {
    log.Fatal(err)
}
price, _ := order["price"].(float64)
status, _ := order["status"].(string)
if int(price) != draftPrice || status != "payment_completed" {
    json.NewEncoder(w).Encode(map[string]bool{"success": false})
    return
}
json.NewEncoder(w).Encode(map[string]bool{"success": true})
```

```csharp [.NET]
using Bootpay.Commerce;
using Newtonsoft.Json.Linq;

var commerce = new BootpayCommerceApi("your-commerce-client-key", "your-commerce-secret-key");
var response = await commerce.OrderDetail(orderNumber); // HttpResponseMessage 로 돌아옵니다
var order = JObject.Parse(await response.Content.ReadAsStringAsync());

if ((int)order["price"] != draftPrice || (string)order["status"] != "payment_completed")
{
    return Ok(new { success = false });
}
return Ok(new { success = true });
```

:::

::: tip 영수증 단위로 더 파고들어야 한다면
카드사·PG 응답까지 확인하려면 응답의 `result_data.receipt_id` 로 결제 API 를 한 번 더 조회합니다 —
[결제 매뉴얼: 서버 검증](https://developers.bootpay.ai/server/verify)에서 다룹니다.
:::

### 웹훅으로 상태 보정 (개발자 · 서버)

주문 상태가 바뀌면 웹훅이 옵니다. 서버 검증과 같은 기준으로 주문 상태를 한 번 더 맞춥니다.

| 이벤트 | 시점 | 서버가 할 일 |
| --- | --- | --- |
| `order.done` | 결제 완료 | 주문 완료 처리 또는 서비스 활성화 |
| `order.cancelled` | 주문 취소 | 환불·서비스 비활성화 처리 |
| `order.confirm_error` | 결제 승인 실패 | 주문 실패 처리 |
| `subscription.approved` | 구독 시작 | 구독 권한 활성화 |
| `subscription.hold_on` | 회차 결제 실패로 자동 중단 | 서비스 제한 + 복구 결제 안내 |
| `subscription.terminated` | 결제 실패 반복으로 자동 해지 | 구독 권한 해제 |

설정은 [주문 웹훅 설정](https://commerce.bootpay.ai/api/server/webhook-setup), 이벤트별 처리는 [웹훅 처리 가이드](https://commerce.bootpay.ai/api/server/webhook-guide)를 확인합니다. 실제 결제 없이 수신 경로를 확인하려면 [웹훅 테스트 API](https://commerce.bootpay.ai/api/reference/v1/webhook)의 `POST /v1/webhook/test` 를 사용합니다.

## 응답

#### 주문 조회 응답

```json
{
  "order_name": "구독상품 - 1회차",
  "price": 2800,
  "status": "payment_completed",
  "receipt_status": "receipt_success",
  "order_number": "25071182085082524116",
  "purchased_at": "2025-07-11T02:52:09Z",
  "created_at": "2025-07-11T02:52:09Z",
  "result_data": {
    "receipt_id": "68707c598bbe23d076af189c",
    "pg": "라이트페이",
    "method": "카드",
    "status": 1,
    "card_data": {
      "card_company": "KB국민",
      "card_no": "557042******1074"
    }
  },
  "order_subscriptions": [
    {
      "order_subscription_id": "68707c58b0eacea5cd974ef7",
      "status": "subscribing",
      "current_duration": 3,
      "total_subscription_duration": 4
    }
  ]
}
```

:::response-fields
| 필드 | 타입 | 필수 | 설명 |
|------|------|------|------|
| order_name | String | Y | 주문명 |
| price | Integer | Y | 결제 금액 |
| status | String | Y | 주문 상태 (`order_pending`: 대기, `payment_pending`: 결제 진행 중, `payment_completed`: 결제 완료) |
| receipt_status | String | Y | 결제 영수증 상태 (`receipt_success`: 완료) |
| order_number | String | Y | 주문 고유번호 |
| purchased_at | String | Y | 결제 일시 (ISO 8601) |
| created_at | String | Y | 주문 생성 일시 |
| result_data | Object | N | 결제 결과 상세 |
| ∟ receipt_id | String | Y | Bootpay 영수증 ID |
| ∟ pg | String | Y | PG사 이름 |
| ∟ method | String | Y | 결제 수단 |
| ∟ status | Integer | Y | 결제 상태 (1: 완료) |
| ∟ card_data | Object | N | 카드 결제 시 카드 정보 |
| ∟∟ card_company | String | Y | 카드사 |
| ∟∟ card_no | String | Y | 마스킹된 카드번호 |
| order_subscriptions | Array | N | 구독 계약 목록 (구독 주문일 때만 옵니다) |
| ∟ order_subscription_id | String | Y | 구독 ID |
| ∟ status | String | Y | 구독 상태 (`subscribing`: 구독 중) |
| ∟ current_duration | Integer | Y | 현재 구독 회차 |
| ∟ total_subscription_duration | Integer | Y | 총 구독 회차 |
:::

::: info `order_id` 는 이 응답에 없습니다
주문 조회 응답과 웹훅에는 주문 문서 ID(`order_id`)가 없습니다. 가맹점 DB 와는 `order_number` 와 `request_id` 로 맞춥니다.
:::

## 주문 상태 관리

결제 뒤 가맹점 DB 의 주문 상태(`pending` → `paid` → 출고 · 완료, 환불이면 `refunded`)를 어떻게 바꾸는지는 [주문 처리 예제 — 주문 상태 관리](https://commerce.bootpay.ai/api/server/order-example#주문-상태-관리)에 상태도와 변경 시점이 있습니다. 이 문서의 흐름에서는 [서버 검증](#서버-검증-개발자--서버)이 성공하면 `paid` 로 바꾸면서 `bootpay_order_number` 를 저장하고, 환불은 `order.cancelled` 웹훅으로 확인합니다. 주문 3단계 · 상태 개념은 [주문·배송](https://commerce.bootpay.ai/docs/orders), 가맹점 DB 테이블 설계는 [데이터 저장 설계](https://commerce.bootpay.ai/api/reference/data-model)를 봅니다.

::: info 상태·유형 값은 문자열입니다
응답의 `status` 같은 코드값은 정수가 아니라 문자열(enum)로 내려옵니다. 전체 목록은 [커머스 Enum](https://commerce.bootpay.ai/api/reference/enum)에서 확인합니다.
:::

## 에러 코드

::: info 공통 에러
인증·권한 관련 에러는 [에러 코드표](https://commerce.bootpay.ai/api/reference/codes#커머스-api-인증-에러)를 참고합니다.
:::

::: error-codes
| 코드 | 메시지 | 대처 방법 |
|------|--------|-----------|
| INVOICE_TARGET_NOT_FOUND | 주문서에 연결할 고객 정보가 없습니다. | `user.user_id` 를 넣었는지, `member` 라면 부트페이에 등록된 고객인지 확인합니다 |
| INVOICE_REQUEST_ID_BLANK | 요청 ID가 필요합니다. | `request_id` 를 넣습니다 |
| INVOICE_EXPIRED_DATE_INVALID | 만료일이 현재 시간보다 과거입니다. | `expired_at` 을 미래 시각으로 넣습니다 |
| INVOICE_PRODUCT_NOT_FOUND | 존재하지 않는 상품이 포함되어 있습니다. | `product_id` 가 이 프로젝트의 판매 중 상품인지 확인합니다 |
| INVOICE_ITEM_QTY_LT_ZERO | 상품 수량은 0보다 커야 합니다. | `quantity` 를 1 이상으로 넣습니다 |
| INVOICE_PRODUCT_OPTION_ID_REQUIRED | 옵션이 필요한 상품이 포함되어 있습니다. | `product_option_id` 를 넣습니다 |
| INVOICE_PRODUCT_OPTION_NOT_FOUND | 존재하지 않는 옵션이 포함되어 있습니다. | `product_option_id` 를 확인합니다 |
| INVOICE_SUBSCRIPTION_REQUEST_ONLY_ONE | 구독 상품은 하나만 담을 수 있습니다. | `products` 를 한 줄로 줄입니다 |
| INVOICE_PRODUCT_SUBSCRIPTION_DURATION_NOT_FOUND | 존재하지 않는 구독 기간이 포함되어 있습니다. | `duration` 을 상품에 등록된 회차로 넣습니다 |
| INVOICE_NEED_USAGE_API_URL | 사용량 기반 구독 상품은 사용량 API URL이 필요합니다. | 상품에 사용량 조회 URL 을 등록합니다 |
:::

주문서 화면에서 결제하는 도중에 나는 에러(재고 소진·배송지 누락 등)는 이 호출의 응답이 아니라 [결제 완료 처리](#결제-완료-처리-개발자--프론트엔드)의 `error_code` 로 돌아옵니다.

## 할인/프로모션 적용

할인을 적용하려면 서버에서 청구서를 미리 만듭니다.

```javascript
// 서버에서 청구서 생성 (할인 적용)
const invoice = await commerce.invoice.create({
    products: [{ product_id: 'product_123', quantity: 1 }],
    price: finalPrice,           // 할인 적용된 최종 금액
    original_price: originalPrice,
    user: { user_id: 'user_1234', name: '홍길동' },
    metadata: { promotion_code: 'SUMMER2024' }
})

// 프론트엔드에서 invoice_id를 request_id로 전달
BootpayCommerce.requestCheckout({
    request_id: invoice.invoice_id,
    // ...
})
```
