API 參考

Widget API 和 REST 端點的完整參考文件。

Widget API

全域 window.LaunchChatWidget 物件提供了以程式方式控制元件的方法。

方法

open()

以程式方式開啟聊天視窗。

window.LaunchChatWidget.open();
close()

關閉聊天視窗。

window.LaunchChatWidget.close();
destroy()

從頁面中完全移除元件。適用於 SPA 頁面切換時使用。

window.LaunchChatWidget.destroy();
init(config)

使用新設定重新初始化元件。

window.LaunchChatWidget.init({ widgetId: "new-widget-id" });
on(event, callback)

訂閱元件事件。

window.LaunchChatWidget.on('message', (data) => {
  console.log('New message:', data);
});
off(event, callback)

取消訂閱元件事件。

事件

事件載荷描述
open{ timestamp }聊天視窗已開啟
close{ timestamp }聊天視窗已關閉
message{ content, role }訊息已傳送或接收
escalate{ email, message }使用者請求真人客服
feedback{ messageId, type }使用者提交了回饋(好評/差評)

REST API

POST /api/widget/chat

傳送訊息並接收AI產生的回覆。

請求主體

{
  "widgetId": "string",      // Required
  "message": "string",       // Required - user's question
  "conversationId": "string", // Optional - for context
  "visitorId": "string",     // Optional - track visitor
  "pageUrl": "string"        // Optional - current page
}

回應

{
  "conversationId": "uuid",
  "messageId": "uuid",
  "answer": "string",
  "citations": [
    {
      "pageId": "string",
      "pageTitle": "string",
      "pageUrl": "string",
      "excerpt": "string"
    }
  ],
  "relatedArticles": [...],
  "confidenceScore": 0.85,
  "wasRefused": false
}

錯誤碼

狀態碼狀態描述
400請求錯誤缺少必填欄位
403禁止存取網域不在允許清單中
404未找到元件未找到或已停用
429請求頻率受限訊息配額已用盡
500伺服器錯誤內部處理錯誤

TypeScript 型別

將這些型別複製到您的專案中以取得完整的型別安全:

interface LaunchChatConfig {
  widgetId: string;
  primaryColor?: string;
  greeting?: string;
  placeholder?: string;
  position?: 'bottom-right' | 'bottom-left';
  theme?: 'light' | 'dark' | 'auto';
}

interface WidgetAPI {
  open(): void;
  close(): void;
  destroy(): void;
  init(config: { widgetId: string }): Promise<void>;
  on<E extends keyof WidgetEvents>(
    event: E,
    callback: (data: WidgetEvents[E]) => void
  ): void;
  off<E extends keyof WidgetEvents>(
    event: E,
    callback: (data: WidgetEvents[E]) => void
  ): void;
}

interface WidgetEvents {
  open: { timestamp: number };
  close: { timestamp: number };
  message: { content: string; role: 'user' | 'assistant' };
  escalate: { email: string; message: string };
  feedback: { messageId: string; type: 'positive' | 'negative' };
}

declare global {
  interface Window {
    LaunchChatConfig?: LaunchChatConfig;
    LaunchChatWidget?: WidgetAPI;
  }
}