주문서 요청
Commerce SDK로 주문서를 열고 결제 결과를 서버에서 검증합니다.
서버에서 청구서를 직접 만들거나 조회할 때는 청구서 API를 참고합니다. POST /v1/invoices는 Basic 인증과 공개 client_key 호출의 응답 형태가 다릅니다.
연동 흐름
상품 등록 (관리자)
상품은 관리자 상품 대시보드에서 등록하면 product_id 가 발급됩니다. 관리자 화면 순서는 매뉴얼 쇼핑몰 상품 등록에, API 로 등록하는 방법은 상품 등록에 있습니다.
주문서 요청 (개발자 · 프론트엔드)
요청 파라미터
요청 파라미터
| 파라미터 | 타입 | 필수 | 설명 |
|---|---|---|---|
| client_key | String | Y | Commerce 클라이언트 키 |
| request_id | String | Y | 가맹점 고유 식별자. 웹훅·주문 응답에 그대로 실려 옵니다 |
| name | String | Y | 주문명 (예: "Professional 플랜") |
| price | Integer | N | 서버에서 계산한 결제 금액. 생략하면 상품 기준으로 계산합니다. 등록된 상품 가격으로 계산한 금액과 대조되므로 주문 미리보기의 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 | 주문 상품 배열 |
| └─ product_id | String | N | 상품 ID |
| └─ product_option_id | String | N | 상품 옵션 ID. 옵션이 있는 상품이면 필수(INVOICE_PRODUCT_OPTION_ID_REQUIRED) |
| └─ quantity | Integer | N | 수량 (1 이상) |
| └─ duration | Integer | N | 구독 회차 수. 구독 기간이 설정된 구독 상품이면 필수 — 상품에 등록된 회차 중 하나여야 합니다(INVOICE_PRODUCT_SUBSCRIPTION_DURATION_NOT_FOUND). 수시결제·사용량 구독은 생략합니다 |
| user | Object | Y | 구매자 정보. 없으면 INVOICE_TARGET_NOT_FOUND |
| └─ membership_type | String | N | 회원 유형 (member 기본 / guest) |
| └─ user_id | String | Y | member 면 부트페이에 등록된 고객의 user_id(몰 설정에 따라 로그인 ID·이메일도 가능) — 없는 회원이면 INVOICE_TARGET_NOT_FOUND. guest 면 가맹점 쪽 식별자이고, 처음 보는 값이면 비회원 고객을 새로 만듭니다 |
| └─ corporate_type | String | N | member 일 때 개인·기업 구분 (individual 기본 / corporate) |
| └─ name | String | N | 구매자 이름 |
| └─ phone | String | N | 구매자 전화번호 |
| String | N | 구매자 이메일 | |
| metadata | Object | N | 가맹점 커스텀 데이터 |
| extra | Object | N | 추가 옵션 |
| └─ open_type | String | Y | 주문서를 여는 방식 (popup / iframe / redirect) |
| └─ separately_confirmed | Boolean | N | 분리 승인 모드. 켜면 결제창이 끝난 뒤 서버가 결제 승인을 불러야 결제가 확정됩니다 |
| └─ create_order_immediately | Boolean | N | 즉시 주문 생성 여부 |
결제 완료 처리 (개발자 · 프론트엔드)
결제가 끝나면 redirect_url로 이동하고, 결과는 URL 파라미터로 옵니다.
| 파라미터 | 설명 |
|---|---|
order_number | Commerce 주문 고유 번호 |
event | 성공 시에만 옵니다. done(결제 완료) · confirm(분리 승인 대기 — 서버가 결제 승인 호출) |
request_id | 주문서 요청 때 넘긴 가맹점 식별자 |
metadata | 주문서 요청 때 넘긴 커스텀 데이터 (JSON 문자열) |
error_code · message | 실패·취소 시에만 옵니다 (event 없이). 결제창을 닫으면 error_code=ORDER_CLOSED 입니다 |
서버 검증 (개발자 · 서버)
웹훅으로 상태 보정 (개발자 · 서버)
주문 상태가 바뀌면 웹훅이 옵니다. 서버 검증과 같은 기준으로 주문 상태를 한 번 더 맞춥니다.
| 이벤트 | 시점 | 서버가 할 일 |
|---|---|---|
order.done | 결제 완료 | 주문 완료 처리 또는 서비스 활성화 |
order.cancelled | 주문 취소 | 환불·서비스 비활성화 처리 |
order.confirm_error | 결제 승인 실패 | 주문 실패 처리 |
subscription.approved | 구독 시작 | 구독 권한 활성화 |
subscription.hold_on | 회차 결제 실패로 자동 중단 | 서비스 제한 + 복구 결제 안내 |
subscription.terminated | 결제 실패 반복으로 자동 해지 | 구독 권한 해제 |
설정은 주문 웹훅 설정, 이벤트별 처리는 웹훅 처리 가이드를 확인합니다. 실제 결제 없이 수신 경로를 확인하려면 웹훅 테스트 API의 POST /v1/webhook/test 를 사용합니다.
// 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
}
})
}<!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>// 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;
}curl -X GET "https://api.bootapi.com/v1/orders/25071182085082524116" \
-H "Authorization: Basic {base64(client_key:secret_key)}"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 })
})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})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]);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")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'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})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 });응답
주문 조회 응답
{
"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
}
]
}응답 필드
| 필드 | 타입 | 필수 | 설명 |
|---|---|---|---|
| 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 | 총 구독 회차 |
주문 상태 관리
결제 뒤 가맹점 DB 의 주문 상태(pending → paid → 출고 · 완료, 환불이면 refunded)를 어떻게 바꾸는지는 주문 처리 예제 — 주문 상태 관리에 상태도와 변경 시점이 있습니다. 이 문서의 흐름에서는 서버 검증이 성공하면 paid 로 바꾸면서 bootpay_order_number 를 저장하고, 환불은 order.cancelled 웹훅으로 확인합니다. 주문 3단계 · 상태 개념은 주문·배송, 가맹점 DB 테이블 설계는 데이터 저장 설계를 봅니다.
에러 코드
오류 코드
| 코드 | 메시지 | 대처 방법 |
|---|---|---|
| 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 로 돌아옵니다.
할인/프로모션 적용
할인을 적용하려면 서버에서 청구서를 미리 만듭니다.
// 서버에서 청구서 생성 (할인 적용)
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,
// ...
})