> For the complete documentation index, see [llms.txt](https://docs.convai.com/api-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-pixel-streaming-embed/authorize-embeds-with-an-auth-token.md).

# 使用认证令牌授权嵌入

在你的服务器上签发一个 Convai 身份验证令牌，并将其传递给嵌入组件，这样你的体验就可以在任何来源上运行，包括 localhost，而无需加入允许列表。

使用短时有效的 Convai 身份验证令牌授权 Pixel Streaming 嵌入，而不是使用域名允许列表。当你将 `@convai/experience-embed` 添加到有后端的网站，或想在 `localhost`上运行嵌入时，请参阅此页面。完成后，你的体验无需向 Convai 发送请求，即可在任何来源上进行流式传输。

### 前提条件

* 已发布的体验及其 `expId`。请参阅 [发布体验并进行授权](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-pixel-streaming-embed/whitelisting-and-publishing-an-experience.md).
* 你的 Convai API 密钥，位于 `<code class="expression">space.vars.dashboard_url</code>`.
* `@convai/experience-embed` 版本 `0.7.0` 或更高版本。
* 你可控制的服务器端路由，例如 Express 路由、Next.js 路由处理程序或无服务器函数。

### 身份验证令牌如何授权会话

你的服务器使用 API 密钥生成令牌。页面从你的服务器获取令牌，并将其作为 `authToken`传递给嵌入。嵌入在启动会话时将令牌作为 `API-AUTH-TOKEN` 标头发送，因此 Convai 会根据令牌而不是页面的域名授权会话。

```mermaid
sequenceDiagram
    participant Server as Your server
    participant Page as Your page
    participant Convai
    Server->>Convai: POST /user/connect (CONVAI-API-KEY)
    Convai-->>Server: apiAuthToken, expirationTime
    Page->>Server: GET /api/convai-token
    Server-->>Page: token
    Page->>Convai: Start session (API-AUTH-TOKEN)
    Convai-->>Page: Stream
```

令牌只会在会话启动时进行检查。令牌过期后，流仍会继续运行。

### 在服务器上生成令牌

发送 `POST https://api.convai.com/user/connect` ，并在 `CONVAI-API-KEY` 标头中附上你的 API 密钥。响应包含 `apiAuthToken` 和 `expirationTime`。每个令牌的有效期为 60 分钟。

`expirationTime` 采用 UTC 时间，但不带时区后缀，例如 `2026-10-01T10:15:00.123456`。请将其解析为 UTC 时间。JavaScript 的 `Date.parse` 会将不带后缀的时间戳视为本地时间。

令牌生成会受到 API 密钥级别的速率限制，限制额度取决于你的套餐。在服务器上缓存一个令牌，并在其即将过期前重复使用，而不是每次页面浏览都生成新令牌。

{% code title="server.js" lineNumbers="true" %}

```javascript
// 将 CONVAI_API_KEY 保存在服务器环境中。切勿将其发送到浏览器。
let cached = null; // { token, expiresAt }

// expirationTime 是不带 "Z" 的 UTC 时间。
const parseUtc = (t) => Date.parse(/[zZ]|[+-]\d\d:?\d\d$/.test(t) ? t : `${t}Z`);

app.get("/api/convai-token", async (req, res) => {
  // 缓存的令牌在过期前 5 分钟内继续复用。
  if (!cached || cached.expiresAt - Date.now() < 5 * 60 * 1000) {
    const r = await fetch("https://api.convai.com/user/connect", {
      method: "POST",
      headers: {
        "CONVAI-API-KEY": process.env.CONVAI_API_KEY,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({}),
    });
    if (!r.ok) return res.status(502).json({ error: "could not mint token" });
    const { apiAuthToken, expirationTime } = await r.json();
    cached = { token: apiAuthToken, expiresAt: parseUtc(expirationTime) };
  }
  res.json({ token: cached.token });
});
```

{% endcode %}

{% hint style="danger" %}
仅在服务器上生成令牌。任何持有你的 API 密钥的人都能完全访问你的账户 API，因此切勿将密钥放入页面代码、客户端构建产物或公开代码库中。如果体验不能公开访问，请在令牌路由前添加你自己的登录验证或速率限制。
{% endhint %}

### 将令牌传递给嵌入组件

创建嵌入组件前先获取令牌，然后将其作为 `authToken`.

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

```tsx
import { useEffect, useRef, useState } from "react";
import {
  PixelStreamComponent,
  PixelStreamComponentHandles,
} from "@convai/experience-embed";

export function Experience() {
  const pixelStreamRef = useRef<PixelStreamComponentHandles>(null);
  const [token, setToken] = useState<string>();

  useEffect(() => {
    fetch("/api/convai-token")
      .then((r) => r.json())
      .then(({ token }) => setToken(token));
  }, []);

  return token ? (
    <PixelStreamComponent
      ref={pixelStreamRef}
      expId="your-experience-id"
      authToken={token}
    />
  ) : (
    <div>Loading…</div>
  );
}
```

{% endtab %}

{% tab title="原生 JavaScript" %}

```javascript
import { PixelStreamClient } from "@convai/experience-embed";

const { token } = await fetch("/api/convai-token").then((r) => r.json());

const pixelStream = new PixelStreamClient({
  container: document.getElementById("pixel-stream-container"),
  expId: "your-experience-id",
  authToken: token,
});
```

{% endtab %}

{% tab title="CDN" %}

```html
<div id="pixel-stream-container" style="width: 100%; height: 600px;"></div>
<script src="https://unpkg.com/@convai/experience-embed/dist/core/convai-embed.umd.js"></script>
<script>
  fetch("/api/convai-token")
    .then((r) => r.json())
    .then(({ token }) => {
      window.pixelStream = new PixelStreamCore.PixelStreamClient({
        container: document.getElementById("pixel-stream-container"),
        expId: "your-experience-id",
        authToken: token,
      });
    });
</script>
```

{% endtab %}
{% endtabs %}

在整个会话期间保持 `authToken` 稳定。在 React 中，新 `authToken` 值会开启一个新会话，就像新的 `expId` 或 `endUserId`一样。开始下一个会话时获取新令牌，例如在下一次加载页面时获取。

本地开发使用相同的流程。在本地运行令牌路由，嵌入内容即可在 `http://localhost` 上进行流式传输，无需加入允许列表。

### 验证会话

加载页面并启动体验。在浏览器的开发者工具中， `viewPublishedExperience` 请求会携带 `API-AUTH-TOKEN` 标头，并返回 HTTP `200`.

{% hint style="success" %}
体验会在页面上进行流式传输，即使页面来源不在账户的允许列表中也一样，例如 `http://localhost:3000`.
{% endhint %}

### 故障排查

#### 嵌入内容提示令牌无效或已过期

**症状：** 嵌入内容显示 `This experience couldn't start: the Convai auth token is invalid or has expired.`

**原因：** 会话启动时，Convai 拒绝了令牌。令牌已过期或输入有误。

**修复方法：** 在服务器上签发新令牌，并使用该令牌重新挂载嵌入内容。检查服务器是否会复用缓存的令牌，且仅在距 `expirationTime`临近时才停止复用；该时间按 UTC 解析。

**验证：** 该 `viewPublishedExperience` 请求返回 HTTP `200` ，且体验能够流式传输。

#### 嵌入内容提示你将域名加入白名单

**症状：** 嵌入内容显示 `Please contact convai to get <your origin> whitelisted!`

**原因：** 嵌入内容未携带令牌便启动了会话，因此 Convai 检查了页面域名是否在允许列表中。 `authToken` 未传入，或传入的是空字符串。

**修复方法：** 将令牌作为 `authToken`传入，并在令牌加载完成后再创建嵌入内容。

**验证：** 该 `viewPublishedExperience` 请求携带了 `API-AUTH-TOKEN` 标头。

#### 令牌路由无法生成令牌

**症状：** `POST /user/connect` 请求失败，响应消息为 `Api key is invalid.` 或 `You've reached your request limit per minute`.

**原因：** 中的 API 密钥 `CONVAI-API-KEY` 不正确，或者服务器每分钟生成的令牌数超出了套餐限制。

**修复方法：** 检查服务器环境中的 API 密钥。缓存一个令牌，并在它即将过期前重复使用，而不是每次页面浏览都生成一个新令牌。

**验证：** `POST /user/connect` 返回 HTTP `200` ，其中包含 `apiAuthToken` 和 `expirationTime`.

### 后续步骤

API 参考文档将 `authToken` 与嵌入内容的其他属性和选项一同列出。

{% content-ref url="/pages/87b57936662c69d8802f20f500191b181163cf02" %}
[Pixel Streaming Embed API 参考](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-pixel-streaming-embed/api-reference.md)
{% endcontent-ref %}


---

# 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://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-pixel-streaming-embed/authorize-embeds-with-an-auth-token.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.
