> ## Documentation Index
> Fetch the complete documentation index at: https://docs.lexq.io/llms.txt
> Use this file to discover all available pages before exploring further.

# 외부 연동

> 쿠폰 발행, 포인트 시스템, 알림 발송, 웹훅을 위해 LexQ를 외부 서비스에 연결합니다.

## 연동이란?

\*\*연동(Integration)\*\*은 LexQ를 외부 서비스에 연결합니다. 규칙의 액션이 실행될 때, LexQ가 쿠폰 시스템, 포인트 플랫폼, 알림 서비스, 또는 웹훅 엔드포인트를 호출할 수 있습니다.

연동은 한 번 설정한 후 규칙 액션에서 ID로 참조합니다.

## 연동 유형

| 유형             | 설명                | 사용 사례          |
| -------------- | ----------------- | -------------- |
| `WEBHOOK`      | HTTP 엔드포인트 호출     | 주문 처리, 커스텀 로직  |
| `COUPON`       | 외부 서비스를 통해 쿠폰 발행  | 웰컴 쿠폰, 시즌 프로모션 |
| `POINT`        | 포인트 적립 또는 차감      | 로열티 프로그램, 캐시백  |
| `NOTIFICATION` | SMS, 이메일, 푸시 발송   | 주문 확인, 알림      |
| `CRM`          | 사용자 데이터 또는 태그 동기화 | 고객 세분화         |
| `MESSENGER`    | 채팅 플랫폼으로 메시지 발송   | 고객 지원 자동화      |

<Info>
  연동 유형은 **외부 서비스의 카테고리**입니다 — 액션 타입과는 독립적입니다. 액션이 어떤 연동 유형으로 라우팅되는지는 dispatcher가 결정하며, 액션 이름이 결정하지 않습니다.
</Info>

## 연동 생성

### 콘솔

**관리 → 연동 → 연동 생성**으로 이동, 유형 선택 후 설정을 입력합니다.

### CLI

```bash theme={null}
lexq integrations save --json '{
  "type": "WEBHOOK",
  "name": "주문 처리 웹훅",
  "baseUrl": "https://api.example.com/webhooks/orders",
  "isActive": true
}'
```

### 필수 설정 확인

각 유형마다 필요한 설정 필드가 다릅니다:

```bash theme={null}
lexq integrations config-spec --type WEBHOOK
lexq integrations config-spec --type COUPON
```

## 규칙에서 연동 사용

LexQ 엔진의 액션은 **도메인 중립 원시(primitive)** 입니다 — 전체 레퍼런스는 [액션 타입](/ko/guides/policy-rules#action-types)을 참조하세요. 아래는 각 연동 유형이 호출되는 패턴입니다.

### 쿠폰 발행 — `EMIT_EVENT` + `COUPON` 연동

```json theme={null}
{
  "type": "EMIT_EVENT",
  "parameters": {
    "integrationId": "<쿠폰-연동-id>",
    "eventPayload": {
      "couponId": "WELCOME_10"
    }
  }
}
```

dispatcher는 `EMIT_EVENT`를 해당 연동 유형에 등록된 서비스로 라우팅합니다. `eventPayload`의 해석은 integration provider 책임입니다 — 엔진은 키를 검증하거나 변환하지 않습니다.

### 알림 — `EMIT_NOTIFICATION` + `NOTIFICATION` 연동

```json theme={null}
{
  "type": "EMIT_NOTIFICATION",
  "parameters": {
    "integrationId": "<알림-연동-id>",
    "targetVar": "phone_number",
    "notificationPayload": {
      "channel": "SMS",
      "templateId": "ORDER_CONFIRM"
    }
  }
}
```

`targetVar`는 수신자 팩트를 지정합니다 (`phone_number`, `email`, `device_token` 등). `notificationPayload`는 변경 없이 integration provider에 전달됩니다.

### 웹훅 — `EMIT_WEBHOOK` + `WEBHOOK` 연동

```json theme={null}
{
  "type": "EMIT_WEBHOOK",
  "parameters": {
    "url": "<웹훅-연동-id>",
    "method": "POST",
    "payloadTemplate": {
      "text": "규칙 {{ruleName}} 매칭 — {{fact.customer_tier}} 고객, 금액: {{output.payment_amount}}원"
    }
  }
}
```

`payloadTemplate` 필드는 선택 사항입니다. 생략하면 모든 팩트가 요청 본문으로 전송됩니다. 설정하면 템플릿 구조만 전송되며 `{{변수}}`가 실제 값으로 치환됩니다. 전체 변수 레퍼런스는 [정책 규칙 — EMIT\_WEBHOOK](/ko/guides/policy-rules#emit_webhook--with-payload-template)을 참조하세요.

### 포인트 적립 — `INCREMENT_FACT`

로열티 포인트 적립은 `INCREMENT_FACT`로 엔진 내부 팩트를 변경합니다:

```json theme={null}
{
  "type": "INCREMENT_FACT",
  "parameters": {
    "targetVar": "total_point",
    "refVar": "payment_amount",
    "method": "PERCENTAGE",
    "rate": 1
  }
}
```

`generatedVariables.total_point__delta`는 적용된 증분량을 노출합니다 (예: `payment_amount: 100000`에 1% 비율이면 `1000`).

<Info>
  엔진 액션 중 **`EMIT_WEBHOOK`만이 엔진 내부에서 변수 치환을 수행**합니다 (`payloadTemplate`을 통해). `EMIT_EVENT`와 `EMIT_NOTIFICATION`의 경우, 페이로드 값은 변경 없이 integration provider에 전달됩니다 — 치환과 해석은 provider 책임입니다.
</Info>

## 연동 관리

```bash theme={null}
lexq integrations list
lexq integrations get --id <integrationId>
lexq integrations save --json '{...}'
lexq integrations delete --id <integrationId>
```

## 장애 처리

실행 중 연동 호출이 실패하면 (네트워크 타임아웃, 5xx 응답 등) **장애 로그**에 기록됩니다. 재시도, 건너뛰기, 해결 처리가 가능합니다:

```bash theme={null}
lexq logs list --status PENDING
lexq logs action --id <logId> --action RETRY
```

<Info>
  변경 영향 시뮬레이션에서는 연동 호출이 항상 모킹됩니다. 드라이런에서는 콘솔의 **외부 호출 모킹** 토글로 제어합니다 (API 파라미터: `mockExternalCalls`, 기본값: `true`). `false`로 설정하면 실제 외부 호출을 시도하며, 실패 시 장애 로그에 기록됩니다.
</Info>

## 다음 단계

<CardGroup cols={2}>
  <Card title="정책 규칙" icon="list-check" href="/ko/guides/policy-rules">
    규칙 액션에서 연동을 사용하는 방법을 알아보세요.
  </Card>

  <Card title="문제 해결" icon="wrench" href="/ko/help/troubleshooting">
    일반적인 연동 문제와 해결 방법.
  </Card>
</CardGroup>
