Skip to content

Web / H5 接入

Web / H5 使用 KFVisitor Widget 快速在页面中加入咨询入口。它会创建悬浮聊天页或新窗口,并由系统处理访客页加载、实时连接和未读提示。

快速接入

在页面中加载 kf.js,再初始化一次 KFVisitor

html
<script src="https://<客服系统域名>/static/js/kf.js"></script>
<script>
  window.kfVisitor = KFVisitor.init({
    businessId: '<商户 ID>',
    groupId: 0,
    baseUrl: 'https://<客服系统域名>',
    displayMode: 'floating',
    channel: '官网咨询',
    auth: async () => {
      const response = await fetch('/api/current-user/customer-service-token', {
        credentials: 'include'
      })
      const data = await response.json()
      return data.visitor_token
    },
    visitor: {
      nickname: '当前用户显示名',
      avatar: 'https://example.com/avatar.png'
    },
    contexts: []
  })
</script>

初始化一次

同一页面只能调用一次 KFVisitor.init()。在 SPA 中请将初始化放到应用启动阶段,并使用返回实例的方法更新上下文或打开、关闭窗口。

配置项

字段必填说明
businessId商户 ID。
groupId客服分组 ID;默认 0
baseUrl客服系统地址;未传时使用 kf.js 脚本所在域名。
displayModefloating 为页面浮层,window 为独立窗口;默认 floating
auth推荐返回访客 Token 的函数,或包含 getToken() 的对象。正式环境应使用。
channel客服可见的业务来源,最多 32 个字符。
visitor显示名称、头像与扩展属性。
contexts当前商品、订单等咨询上下文。
theme.primaryColor主题色。
launcher自定义入口元素、未读角标和消息预览行为。

auth 函数只能向宿主自己的服务端取得 Token,不能在浏览器中使用商户 API Key。

打开与更新上下文

初始化结果提供打开、关闭和上下文同步方法:

js
// 在商品或订单详情页切换咨询上下文
window.kfVisitor.setContexts([
  {
    key: 'product:SKU-1001',
    type: 'product',
    title: '商品详情',
    fields: [{ key: 'price', label: '价格', value: '¥99' }]
  }
])

window.kfVisitor.open()

自定义界面

若不使用 Widget,请改用本文档的访客端 HTTP 接口WebSocket 连接与订阅。自定义界面必须自行处理身份、消息 mid 去重、断线重连、历史补拉、上传和已读状态。