> For the complete documentation index, see [llms.txt](https://developers-apps-in-toss.toss.im/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://developers-apps-in-toss.toss.im/documentation/common/authentication/hash-key.md).

# 사용자 식별키 발급

사용자 식별키 발급은 별도의 서버 연동이나 사용자 동의 절차 없이도 미니앱 안에서 사용자를 안정적으로 식별할 수 있도록 돕는 기능이에요.\
사용자가 미니앱에 들어오는 순간, 해당 사용자의 미니앱 준회원이 생성돼요.

{% hint style="info" %}
**토스 로그인 마이그레이션**

기존에 토스 로그인으로 사용자를 식별하고 있었다면, 사용자 식별키 발급으로 전환할 수 있어요. 마이그레이션 가이드를 참고해 주세요.
{% endhint %}

게임·비게임 구분 없이 [User.getAnonymousKey](https://developers-apps-in-toss.toss.im/documentation/sdk/domains-api/user/user.getanonymouskey.md)로 사용자 식별키를 가져올 수 있어요. **새로 연동할 때는 `User.getAnonymousKey`를 사용해 주세요.** 미니앱 유형에 따라 서로 다른 함수를 선택할 필요가 없어요.

기존 `getUserKeyForGame`과 `getAnonymousKey`도 계속 사용할 수 있어요. 이미 연동한 코드를 반드시 변경할 필요는 없어요. 기존 함수 사용법과 오류 처리 차이는 아래 [기존 함수와의 호환성](#legacy-api)을 참고해 주세요.

{% hint style="info" %}
**꼭 확인해 주세요**

* 반환되는 고유 키 값(`hash`)은 미니앱별로 고유하며, 같은 미니앱 안에서 동일한 사용자에게 항상 같은 값이 반환돼요.
* 앱 삭제나 기기 변경이 있더라도 동일한 사용자라면 같은 값이 반환돼요.
* 토스앱 **5.232.0 이상**에서 사용할 수 있어요.
* 샌드박스에서는 mock 데이터가 반환돼요. 실제 동작은 QR 코드로 토스앱에서 테스트해 주세요.
  {% endhint %}

***

### 사용자 식별키 가져오기 <a href="#get-anonymous-key" id="get-anonymous-key"></a>

**권장 API: `User.getAnonymousKey`**

게임·비게임 모두 별도의 인증 화면이나 서버 연동 없이 사용자 식별키를 가져올 수 있어요. 반환된 `hash`로 사용자 데이터, 랭킹, 포인트, 저장 데이터 등을 관리할 수 있어요.

**시그니처와 반환 값**

```ts
User.getAnonymousKey(): Promise<GetAnonymousKeyResponse>;

type GetAnonymousKeyResponse = {
  type: 'HASH';
  hash: string;
};
```

성공하면 `{ type: 'HASH', hash: string }`을 반환해요. 실패하면 에러를 던지므로 `try/catch`로 처리해 주세요. 기존 함수의 `'ERROR'`·`undefined` 반환값 분기를 그대로 옮기지 않도록 주의해 주세요.

**예제: 사용자 식별키 가져오기**

게임·비게임에서 같은 예제를 사용할 수 있어요.

{% tabs %}
{% tab title="JavaScript" %}

```js
import { User } from '@apps-in-toss/web-framework';

async function handleGetUserKey() {
  try {
    const result = await User.getAnonymousKey();
    console.log('사용자 키:', result.hash);
    // 여기에서 사용자 키를 사용해 데이터를 관리할 수 있어요.
  } catch (error) {
    console.error('사용자 키를 가져오지 못했어요.', error);
  }
}
```

{% endtab %}

{% tab title="React" %}

```tsx
import { User } from '@apps-in-toss/web-framework';

function UserKeyButton() {
  async function handleClick() {
    try {
      const result = await User.getAnonymousKey();
      console.log('사용자 키:', result.hash);
      // 여기에서 사용자 키를 사용해 데이터를 관리할 수 있어요.
    } catch (error) {
      console.error('사용자 키를 가져오지 못했어요.', error);
    }
  }

  return <button onClick={handleClick}>사용자 키 가져오기</button>;
}
```

{% endtab %}
{% endtabs %}

반환되는 사용자 키(`hash`)는 `x-anon-key` 헤더로 프로모션, 스마트 발송, 토스페이 같은 서버 API에 보내 사용자를 식별할 수 있어요. 스마트 대량 발송은 요청 본문의 `anonKey`로 보내요. 서버에서 키가 유효한지는 아래 [식별키 검증하기](#verify-identifier-key) API로 확인할 수 있어요.

***

### 기존 함수와의 호환성 <a href="#legacy-api" id="legacy-api"></a>

기존 `getUserKeyForGame`과 `getAnonymousKey`는 계속 사용할 수 있어요. 기존 연동을 유지하거나 `User.getAnonymousKey`를 제공하지 않는 SDK를 사용 중이라면 아래 함수 사용법을 참고해 주세요. 새로 연동할 때는 게임·비게임 구분 없이 `User.getAnonymousKey`를 권장해요.

| API                    | 사용 안내                   | 실패 처리                           |
| ---------------------- | ----------------------- | ------------------------------- |
| `User.getAnonymousKey` | 게임·비게임 공통으로 권장하는 API예요. | 에러를 던지므로 `try/catch`로 처리해요.     |
| `getUserKeyForGame`    | 기존 연동을 계속 사용할 수 있어요.    | `'ERROR'` 또는 `undefined`를 확인해요. |
| `getAnonymousKey`      | 기존 연동을 계속 사용할 수 있어요.    | `'ERROR'` 또는 `undefined`를 확인해요. |

기존 두 함수는 성공하면 `{ type: 'HASH', hash: string }`을 반환해요. 알 수 없는 오류가 발생하면 `'ERROR'`, 토스앱 버전이 최소 지원 버전보다 낮으면 `undefined`를 반환해요. 토스앱 최소 지원 버전은 **5.232.0**이며, 함수형 `getAnonymousKey`는 **SDK 2.4.5 이상**에서 지원해요.

#### 기존 `getUserKeyForGame` 사용법 <a href="#game-miniapp" id="game-miniapp"></a>

```js
import { getUserKeyForGame } from '@apps-in-toss/web-framework';

async function handleGetUserKey() {
  const result = await getUserKeyForGame();

  if (!result) {
    console.warn('지원하지 않는 앱 버전이에요.');
  } else if (result === 'ERROR') {
    console.error('사용자 키 조회 중 오류가 발생했어요.');
  } else if (result.type === 'HASH') {
    console.log('사용자 키:', result.hash);
  }
}
```

#### 기존 `getAnonymousKey` 사용법 <a href="#non-game-miniapp" id="non-game-miniapp"></a>

```js
import { getAnonymousKey } from '@apps-in-toss/web-framework';

async function handleGetUserKey() {
  const result = await getAnonymousKey();

  if (!result) {
    console.warn('지원하지 않는 앱 버전이에요.');
  } else if (result === 'ERROR') {
    console.error('사용자 키 조회 중 오류가 발생했어요.');
  } else if (result.type === 'HASH') {
    console.log('사용자 키:', result.hash);
  }
}
```

***

### 식별키 검증하기 <a href="#verify-identifier-key" id="verify-identifier-key"></a>

받은 사용자 식별키가 앱인토스에서 발급된 키이고 해당 미니앱의 키인지 확인하려면 [익명 사용자 식별 키 검증하기](https://developers-apps-in-toss.toss.im/api/user-key#post-api-partner-v1-apps-in-toss-users-anon-key-verify) API를 사용해요. 요청 방법과 응답, 에러 코드는 API 문서를 참고해 주세요.

검증 API는 요청한 쪽이 해당 사용자임을 증명하지는 않아요. 파트너 서버에서 사용자를 확인하고 로그인 처리 등에 활용하려면 [사용자 식별키 인증 코드 발급](https://developers-apps-in-toss.toss.im/guide/authentication/anonymous-key-auth-code)을 이용할 수 있어요. 미니앱에서 일회용 인증 코드를 발급하고, 파트너 서버가 코드를 교환해 사용자 식별키(`anonKey`)를 받는 방식이에요.


---

# 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 by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://developers-apps-in-toss.toss.im/documentation/common/authentication/hash-key.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
