Skip to content

第三方对接指南

本文档面向需要将 IM 系统集成到现有应用中的开发者。

集成方式概览

IM 系统提供三种集成方式:

方式适用场景复杂度
REST API后端服务集成、数据同步
WebSocket实时消息收发
管理后台 API后台管理系统对接

后端服务集成

认证对接

IM 使用独立的认证体系。对接时需要:

  1. 用户在 IM 后端注册或登录获取 JWT
  2. 后续所有请求携带 JWT
javascript
// 登录获取 Token
const response = await fetch('https://chat.example.com/api/login', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    username: 'alice',
    password: 'password123'
  })
});
const { data } = await response.json();
const token = data.token;

消息发送

可通过 HTTP API 或 WebSocket 发送消息:

HTTP 方式(适合服务端推送通知):

javascript
await fetch('https://chat.example.com/api/message/send', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${token}`
  },
  body: JSON.stringify({
    id: generateUUID(),
    fromId: 'bot_user',
    toId: 'target_user',
    chatType: 'single',
    content: '系统通知:您的订单已发货',
    contentType: 'text'
  })
});

WebSocket 方式(适合实时聊天):参考 WebSocket 连接文档

管理后台对接

管理后台 API 使用 API Key 认证,适合开发管理面板、数据看板等。

bash
# 获取所有用户
curl -H "Authorization: Bearer YOUR_API_KEY" \
     https://chat.example.com/api/admin/users

# 获取聊天记录
curl -H "Authorization: Bearer YOUR_API_KEY" \
     "https://chat.example.com/api/admin/history?type=single&toId=user_b&fromId=user_a"

# 创建群聊
curl -X POST \
     -H "Authorization: Bearer YOUR_API_KEY" \
     -H "Content-Type: application/json" \
     -d '{"id":"group_001","name":"客服群","creatorId":"admin_user"}' \
     https://chat.example.com/api/admin/group/create

Webhook 集成(扩展)

可在服务端添加 Webhook 中间件,将特定事件转发到第三方系统:

javascript
// 示例:消息事件转发到企业微信
app.post('/api/webhook/wechat', (req, res) => {
  const { event, data } = req.body;
  
  if (event === 'new_message') {
    // 转发到企业微信机器人
    fetch('https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxx', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        msgtype: 'text',
        text: { content: `[IM消息] ${data.fromName}: ${data.content}` }
      })
    });
  }
  
  res.json({ code: 200 });
});

数据库直接对接

IM 使用 SQLite 数据库文件,在只读模式下可直接被其他系统读取:

注意

直接读取数据库时请确保不会写入,避免数据不一致。建议通过 REST API 进行写操作。

常见问题

Q: 如何与现有用户体系打通?

方案一:用户首次登录 IM 时自动注册(通过管理 API 创建用户) 方案二:在现有系统登录成功后,调用 IM 后端 /api/login 获取 JWT,前端存储后使用

Q: 支持多少并发用户?

SQLite + sql.js 方案适合中小规模使用(数百并发连接)。如需更大规模,建议将存储层替换为 MySQL/PostgreSQL/Redis。