> 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/api-and-sdk-zh/common/authentication/hash-key.md).

# 用户识别键发放

用户识别键发放是一项无需单独服务器或用户同意流程，也能帮助在迷你应用内稳定识别用户的功能。

{% hint style="info" %}
**Toss 登录迁移**

如果你之前是通过 Toss 登录来识别用户，可以切换到用户识别键发放。请参考迁移指南。
{% endhint %}

根据迷你应用类型，使用的函数不同。

| 迷你应用类型 | 函数                  | 说明                 |
| ------ | ------------------- | ------------------ |
| 游戏     | `getUserKeyForGame` | 返回游戏迷你应用专用的用户识别键。  |
| 非游戏    | `getAnonymousKey`   | 返回非游戏迷你应用专用的用户识别键。 |

这两个函数都能在无需服务器联动的情况下识别用户的 **唯一键值（hash）** 并返回。返回的用户识别符按迷你应用分别唯一。

{% hint style="info" %}
**请务必确认**

* 唯一键值（`hash`）的值在同一迷你应用内，对同一用户始终返回相同的值。
* 各函数只能在对应类别的迷你应用中使用。在错误的类别中调用会发生错误。
* 在沙盒中会返回 mock 数据，请通过二维码进行测试。
  {% endhint %}

***

### 游戏迷你应用

**SDK 函数：** `getUserKeyForGame`

`getUserKeyForGame`是用于在游戏迷你应用中识别用户的专用 API。像 Toss 登录一样，无需单独的认证页面或服务器联动，就能直接在游戏迷你应用内部获取唯一的用户识别符。

此函数 **仅可在游戏类别迷你应用中使用**，并且返回的用户识别符（`hash`） **按迷你应用（游戏）分别唯一**。此值可用于游戏内数据存储、排行榜管理等。

{% hint style="info" %}
**请注意**

* 此函数 **仅可在游戏类别迷你应用中使用**。如果在非游戏迷你应用中调用， `'INVALID_CATEGORY'`会返回。
* **仅支持 Toss 应用 5.232.0 及以上版本**。低于该版本时， `undefined`会返回。
* 为了稳定地向所有用户提供识别符 **游戏迷你应用的最低支持 Toss 应用版本已提升至 5.232.0**。
  * 低于支持版本时，进入迷你应用会显示更新提示页面。
* 返回的用户键不是 **用于调用 Toss 服务器 API 的键。**
  * 请仅用于游戏公司内部用户识别和数据管理。
* 在沙盒环境中， **mock 数据**会返回。实际行为请通过二维码在 Toss 应用中测试。
  {% endhint %}

**签名**

```typescript
function getUserKeyForGame(): Promise<GetUserKeyForGameSuccessResponse | 'INVALID_CATEGORY' | 'ERROR' | undefined>;
```

**返回值**

* `Promise<GetUserKeyForGameSuccessResponse | 'INVALID\_CATEGORY' | 'ERROR' | undefined>`

  返回用户键查询结果。
* `GetUserKeyForGameSuccessResponse`：用户键查询成功。 `{ type: 'HASH', hash: string }` 以该形式返回。
  * `hash` 该值是仅在对应游戏迷你应用中有效的用户识别符。
* `'INVALID_CATEGORY'`：在非游戏类别的迷你应用中调用了。
* `'ERROR'`：发生了未知错误。
* `undefined`：应用版本低于最低支持版本。

**示例：获取游戏用户识别符**

