Skip to content

Web 从零接入雁帛IM ​

本页面向普通浏览器网站。完成后,你可以用两个测试账号连接同一个 XHIM Server, 发送并接收第一条文字消息。

如果你的应用由 Electron 打包,请改看 Electron 接入。

1. 准备接入信息 ​

向服务端负责人领取:

text
Server URL       例如 https://im-test.example.com
App ID           例如 xhim-demo
当前用户 ID      例如 alice
对端用户 ID      例如 bob

本地开发网址和正式网址还需要加入服务端允许的 Origin。正式环境使用 HTTPS/WSS, 不要把管理员密钥、数据库密码或长期访问令牌放进网页。

2. 安装 SDK ​

当前源码包标记为 0.1.0-alpha.1,按开发预览范围交付。先领取已发布的私有 npm 源或 npm tarball,不能假定已经在公共 npm 可下载。私有源登记后精确锁定:

bash
npm install --save-exact @xihansoftware/xhim-web@0.1.0-alpha.1

本包是标准 ESM 包,可用于原生 TypeScript、React、Vue 或 Svelte 项目。

3. 连接当前账号 ​

Development Server 已开启测试登录时,可以直接使用开发凭证提供器:

ts
import {
  XHIMWebClient,
  XHIMIndexedDBProjectionStore,
  createXHIMDevelopmentCredentialProvider
} from '@xihansoftware/xhim-web'

const server = 'https://im-test.example.com'
const appId = 'xhim-demo'
const currentUserId = 'alice'

const client = await XHIMWebClient.connect({
  server,
  appId,
  projectionStore: new XHIMIndexedDBProjectionStore(),
  accountHint: currentUserId,
  credentialProvider: createXHIMDevelopmentCredentialProvider({
    server,
    appId,
    userId: currentUserId,
    deviceId: `web-${currentUserId}`
  })
})

正式环境把 credentialProvider 换成应用自己的后台接口:

ts
const client = await XHIMWebClient.connect({
  server: 'https://im.example.com',
  appId: 'your-app',
  projectionStore: new XHIMIndexedDBProjectionStore(),
  accountHint: signedInUser.id,
  credentialProvider: async ({ forceRefresh }) => {
    const response = await fetch('/api/im/credential', {
      method: 'POST',
      credentials: 'include',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ forceRefresh })
    })
    if (!response.ok) throw new Error('当前账号无法登录 IM')
    const session = await response.json()
    return {
      accessToken: session.accessToken,
      expiresAtMs: session.expiresAtMs
    }
  }
})

凭证只交给 SDK,不写入 localStorage、URL 或日志。

4. 监听连接和数据变化 ​

连接返回后立即注册监听,并读取 client.state。只有 connected 才开始在线业务 查询/发送;Promise 完成时 WSS 可能仍在连接。页面以状态控制操作,不用固定延时。 收到 sync 后重新查询当前会话或消息列表, 不要在页面里自己拼一份 IM 数据库。

ts
const stopState = client.on('stateChanged', ({ current }) => {
  accountStore.setConnected(current === 'connected')
})

const stopSync = client.on('sync', () => {
  conversationStore.reload()
})

const stopError = client.on('error', (error) => {
  console.error(error.code, error.message)
})

注册完上面的监听后,调用 accountStore.setConnected(client.state === 'connected') 读取初始状态。accountStore 和 conversationStore 是宿主账号/UI 层;前者控制发送按钮,后者在就绪时查询数据。 本页显式安装 IndexedDB Projection Store;缺少 Projection 的本地查询会失败,不能 自动当成 HTTP 查询。只在浏览器初始化;SSR 在客户端生命周期中创建 Client。

5. 发送第一条消息 ​

ts
const conversation = await client.getOrCreateDirectConversation('bob')

const sent = await client.sendText(
  conversation.conversationId,
  '你好,雁帛IM'
)

console.log('服务端消息 ID:', sent.serverMessageId)

让 Bob 使用同一个 Server URL 和 App ID 登录。Bob 收到 sync 后重新查询该会话, 即可看到消息。

6. 在 React 或 Vue 中管理 Client ​

每个已登录账号只创建一个 XHIMWebClient。把它放在账号级 Service 或 Store, 组件只注册和取消自己的监听。

ts
// 组件卸载
stopState()
stopSync()
stopError()

// 用户真正登出或切换账号
client.disconnect()

关闭一个聊天页面时不要断开整个账号;只有登出或换号时才调用 disconnect()。

7. 常用功能入口 ​

任务方法
查询消息历史client.getMessageHistory(...)
标记会话已读client.markConversationRead(...)
发送业务消息client.sendCustomMessage(...)
查询在线状态client.queryPresence(...)
订阅输入状态client.on('typing', ...)
查询用户资料client.getUserProfiles(...)
创建群client.createGroup(...)
取消长查询传入 AbortSignal

每个公开方法的参数、返回值、错误和 Web 示例见 SDK API Reference。

8. 运行 Demo ​

Web Demo 应用源码已迁出联调仓库,位于独立仓库 xhim-web-app (https://git.xihansoftware.com/laowang/xhim-web-app),不随本仓库交付:

bash
git clone git@git.xihansoftware.com:laowang/xhim-web-app.git
cd xhim-web-app
npm install
npm run dev

打开两个无痕窗口,分别登录 Alice 和 Bob。先验证文字消息,再继续接群组、媒体、 Presence、Typing 和自定义消息。

9. 常见问题 ​

浏览器提示跨域 ​

把当前网页的精确 Origin 加入服务端允许列表。不要用 * 代替正式域名。

登录成功但收不到新消息 ​

确认页面保留了 sync 监听,并在收到通知后重新查询当前会话。

页面刷新后数据为空 ​

为正式项目配置账号隔离的 XHIMIndexedDBProjectionStore;不要自己解码或改写 SDK 的同步游标。

Web 和 Electron 包能否混用 ​

不能。浏览器使用 @xihansoftware/xhim-web,Electron 使用 @xihansoftware/xhim-electron。

版本与发布边界 ​

业务接口 /api/im/credential 是宿主后台实现的示例路由,返回 SDK 的驼峰字段; 不要直接返回 Server API 的 snake_case JSON。正式设备身份、续期和撤销合同见 账号认证。浏览器当前没有原生 MLS Provider, Outbox/文件与原生存在边界,见 SDK 版本与能力。 上线验证浏览器、IndexedDB、Origin 白名单、WSS、前后台、业务会话过期和换号。

XHIM 客户端 SDK 与服务端文档