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

# 빠른 시작

> 편집기를 내 화면에 띄우기까지 가장 짧은 경로

이 문서를 끝내면 내 페이지 안에 Edicus 편집기가 떠 있고, 사용자가 만든 프로젝트의 id를 내 서버에 저장할 수 있습니다. 15분 정도 걸립니다.

<Warning>
  API 키는 고객사 서버에만 둡니다. 브라우저 코드나 공개 저장소에 넣지 마세요. 브라우저에는 API 키로 발급받은 토큰만 내려보냅니다.
</Warning>

## 준비물

* **파트너 코드**와 **API 키**. 둘 다 모션원에서 발급합니다.
* 연습용 \*\*템플릿 `resUri`\*\*와 **ps\_code**. 발급 시 함께 안내합니다. `resUri`는 띄울 때 `template_uri`에 그대로 넣습니다. 직접 만들려면 [상품과 ps\_code 만들기](/docs/products/create)로 상품을 만들고 [템플릿 업로드와 수정](/docs/templates/upload)으로 템플릿을 올립니다.
* 서버 한 대. 예제는 Node.js 18 이상 기준이지만 HTTP를 보낼 수 있으면 어느 언어든 됩니다.

## 1. 설치

```sh theme={null}
npm install @edicus/sdk@3.0.0-alpha.2
```

`<script>` 태그로 쓰신다면 [SDK v2에서 옮기기](/docs/reference/migration-from-v2)를 보세요.

## 2. 서버에서 토큰 발급

토큰은 반드시 서버에서 발급합니다. API 키가 브라우저로 내려가면 누구나 그 키로 남의 프로젝트를 조회하고 주문을 넣을 수 있습니다.

서버 연동에는 JS SDK가 없습니다. HTTP 엔드포인트를 직접 호출합니다.

```ts server/edicus.ts theme={null}
// 사용자마다 고유한 uid로 발급합니다. 유효기간은 1시간입니다.
export async function issueToken(edicusUid: string) {
  const res = await fetch('https://api.edicus.io/v2/auth/token', {
    method: 'POST',
    headers: {
      'edicus-api-key': process.env.EDICUS_API_KEY!,
      'edicus-uid': edicusUid,
    },
  })
  if (!res.ok) {
    // 실패는 4xx와 5xx로 옵니다. body는 { error: { code, message, request_id } }입니다
    const { error } = await res.json()
    throw new Error(`토큰 발급 실패: ${error.code} (${error.request_id})`)
  }
  const { token } = await res.json()
  return token
}
```

<Note>
  `edicus-uid`가 형식 규칙을 어기면 `400 invalid_request`, API 키가 틀리면 `401 invalid_api_key`입니다. 오류 코드 전체는 [오류 처리](/docs/server/errors)에 있습니다.
</Note>

`uid`는 고객사 사용자 계정과 1:1로 대응하는 값입니다. 별도의 생성 절차가 없고, 처음 보는 값이면 토큰을 요청하는 그 순간 사용자가 만들어집니다. 형식 규칙은 [토큰과 API 키](/docs/concepts/authentication)에 있습니다.

이 토큰을 내려줄 엔드포인트를 하나 만들어 둡니다.

```ts server/routes.ts theme={null}
app.get('/api/edicus/token', async (req, res) => {
  const token = await issueToken(req.user.edicusUid)
  res.json({ token })
})
```

## 3. 브라우저에서 편집기 띄우기

```ts app.ts theme={null}
import { createEdicusClient } from '@edicus/sdk'

const edicus = createEdicusClient({
  // 편집기가 토큰을 다시 요청하면 SDK가 이 함수로 갱신해 자동으로 응답합니다.
  getToken: async () => (await fetch('/api/edicus/token').then((r) => r.json())).token,
})

const { token } = await fetch('/api/edicus/token').then((r) => r.json())

const session = edicus.createProject({
  parent_element: document.getElementById('editor-mount')!,
  token,
  partner: '<파트너 코드>',
  ps_code: '90x50@NAMECARD',
  template_uri: 'gcs://template/partners/<파트너 코드>/res/template/<템플릿 ID>.json',
  title: '내 명함',
  mobile: 'm2',
})
```

`parent_element`로 준 요소 안에 편집기가 iframe으로 들어갑니다. 그 요소에 크기를 주어야 편집기가 보입니다.

## 4. 프로젝트 id 받아 저장하기

새 프로젝트가 만들어지면 편집기가 `project-id-created` 이벤트를 한 번 보냅니다. 이 id가 있어야 나중에 다시 열거나 주문할 수 있으므로 내 DB에 저장합니다.

```ts theme={null}
const { project_id } = await session.waitFor('project-id-created')
console.log('project_id', project_id)
await fetch('/api/my/projects', {
  method: 'POST',
  headers: { 'content-type': 'application/json' },
  body: JSON.stringify({ project_id }),
})
```

## 5. 편집기 닫기

사용자가 편집기 안에서 저장하고 나가면 편집기가 `close` 또는 `goto-cart`를 보냅니다.

```ts theme={null}
const reason = await session.waitForExit() // 'close' | 'goto-cart'
session.close()
```

<Warning>
  `save-doc-report` 핸들러에서 내 서버로 무언가를 보내고 계시다면 `waitForExit()`를 꼭 쓰세요. 그 비동기 작업이 끝나기 전에 화면을 떠나면 반영이 유실됩니다. 자세한 내용은 [닫기와 저장 후처리](/docs/sdk/exit)에 있습니다.
</Warning>

## 됐는지 확인하기

<Check>
  편집기가 화면에 보이고, 콘솔에 프로젝트 id가 찍히고, 편집기에서 나가기를 누르면 `waitForExit()`가 resolve됩니다.
</Check>

편집기가 뜨지 않는다면 다음을 확인합니다.

| 증상 | 확인할 것 |
| - | - |
| 빈 화면 | `parent_element`에 높이가 있는지 |
| `error-report`의 `load-prodinfo-failed` | `ps_code`가 맞는지 |
| `error-report`의 `load-template-failed` | `template_uri`가 맞는지 |
| 즉시 `Error` 발생 | 필수 옵션을 빠뜨리지 않았는지. 메시지에 빠진 키 이름이 들어 있습니다 |

## 다음 단계

<Columns cols={2}>
  <Card title="큰 그림" icon="diagram-project" href="/docs/concepts/architecture">
    세 참여자가 무엇을 주고받는지 정리합니다.
  </Card>

  <Card title="편집기 띄우기" icon="window" href="/docs/sdk/launch">
    세 가지 띄우기 메서드와 전체 옵션을 봅니다.
  </Card>

  <Card title="주문" icon="cart-shopping" href="/docs/server/orders">
    편집이 끝난 프로젝트를 주문으로 넘깁니다.
  </Card>

  <Card title="Server API" icon="server" href="/docs/api-reference/introduction">
    엔드포인트별 요청과 응답을 확인합니다.
  </Card>
</Columns>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.