下面的示例展示了在游戏迷你应用中 `getUserKeyForGame`调用并接收用户识别符进行处理的基本流程。

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

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

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

  if (!result) {
    console.warn('不支持的应用版本。');
  } else if (result === 'INVALID_CATEGORY') {
    console.error('不是游戏类别的迷你应用。');
  } else if (result === 'ERROR') {
    console.error('查询用户键时发生错误。');
  } else if (result.type === 'HASH') {
    console.log('用户键：', result.hash);
    // 可以在这里使用用户键来管理游戏数据。
  }
}
```

{% endtab %}

{% tab title="React" %}

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

function GameUserKeyButton() {
  async function handleClick() {
    const result = await getUserKeyForGame();

    if (!result) {
      console.warn('不支持的应用版本。');
      return;
    }

    if (result === 'INVALID_CATEGORY') {
      console.error('不是游戏类别的迷你应用。');
      return;
    }

    if (result === 'ERROR') {
      console.error('查询用户键时发生错误。');
      return;
    }

    if (result.type === 'HASH') {
      console.log('用户键：', result.hash);
      // 可以在这里使用用户键来管理游戏数据。
    }
  }

  return <button onClick={handleClick}>获取用户键</button>;
}
```

{% endtab %}

{% tab title="React Native" %}

```tsx
import { Button } from 'react-native';
import { getUserKeyForGame } from '@apps-in-toss/framework';

function GameUserKeyButton() {
  async function handlePress() {
    const result = await getUserKeyForGame();

    if (!result) {
      console.warn('不支持的应用版本。');
      return;
    }

    if (result === 'INVALID_CATEGORY') {
      console.error('不是游戏类别的迷你应用。');
      return;
    }

    if (result === 'ERROR') {
      console.error('查询用户键时发生错误。');
      return;
    }

    if (result.type === 'HASH') {
      console.log('用户键：', result.hash);
      // 可以在这里使用用户键来管理游戏数据。
    }
  }

  return <Button onPress={handlePress} title="获取用户键" />;
}
```

{% endtab %}
{% endtabs %}

**参考事项**

* `getUserKeyForGame`是游戏迷你应用专用的登录/识别手段。
* Toss 登录（`appLogin`）不同，即使不联动服务器 API 也能使用。
* 建议以该用户键为基准管理游戏用户数据（排行榜、积分、存档数据等）。

***

### 非游戏迷你应用

**SDK 函数：** `getAnonymousKey`

`getAnonymousKey`是用于在非游戏迷你应用中识别用户的 API。像 Toss 登录一样，无需单独的认证页面或服务器联动，就能直接在迷你应用内部获取唯一的用户识别符。

此函数 **仅可在非游戏类别的迷你应用中使用**，并且返回的用户识别符（`hash`） **按迷你应用分别唯一**。

{% hint style="info" %}
**请注意**

* 此函数 **仅可在非游戏类别的迷你应用中使用**。如果在游戏迷你应用中调用， `'INVALID_CATEGORY'`会返回。
* **SDK 2.4.5 及以上**支持。低于该版本时， `undefined`会返回。
* 返回的用户键不是 **用于调用 Toss 服务器 API 的键。**
  * 请仅用于内部用户识别和数据管理。
* 在沙盒环境中， **mock 数据**会返回。实际行为请通过二维码在 Toss 应用中测试。
  {% endhint %}

**签名**

```typescript
function getAnonymousKey(): Promise<GetAnonymousKeySuccessResponse | 'INVALID_CATEGORY' | 'ERROR' | undefined>;
```

**返回值**

* `Promise<GetAnonymousKeySuccessResponse | 'INVALID\_CATEGORY' | 'ERROR' | undefined>`

  返回用户键查询结果。
* `GetAnonymousKeySuccessResponse`：用户键查询成功。 `{ type: 'HASH', hash: string }` 以该形式返回。
  * `hash` 该值是仅在对应迷你应用中有效的用户识别符。
* `'INVALID_CATEGORY'`：在非游戏类别之外的迷你应用中调用了。
* `'ERROR'`：发生了未知错误。
* `undefined`：SDK 版本低于最低支持版本。

**示例：获取用户识别符**

