API 参考
LiveSDK 类
Section titled “LiveSDK 类”new LiveSDK(config: SDKConfig): LiveSDK必填字段缺失时抛出异常:activityId、token、merchantId。
SDKConfig
Section titled “SDKConfig”interface SDKConfig { /** 直播间 ID */ activityId: string
/** JWT 访问令牌(由 auth 服务颁发) */ token: string
/** 商户 ID */ merchantId: string
/** BCP-47 locale 字符串,用于 UI 文案。默认 'zh-CN'。未知值警告后回退。 */ locale?: string
/** Phase 11:启用哪些 WS 驱动入口模块。默认全部启用。NEEDS-SERVER-VERIFY */ entryModules?: AppEntryModuleId[]
/** 腾讯 IM 配置(Phase 7) */ tim?: TIMConfig
/** @deprecated 改用 ws.url */ wsUrl?: string
/** LAPS WebSocket 配置(Phase 10)。未配置时降级为 HTTP 轮询。 */ ws?: WSConfig
/** 启用/禁用特定业务模块(默认全部启用) */ modules?: ModuleConfig[]
/** 内置 app 模块(ViewerCount / Like / Gift / Goods / Security)的开关 */ appModules?: AppModuleConfigs
/** 布局配置(横竖屏、Tab、模块顺序)*/ layout?: LayoutConfig
options?: SDKOptions}TIMConfig
Section titled “TIMConfig”interface TIMConfig { sdkAppId: number // 腾讯 IM App ID userId: string // 观众用户 ID userSig: string // 服务端生成的 UserSig groupId: string // 直播间 IM 群组 ID}注意:TIM 凭证由集成方通过环境变量或运行时注入,auth API 不返回这些字段。
WSConfig
Section titled “WSConfig”interface WSConfig { url: string // wss://your-laps-host/ws reconnectBaseDelay?: number // 重连基础延迟 ms(默认 1000) reconnectMaxDelay?: number // 重连最大延迟 ms(默认 30000) reconnectMaxAttempts?: number // 最大重连次数(默认 10) heartbeatInterval?: number // 心跳间隔 ms(默认 25000) authTimeout?: number // 认证超时 ms(默认 5000) loginRetryMax?: number // 认证重试次数(默认 3)}注意:WS 端点由集成方提供,auth API 不返回 WS URL。
SDKOptions
Section titled “SDKOptions”interface SDKOptions { origin?: string // HTTP API base URL saveUserInfo?: boolean logLevel?: 'silent' | 'error' | 'warn' | 'info' | 'debug' // 默认 'warn' /** 主题覆盖 — 仅传入字段覆盖 CSS 默认值 */ theme?: SDKTheme /** 运行时 i18n 字符串覆盖,叠加在 locale 基础字符串之上 */ i18n?: Partial<I18nMessages>}SDKTheme(全部可选)
Section titled “SDKTheme(全部可选)”interface SDKTheme { primaryColor?: string // 主色(按钮、高亮) backgroundColor?: string // 背景色 overlayColor?: string // 浮层背景色 chatBgColor?: string // 聊天区域背景色 textColor?: string // 文字颜色 fontFamily?: string // 字体族 fontSize?: string // 基础字号(如 '14px') radius?: string // 圆角(如 '8px')}CSS 变量以 --live-* 前缀注入,默认值定义在 .livesdk-root(app.css)中。
LayoutConfig
Section titled “LayoutConfig”interface LayoutConfig { /** * 方向控制。 * - 'portrait' | 'landscape' → 强制指定,忽略 API 返回值 * - 'auto'(默认)→ 读取 body.extendSet.screenType(1=横屏,2=竖屏) */ orientation?: 'portrait' | 'landscape' | 'auto' chatTabs?: { key: string; label: string }[] modulesOrder?: { chatOffset?: number }}AppEntryModuleId(NEEDS-SERVER-VERIFY)
Section titled “AppEntryModuleId(NEEDS-SERVER-VERIFY)”type AppEntryModuleId = | 'coupon' | 'lottery' | 'taskReward' | 'productList' | 'commentary'// 挂载 Svelte UI 到 DOM 容器sdk.mount(target: string | HTMLElement): Promise<void>
// 销毁 SDK,卸载 UI,清理所有资源sdk.destroy(): void
// 事件系统(由 SDK_EVENTS 类型化)sdk.on(event, handler): thissdk.off(event, handler): thissdk.once(event, handler): this
// 插件系统sdk.use(plugin: IPlugin): this
// 业务模块访问sdk.getModule<T>(id: ModuleId): T | undefined
// 应用层入口模块访问(Phase 11,NEEDS-SERVER-VERIFY)sdk.getAppModule(id: AppEntryModuleId): BaseAppModule | undefined
// i18n 文案(公共方法,供宿主页面使用)sdk.t(key: I18nKey): string事件(SDK_EVENTS)
Section titled “事件(SDK_EVENTS)”| 事件名 | Payload | 说明 |
|---|---|---|
ready |
undefined |
SDK 初始化完成 |
destroy |
undefined |
SDK 销毁 |
error |
{ code: number, message: string } |
全局错误 |
| 事件名 | Payload | 说明 |
|---|---|---|
live.status |
LiveStatus |
直播状态变更 |
live.orientation |
'portrait' | 'landscape' |
布局方向确定(取自 extendSet.screenType + config 覆盖) |
LiveStatus 枚举:
| 值 | 服务端状态码 | 说明 |
|---|---|---|
'not_started' |
102 | 预告 |
'ongoing' |
101 | 直播中 |
'ended' |
103 | 已结束 |
'banned' |
104 | 禁播 |
'paused' |
105 | 暂停 |
'error' |
106 | 异常 |
'expired' |
107 | 已过期 |
'playback' |
108 | 回放(VOD) |
| 事件名 | Payload | 说明 |
|---|---|---|
player.ready |
undefined |
TCPlayer 就绪 |
player.playing |
undefined |
开始播放 |
player.pause |
undefined |
暂停 |
player.error |
{ code: number, message: string } |
播放错误 |
player.duration |
{ duration: number } |
视频总时长(秒,DurationTracker 每 5s emit) |
player.timeupdate |
{ currentTime: number } |
当前播放位置(TCPlayer timeupdate,节流 250ms) |
| 事件名 | Payload | 说明 |
|---|---|---|
chat.message |
ChatMessage |
新聊天消息 |
chat.pinned |
ChatMessage | null |
置顶消息变更 |
chat.mute |
boolean | { muted: boolean } |
全员禁言开关 |
ChatMessage.type:'text' \| 'system' \| 'pinned' \| 'enter' \| 'welcome'(welcome= 进场欢迎语,仅本端可见)。
认证 / IM
Section titled “认证 / IM”IM 错误从全局
error通道分流到im.*事件族,集成方可精细处理 IM 特定错误,与im.reconnected生命周期粒度对齐。
| 事件名 | Payload | 说明 |
|---|---|---|
auth.success |
{ streamUrl: string } |
auth API 成功,返回流地址 |
im.ready |
undefined |
腾讯 IM SDK 就绪 |
im.reconnected |
undefined |
IM 网络重连成功 |
im.user_banned |
{ userId: string, reason?: string } |
用户被禁言 |
im.user_kicked |
{ userId: string, reason?: string } |
用户被踢出群 |
im.error |
{ code: number, message: string } |
IM 致命错误(如被踢下线) |
im.net_error |
{ code: number, message: string } |
IM 网络断开(与 im.reconnected 成对) |
WebSocket
Section titled “WebSocket”| 事件名 | Payload | 说明 |
|---|---|---|
ws.connected |
undefined |
WS 认证成功,连接就绪 |
ws.disconnected |
{ reason?: string } |
连接断开 |
ws.message |
WSMessage |
原始 WS 帧(调试用) |
ws.error |
{ code: number, message: string } |
WS 错误 |
ws.auth_failed |
{ code: number, message: string } |
认证失败(重试耗尽) |
ws.room_status |
{ status: LiveStatus } |
5000 ROOM_STATUS_NOTIFY 解析结果 |
ws.room_config |
Record<string, unknown> |
5010 ROOM_CONFIG_NOTIFY 原始 payload(Phase 11 扇出 subfield) |
ws.coupon_dispatch |
Record<string, unknown> |
优惠券推送(NEEDS-SERVER-VERIFY) |
ws.commentary |
Record<string, unknown> |
解说推送(NEEDS-SERVER-VERIFY) |
ws.goods_config |
Record<string, unknown> |
商品配置更新推送(NEEDS-SERVER-VERIFY) |
| 事件名 | Payload | 说明 |
|---|---|---|
interact.like |
{ count: number, delta: number } |
点赞 |
interact.gift |
GiftPayload |
礼物 |
interact.cart |
undefined |
底部栏购物车点击 |
interact.share |
undefined |
底部栏分享点击 |
interact.more |
{ action?: string } |
底部栏更多点击 |
用户 / 房间
Section titled “用户 / 房间”| 事件名 | Payload | 说明 |
|---|---|---|
user.join |
UserProfile |
用户进入直播间 |
room.viewerCount |
{ count: number } |
观看人数更新 |
| 事件名 | Payload | 说明 |
|---|---|---|
goods.show |
GoodsItem |
展示商品卡片 |
goods.hide |
{ goodsId: string } |
隐藏商品卡片 |
| 事件名 | Payload | 说明 |
|---|---|---|
duration.change |
{ totalMs: number, seconds: number } |
DurationTracker 每 5s emit |
duration.report |
{ seconds: number, success: boolean } |
30s 上报 taskTimeChime 结果 |
应用模块生命周期
Section titled “应用模块生命周期”| 事件名 | Payload | 说明 |
|---|---|---|
app.module.init |
{ moduleId: string } |
应用模块初始化 |
app.module.destroy |
{ moduleId: string } |
应用模块销毁 |
Phase 11 入口模块事件(NEEDS-SERVER-VERIFY)
Section titled “Phase 11 入口模块事件(NEEDS-SERVER-VERIFY)”以下事件 payload schema 由 5010 ROOM_CONFIG_NOTIFY subfield 推断,未经真实 LAPS 端点验证。
| 事件名 | Payload | 说明 |
|---|---|---|
coupon.show |
Record<string, unknown> |
优惠券可领取推送 |
coupon.open |
undefined |
打开优惠券面板 |
coupon.close |
undefined |
关闭优惠券面板 |
lottery.start |
Record<string, unknown> |
抽奖开始推送 |
lottery.open |
undefined |
打开抽奖面板 |
lottery.close |
undefined |
关闭抽奖面板 |
task.new |
Record<string, unknown> |
新任务推送 |
task.open |
undefined |
打开任务面板 |
task.close |
undefined |
关闭任务面板 |
goods.config |
Record<string, unknown> |
商品列表配置推送 |
goods.open |
undefined |
打开商品面板 |
goods.close |
undefined |
关闭商品面板 |
commentary.push |
Record<string, unknown> |
直播解说推送 |
commentary.open |
undefined |
打开解说面板 |
commentary.close |
undefined |
关闭解说面板 |
interface ChatMessage { id: string userId: string userName: string userAvatar?: string content: string timestamp: number type: 'text' | 'system' | 'pinned'}
interface GiftPayload { giftId: string giftName: string giftIcon?: string userId: string userName: string count: number}
interface UserProfile { userId: string userName: string avatar?: string level?: number}
interface GoodsItem { id: string name: string price: number image?: string url?: string}通过 sdk.getModule<T>(id) 访问:
// Player 模块const player = sdk.getModule<Player>('player')player.play()player.pause()player.setVolume(0.8) // 0–1player.attachElement(videoEl)
// IM 模块const im = sdk.getModule<IM>('im')await im.sendTextMessage('Hello!')const history = await im.getHistoryMessages(20)
// Interact 模块const interact = sdk.getModule<Interact>('interact')await interact.sendLike(3)
// User 模块const user = sdk.getModule<User>('user')await user.refreshUserSig(newSig)应用层入口模块(Phase 11,NEEDS-SERVER-VERIFY)
Section titled “应用层入口模块(Phase 11,NEEDS-SERVER-VERIFY)”// 获取入口模块实例并手动触发开/关const coupon = sdk.getAppModule('coupon')coupon?.open() // emit coupon.opencoupon?.close() // emit coupon.close
const lottery = sdk.getAppModule('lottery')lottery?.open()DanmuPlugin
Section titled “DanmuPlugin”import { DanmuPlugin } from 'we-livesdk/plugins'
sdk.use(new DanmuPlugin({ speed: 8, // 滚动时长(秒) fontSize: 14, opacity: 0.85, maxLines: 3,}))WatermarkPlugin
Section titled “WatermarkPlugin”import { WatermarkPlugin } from 'we-livesdk/plugins'
sdk.use(new WatermarkPlugin({ text: 'Username', position: 'top-right', // 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right' opacity: 0.4,}))DefinitionPlugin
Section titled “DefinitionPlugin”import { DefinitionPlugin } from 'we-livesdk/plugins'
sdk.use(new DefinitionPlugin({ defaultQuality: 'hd', qualityList: ['auto', 'hd', 'sd'],}))class AuthError extends Error { code: number // HTTP 状态码或业务错误码 message: string}auth API 调用失败时抛出 AuthError,可在 mount() 的 catch 中捕获。
import { LiveSDK } from 'we-livesdk' // 主入口import { LiveRoom } from 'we-livesdk/components' // Svelte 组件import { createChatStore } from 'we-livesdk/stores' // Store 工厂import { DanmuPlugin } from 'we-livesdk/plugins' // 插件import type { SDKConfig } from 'we-livesdk/types' // 仅类型import 'we-livesdk/styles' // Tailwind CSS完整使用示例
Section titled “完整使用示例”import { LiveSDK, SDK_EVENTS } from 'we-livesdk'import { DanmuPlugin } from 'we-livesdk/plugins'import 'we-livesdk/styles'
const sdk = new LiveSDK({ activityId: 'room-001', token: 'your-jwt-token', merchantId: 'your-merchant-id', locale: 'zh-CN',
tim: { sdkAppId: 1400000000, userId: 'viewer-123', userSig: await fetchUserSig('viewer-123'), groupId: 'live-room-001', },
ws: { url: 'wss://your-laps-host/ws', },
layout: { orientation: 'auto', // 读 API body.extendSet.screenType },
options: { logLevel: 'info', theme: { primaryColor: '#ff6b35', radius: '8px', }, },})
sdk.use(new DanmuPlugin({ speed: 8 }))
sdk.on(SDK_EVENTS.READY, () => { console.log('SDK ready')})
sdk.on(SDK_EVENTS.LIVE_ORIENTATION, (orientation) => { console.log('布局方向:', orientation) // 'portrait' | 'landscape'})
sdk.on(SDK_EVENTS.CHAT_MESSAGE, (msg) => { console.log(`${msg.userName}: ${msg.content}`)})
sdk.on(SDK_EVENTS.DURATION_CHANGE, ({ seconds }) => { console.log('已观看', seconds, '秒')})
sdk.on(SDK_EVENTS.PLAYER_ERROR, ({ code, message }) => { console.error(`播放错误 ${code}: ${message}`)})
// WS 连接状态sdk.on(SDK_EVENTS.WS_CONNECTED, () => { console.log('WebSocket 已连接')})
sdk.on(SDK_EVENTS.WS_ROOM_STATUS, ({ status }) => { console.log('直播状态(WS推送):', status)})
await sdk.mount('#live-container')
// 清理window.addEventListener('beforeunload', () => sdk.destroy())