> For the complete documentation index, see [llms.txt](https://malgn.gitbook.io/cloud/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://malgn.gitbook.io/cloud/api/coupon-issuance-search.md).

# 쿠폰 발급 및 주문 쿠폰 조회

> **문서 정보**
>
> * **버전:** 1.0
> * **작성일:** 2026.04.17

* **Base URL (Production)**: `https://api.dbmalgn.com`
* **Swagger UI**: `https://api.dbmalgn.com/docs`
* **OpenAPI Spec**: `https://api.dbmalgn.com/openapi.json`
* **인증 방식**: `X-API-Key` 헤더 (발급받은 API Key 사용)

***

### 1. 인증

모든 `/api/v1/*` 엔드포인트는 인증이 필요합니다.

#### 헤더

```
X-API-Key: <발급받은 API Key>
Content-Type: application/json
```

* API Key는 별도로 발급받아 관리합니다.
* API Key는 `siteId`(사이트 식별자)와 매핑되어 있으며, 요청 시 자동으로 해당 사이트 컨텍스트로 처리됩니다.
* 유효하지 않거나 누락된 경우 `401 Unauthorized` 반환.

***

### 2. 엔드포인트 목록

<table><thead><tr><th width="108">메서드</th><th width="306">경로</th><th>설명</th></tr></thead><tbody><tr><td><code>GET</code></td><td><code>/health</code></td><td>헬스체크 (인증 불필요)</td></tr><tr><td><code>POST</code></td><td><code>/api/v1/coupons/issue</code></td><td>쿠폰 자동 발급 요청 <br>(비동기, 웹훅 수신)</td></tr><tr><td><code>GET</code></td><td><code>/api/v1/orders/{orderId}/coupons</code></td><td>주문에 사용된 쿠폰 정보 조회</td></tr></tbody></table>

***

### 3. 쿠폰 발급 요청

**`POST /api/v1/coupons/issue`**

지정한 수량만큼 쿠폰을 비동기로 발급합니다. 요청 즉시 `202 Accepted`와 `traceId`를 응답하며, 실제 발급이 완료되면 지정한 `webhookUrl`로 결과를 전송합니다.

#### 요청 파라미터

<table><thead><tr><th width="130">필드</th><th width="129">타입</th><th width="105">필수</th><th>설명</th></tr></thead><tbody><tr><td><code>couponId</code></td><td>integer</td><td>조건부</td><td><code>TB_COUPON.ID</code>. <code>couponId</code> 또는 <code>couponCd</code> 중 하나 필수. 둘 다 있으면 <code>couponId</code> 우선</td></tr><tr><td><code>couponCd</code></td><td>string</td><td>조건부</td><td><code>TB_COUPON.COUPON_CD</code></td></tr><tr><td><code>quantity</code></td><td>integer</td><td>✅</td><td>발급 수량 (1 이상 정수)</td></tr><tr><td><code>webhookUrl</code></td><td>string (uri)</td><td>✅</td><td>발급 완료 시 결과를 전송받을 URL</td></tr></tbody></table>

#### 요청 예시

```bash
curl -X POST https://api.dbmalgn.com/api/v1/coupons/issue \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "couponCd": "SPRING2026",
    "quantity": 100,
    "webhookUrl": "https://your-service.com/webhooks/coupon-result"
  }'
```

#### 응답 (202 Accepted)

```json
{
  "status": "processing",
  "message": "쿠폰 발급 요청이 대기열에 등록되었습니다. 완료 시 웹훅으로 전송됩니다.",
  "traceId": "req_8f7d9a8c"
}
```

* `traceId`: 발급 요청 추적용 ID. 웹훅 페이로드에 동일하게 포함됩니다.

#### 웹훅 페이로드 (발급 완료 시)

서버가 `webhookUrl`로 `POST` 요청을 보냅니다.

```json
{
  "traceId": "req_8f7d9a8c",
  "status": "completed",
  "couponId": 1234,
  "couponCd": "SPRING2026",
  "quantity": 100,
  "issuedAt": "2026-04-17T08:30:00Z"
}
```

> **주의**: 웹훅 수신 엔드포인트는 외부에서 접근 가능한 HTTPS URL이어야 하며, 2xx 응답을 반환해야 성공 처리됩니다.

***

### 4. 주문 쿠폰 조회

**`GET /api/v1/orders/{orderId}/coupons`**

특정 주문(`orderId`)에 사용된 쿠폰 목록을 조회합니다. KV 캐시 우선 조회(TTL 60초), 미스 시 DB 조회 후 캐싱됩니다.

#### 경로 파라미터

| 필드        | 타입      | 필수 | 설명    |
| --------- | ------- | -- | ----- |
| `orderId` | integer | ✅  | 주문 ID |

#### 요청 예시

```bash
curl -X GET https://api.dbmalgn.com/api/v1/orders/12385125/coupons \
  -H "X-API-Key: YOUR_API_KEY"
```

#### 응답 (200 OK)

```json
{
  "orderId": 12385125,
  "cacheHit": false,
  "usedCoupons": [
    {
      "orderItemId": 98765,
      "couponUserId": 45612,
      "couponId": 1234,
      "couponName": "봄맞이 10% 할인",
      "couponCode": "SPRING2026"
    }
  ]
}
```

<table><thead><tr><th width="148">필드</th><th>설명</th></tr></thead><tbody><tr><td><code>cacheHit</code></td><td>KV 캐시 히트 여부 (<code>true</code>이면 캐시에서 반환)</td></tr><tr><td><code>usedCoupons[]</code></td><td>사용된 쿠폰 목록. 해당 주문이 쿠폰을 사용하지 않았으면 빈 배열</td></tr></tbody></table>

***

### 5. 헬스체크

**`GET /health`**

인증 없이 호출 가능한 상태 확인용 엔드포인트입니다.

```bash
curl https://api.dbmalgn.com/health
```

```json
{
  "status": "healthy",
  "timestamp": "2026-04-17T08:30:00.000Z",
  "db": { "connected": true, "result": { "ok": 1 } }
}
```

***

### 6. 에러 응답

모든 에러 응답은 다음 형식을 따릅니다.

```json
{
  "error": "Validation Error",
  "message": "quantity, webhookUrl은 필수 파라미터입니다."
}
```

<table data-header-hidden><thead><tr><th width="121"></th><th width="228"></th><th></th></tr></thead><tbody><tr><td>HTTP 상태</td><td><code>error</code></td><td>발생 사유</td></tr><tr><td><code>400</code></td><td><code>Validation Error</code></td><td>필수 파라미터 누락, 타입/값 오류</td></tr><tr><td><code>401</code></td><td><code>Unauthorized</code></td><td>API Key 누락 또는 유효하지 않음</td></tr><tr><td><code>404</code></td><td><code>Not Found</code></td><td>리소스 없음 / 존재하지 않는 경로</td></tr><tr><td><code>500</code></td><td><code>Internal Server Error</code></td><td>서버 내부 오류</td></tr></tbody></table>

#### 대표 에러 예시

**API Key 누락/오류 (401)**

```json
{ "error": "Unauthorized", "message": "Invalid API Key" }
```

**필수 파라미터 누락 (400)**

```json
{ "error": "Validation Error", "message": "couponId 또는 couponCd 중 하나는 필수입니다." }
```

**잘못된 orderId (400)**

```json
{ "error": "Validation Error", "message": "유효한 orderId를 입력해주세요." }
```

***


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://malgn.gitbook.io/cloud/api/coupon-issuance-search.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
