> 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/unity/first-steps/getting-started.md).

# 开始使用

从安装 SDK 到启动第一个构建所需的内容，已按顺序整理为最必要的部分。

使用 Apps in Toss Unity SDK，无需单独配置 Vite 项目或实现 JS Bridge，就可以将 Unity 项目移植为迷你应用。加载画面已默认包含在 SDK 中，到首次交互为止的耗时、帧停顿、错误·异常、内存警告等运行时事件会在无需用户代码的情况下自动收集（详情请参见 [SDK事件日志记录](https://developers-apps-in-toss.toss.im/documentation/unity/add-features/metrics) 注）。

### 安装 SDK

#### 通过 Package Manager 安装

1. 在 Unity Editor 中 `Window` > `Package Manager` 打开
2. 左上角 `+` 按钮点击
3. `Add package from git URL...` 选择
4. 输入 Git URL：

```
https://github.com/toss/apps-in-toss-unity-sdk.git#release/v3.0.3
```

#### 直接修改 manifest.json

项目的 `Packages/manifest.json`中添加依赖项。

```json
{
  "dependencies": {
    "im.toss.apps-in-toss-unity-sdk": "https://github.com/toss/apps-in-toss-unity-sdk.git#release/v3.0.3"
  }
}
```

#### 支持的 Unity 版本

至少需要 Unity 2021.3，推荐 Unity 6 或更高版本。支持 2021.3 之后的所有版本。

### SDK 组成

Apps in Toss Unity SDK 提供了两层，以便在 WebGL 环境中使用平台 API。

* **C# API 层** (`Runtime/SDK/`）— `AIT.*` 以 C# 方法形式封装平台 API。内部通过 `DllImport("__Internal")`，在 WebGL 构建时与 JS 函数连接。
* **JS Bridge** (`.jslib`）— 在 C# 中调用的 JS 函数已定义，实际与 Apps in Toss WebView SDK 通信的逻辑在这里。

这两层都已包含在 SDK 中，因此无需自行编写代码。

### 安装 ref 管理

URL 末尾的 `#...` 部分是 **安装 ref**。UPM 会原样获取该 ref 指向的提交，因此这里写什么，实际上就决定了“何时以及如何更新”。

#### 选择 ref

| ref 形式  | 示例                    | 行为                              |
| ------- | --------------------- | ------------------------------- |
| 不可变发布标签 | `#release/vX.Y.Z`     | 固定到特定提交。保证可复现构建，并隔离意外更新         |
| 分支      | `#main`               | 每次 HEAD 移动时，自动更新器都会检测到变更并显示更新提示 |
| 预发布渠道   | `#beta`, `#beta-perf` | 可移动分支。不会弹出自动更新提示，需要手动管理         |

> **建议**：服务部署请使用不可变发布标签。可用标签请参见 [GitHub Releases](https://github.com/toss/apps-in-toss-unity-sdk/releases)中查看。

预发布渠道仅向事先协商的试点对象说明。 [Beta 渠道](https://github.com/toss/apps-in-toss-unity-sdk/blob/main/Documentation~/BetaChannel.md)和 [perf Beta 渠道](https://github.com/toss/apps-in-toss-unity-sdk/blob/main/Documentation~/PerfBetaChannel.md)。

#### 将可移动 ref 重新拉取到最新

UPM 会将 git 依赖 `Packages/packages-lock.json`中 **锁定为提交哈希。** 所以 `#main`即使像这样把 ref pin 到可移动 ref，仅仅重新打开 Unity 也不会更新。必须通过以下两种方式之一解除锁定。

* **从 Package Manager 中移除后重新添加** — 删除包并使用相同 URL 再次添加，ref 会重新解析。最简单。
* **解除锁定** — `Packages/packages-lock.json`在 `im.toss.apps-in-toss-unity-sdk` 条目的 `"hash"` 值并保存后，Unity 会重新解析 ref。

#### 移动到其他 ref

`Packages/manifest.json`中只更改 URL 的 fragment 并保存。只要依赖字符串发生变化，UPM 就会从头重新解析该包，因此这种情况下不需要进行上述解锁。

* 试点参与： `#release/vX.Y.Z` → `#beta` 或 `#beta-perf`
* 恢复 stable： `#beta` → `#release/vX.Y.Z`

恢复为不可变发布标签后，自动更新器会再次追踪该 stable ref。

### 设置

安装 SDK 后，在 Unity Editor 菜单中 `AIT` > `Configuration`点击以打开设置窗口。

| 设置         | 说明                                                            |
| ---------- | ------------------------------------------------------------- |
| **应用 ID**  | 从 Apps in Toss 平台获取的应用 ID。只能使用英文字母、数字和连字符，在设置窗口中 `*`显示为唯一的必填项 |
| **显示名称**   | 加载画面中显示的应用名称                                                  |
| **版本**     | `x.y.z` 格式                                                    |
| **主色调**    | 品牌颜色。用于进度条等                                                   |
| **图标 URL** | 将显示为迷你应用图标的图片 URL。输入时 `http://` 或 `https://`必须以               |

### AIT 菜单

SDK 安装完成后，Unity Editor 顶部会添加 `AIT` 菜单。

| 菜单                       | 说明                                                                                                                                   |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------ |
| **Dev Server**           | 下有 Start / Stop / Restart Server / Restart Server (server-only)。 `server-only`仅重启服务器，无需重新构建                                          |
| **Production Server**    | 下有 Start / Stop / Restart Server / Restart Server (server-only)。 `server-only`仅重启服务器，无需重新构建                                          |
| **Build & Package**      | WebGL 构建和 `.ait` 打包会一次性执行                                                                                                            |
| **Publish**              | 生成的 `.ait` 文件上传到 Apps in Toss 平台。 `Configuration`中必须已设置部署密钥                                                                          |
| **Clean**                | `webgl/`, `ait-build/` 删除构建产物文件夹                                                                                                     |
| **Open Build Output**    | 打开保存构建产物的文件夹                                                                                                                         |
| **重置加载画面**               | 将加载画面恢复为 SDK 默认模板。详情请参见 [加载画面自定义](https://developers-apps-in-toss.toss.im/documentation/unity/build/loading-screen-customization) 参考 |
| **Configuration**        | 打开迷你应用联动设置窗口，如应用 ID、显示名称等                                                                                                            |
| **Install Sentry SDK**   | 安装 Sentry Unity SDK。详情请参见 [Sentry集成](https://developers-apps-in-toss.toss.im/documentation/unity/add-features/sentry-integration) 参考 |
| **报告问题**                 | 打开报告问题情况的窗口                                                                                                                          |
| **Check for Updates...** | 手动检查是否有新的 SDK 发布版本                                                                                                                   |
| **Debug**                | 汇集了用于调试的子菜单，如 SDK 状态初始化、强制刷新 WebGL 模板等                                                                                               |

Dev Server 与 Production Server，以及各构建配置文件的 devtools·压缩设置差异， [构建配置文件](https://developers-apps-in-toss.toss.im/documentation/unity/build/build-profiles)中有整理。

### 第一次构建

所有构建入口都在 `AIT` 菜单中。各入口分别如何以什么方式构建的差异， [构建配置文件](https://developers-apps-in-toss.toss.im/documentation/unity/build/build-profiles)中有整理。

#### 通过开发服务器确认

开发阶段使用 Dev Server。 `@apps-in-toss/devtools`Mock SDK 和面板会一起运行，可以在没有 toss 应用的浏览器中通过 mock 方式确认平台 API 调用，并可通过面板直接控制 mock 状态。

1. `AIT` > `Dev Server` > `Start Server` 点击
2. Unity WebGL 构建会自动执行
3. 构建结束后，本地开发服务器将启动
4. 浏览器会自动打开，或者访问控制台中显示的 URL

#### 制作发布用包

1. `AIT` > `Build & Package` 点击
2. 构建完成后 `ait-build/dist/`在其中查看结果物

#### 在真机上确认（Deploy Test）

要在真机上确认浏览器 Mock 无法验证的实际 Toss 应用环境（摄像头、支付、广告等），请使用 Deploy (Test)。

1. `AIT` > `Deploy (Test)` 点击
2. 必须已设置部署密钥。 `AIT` > `Configuration`在其中输入
3. 增量构建后 `ait deploy`会部署到控制台 QR 测试环境（memo 中 `[Test]` 会自动附加前缀）
4. 部署完成后，在弹出的窗口中用 Toss 应用扫描 QR 码，或通过 URL 访问，在真机上确认

#### 发布到平台（Deploy Production）

若要面向实际用户公开，需先用清理构建重新部署，然后在控制台申请审核。

1. `AIT` > `Deploy (Production)` 点击（与 Deploy (Test) 相同，但清理构建 + memo `[Production]` 前缀）
2. 部署完成后弹出的窗口中，点击“打开控制台”按钮即可跳转到 Apps in Toss 控制台
3. 在控制台中申请审核/发布刚刚部署的构建 — `ait deploy` Deploy 本身始终只会部署到控制台 QR 测试环境，实际发布仅通过该控制台流程完成

### SDK 使用示例

SDK API 使用 async/await 模式。 `Awaitable`和 `Task` 返回的是哪个、如何处理超时和错误代码，请参见 [API 使用模式](https://developers-apps-in-toss.toss.im/documentation/unity/first-steps/api-usage-patterns)中有整理。

#### 查询设备信息

```csharp
using AppsInToss;
using UnityEngine;

public class GameManager : MonoBehaviour
{
    async void Start()
    {
        try
        {
            // 查询设备 ID
            string deviceId = await AIT.GetDeviceId();
            Debug.Log($"Device ID: {deviceId}");

            // 查询平台 OS
            string os = await AIT.GetPlatformOS();
            Debug.Log($"平台：{os}");

            // 检查网络状态
            NetworkStatus status = await AIT.GetNetworkStatus();
            Debug.Log($"网络：{status}");
        }
        catch (AITException ex)
        {
            Debug.LogError($"API 调用失败：{ex.Message}（code: {ex.ErrorCode}）");
        }
    }
}
```

#### 支付请求

```csharp
using AppsInToss;
using UnityEngine;
using System.Threading.Tasks;

public class PaymentManager : MonoBehaviour
{
    public async Task RequestPayment()
    {
        try
        {
            var options = new CheckoutPaymentOptions {
                PayToken = "your-pay-token"
            };

            CheckoutPaymentResult result = await AIT.CheckoutPayment(options);
            Debug.Log($"Payment success: {result.Success}");
        }
        catch (AITException ex)
        {
            Debug.LogError($"支付失败：{ex.Message}");
        }
    }
}
```

> **重要**：应用内支付必须指定支付批准回调。如果不指定，所有支付都会被视为支付失败。 [API 使用模式](https://developers-apps-in-toss.toss.im/documentation/unity/first-steps/api-usage-patterns)请先阅读文档中的应用内支付部分。

#### 触觉反馈

```csharp
using AppsInToss;
using UnityEngine;

public class FeedbackManager : MonoBehaviour
{
    public async void VibrateDevice()
    {
        try
        {
            var options = new HapticFeedbackOptions {
                Type = HapticFeedbackType.Tap
            };

            await AIT.GenerateHapticFeedback(options);
            Debug.Log("已生成触觉反馈");
        }
        catch (AITException ex)
        {
            Debug.LogError($"触觉反馈失败：{ex.Message}");
        }
    }
}
```

### 测试

SDK API 只有在 WebGL 构建中才会真正通过桥接调用，而且即便如此也大多仅在 Apps in Toss 应用环境中正常工作。Unity Editor 里只会返回 Editor mock 的默认值。详情请参见 [API 使用模式](https://developers-apps-in-toss.toss.im/documentation/unity/first-steps/api-usage-patterns)的 **Mock** 部分。

通过沙盒应用确认本地构建的流程见 [问题排查](https://developers-apps-in-toss.toss.im/documentation/unity/first-steps/faq) 文档的“Dev Server 能用但 Production 不行”一节中有整理。

在最终发布前的验证中， `.ait` 使用文件上传测试。

1. `AIT` > `Build & Package`做 `.ait` 生成文件。
2. [Apps in Toss 控制台](https://apps-in-toss.toss.im/)上传到。
3. 通过 QR 码运行迷你应用进行确认。

如果遇到卡住的地方， [问题排查](https://developers-apps-in-toss.toss.im/documentation/unity/first-steps/faq) 文档。

### 相关文档

* [API 使用模式](https://developers-apps-in-toss.toss.im/documentation/unity/first-steps/api-usage-patterns) — async/await、错误处理、Mock
* [构建配置文件](https://developers-apps-in-toss.toss.im/documentation/unity/build/build-profiles) — 各构建入口的设置差异
* [构建自定义](https://developers-apps-in-toss.toss.im/documentation/unity/build/build-customization) — 修改 Web 入口、添加外部库
* [加载画面自定义](https://developers-apps-in-toss.toss.im/documentation/unity/build/loading-screen-customization) — 替换加载画面
* [问题排查](https://developers-apps-in-toss.toss.im/documentation/unity/first-steps/faq) — 常见卡点与解决方法


---

# 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/unity/first-steps/getting-started.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.