下面的示例展示了在非游戏迷你应用中 `getAnonymousKey`调用并接收用户识别符进行处理的基本流程。

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

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

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

  if (!result) {
    console.warn('不支持的 SDK 版本。');
  } else if (result === 'INVALID_CATEGORY') {
    console.error('不是非游戏类别的迷你应用。');
  } else if (result === 'ERROR') {
    console.error('查询用户键时发生错误。');
  } else if (result.type === 'HASH') {
    console.log('用户键：', result.hash);
    // 可以在这里使用用户键来管理数据。
  }
}
```

{% endtab %}

{% tab title="React" %}

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

function UserKeyButton() {
  async function handleClick() {
    const result = await getAnonymousKey();

    if (!result) {
      console.warn('不支持的 SDK 版本。');
      return;
    }

    if (result === 'INVALID_CATEGORY') {
      console.error('不是非游戏类别的迷你应用。');
      return;
    }

    if (result === 'ERROR') {
      console.error('查询用户键时发生错误。');
      return;
    }

    if (result.type === 'HASH') {
      console.log('用户键：', result.hash);
      // 可以在这里使用用户键来管理数据。
    }
  }

  return <button onClick={handleClick}>获取用户键</button>;
}
```

{% endtab %}

{% tab title="React Native" %}

```tsx
import { Button } from 'react-native';
import { getAnonymousKey } from '@apps-in-toss/framework';

function UserKeyButton() {
  async function handlePress() {
    const result = await getAnonymousKey();

    if (!result) {
      console.warn('不支持的 SDK 版本。');
      return;
    }

    if (result === 'INVALID_CATEGORY') {
      console.error('不是非游戏类别的迷你应用。');
      return;
    }

    if (result === 'ERROR') {
      console.error('查询用户键时发生错误。');
      return;
    }

    if (result.type === 'HASH') {
      console.log('用户键：', result.hash);
      // 可以在这里使用用户键来管理数据。
    }
  }

  return <Button onPress={handlePress} title="获取用户键" />;
}
```

{% endtab %}
{% endtabs %}

**参考事项**

* `getAnonymousKey`是非游戏迷你应用专用的用户识别手段。
* Toss 登录（`appLogin`）不同，即使不联动服务器 API 也能使用。
* 建议以该用户键为基准管理用户数据。

***

### 验证识别键

用于验证用户识别键是否有效。

**基本信息**

| 项目           | 值                                  |
| ------------ | ---------------------------------- |
| Base URL     | `https://apps-in-toss-api.toss.im` |
| 服务器认证        | mTLS（客户端证书）                        |
| Content-Type | `application/json`                 |

{% hint style="info" %}
**服务器间通信需要 mTLS 证书**

识别键验证 API 是从合作伙伴服务器调用 Apps in Toss 服务器的服务器间通信。为了安全，请先在服务器上配置 mTLS 证书后再调用。证书发放方法请参考 [mTLS 证书发放方法](https://developers-apps-in-toss.toss.im/documentation/integration/getting-started)。
{% endhint %}

* Method: `POST`
* Endpoint: `/api-partner/v1/apps-in-toss/users/anon-key/verify`

**请求头**

| 名称           | 类型     | 必填 | 说明                                                                                                            |
| ------------ | ------ | -- | ------------------------------------------------------------------------------------------------------------- |
| `x-anon-key` | string | Y  | [用户识别键发放](https://developers-apps-in-toss.toss.im/documentation/common/authentication/hash-key)中获得的 `hash` 值。 |

```bash
curl -X 'POST' \\
  'https://apps-in-toss-api.toss.im/api-partner/v1/apps-in-toss/users/anon-key/verify' \\
  -H 'accept: application/json' \\
  -H 'x-anon-key: anon-key' \\
  -d ''
```

**响应参数**

| 名称      | 类型     | 说明                                  |
| ------- | ------ | ----------------------------------- |
| success | string | 表示识别键是否有效。有效时， `"true"`；无效时会返回错误响应。 |

```json
{
  "resultType": "SUCCESS",
  "success": "true"
}
```

**错误代码**

这是 API 使用过程中可能发生的错误代码列表。请参考响应代码或消息， **适当的异常处理逻辑**并应用。

| 代码    | 消息                 |
| ----- | ------------------ |
| `401` | 没有用户识别键，或找不到已映射的用户 |


---

# 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://developers-apps-in-toss.toss.im/documentation/api-and-sdk-zh/common/authentication/hash-key.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.
