跳至主要內容

WhatsApp

WhatsApp 頻道可讓 Mastra Agent 透過 WhatsApp Business Cloud 接收客戶訊息。Mastra 會處理 Agent 串接與 webhook 路由;Chat SDK WhatsApp adapter 文件則涵蓋 Meta 應用程式設定、憑證與 webhook 設定。

安裝 adapter
「安裝 adapter」的直接連結

從 Chat SDK 安裝 WhatsApp adapter:

npm install @chat-adapter/whatsapp

Agent 設定
「Agent 設定」的直接連結

createWhatsAppAdapter() 加入 Agent 的 channels.adapters 物件:

src/mastra/agents/whatsapp-agent.ts
import { Agent } from '@mastra/core/agent'
import { createWhatsAppAdapter } from '@chat-adapter/whatsapp'

export const whatsappAgent = new Agent({
id: 'whatsapp-agent',
name: 'WhatsApp Agent',
instructions: 'Answer customer questions and help with tasks in WhatsApp.',
model: 'openai/gpt-5.6-sol',
channels: {
adapters: {
whatsapp: createWhatsAppAdapter(),
},
},
})

在 Mastra instance 上註冊 Agent:

src/mastra/index.ts
import { Mastra } from '@mastra/core'
import { whatsappAgent } from './agents/whatsapp-agent'

export const mastra = new Mastra({
agents: { whatsappAgent },
})

Adapter 設定
「Adapter 設定」的直接連結

請依照 Chat SDK WhatsApp adapter 文件完成 WhatsApp 專屬設定,包括 Meta 應用程式設定、存取 token、電話號碼 ID、webhook 驗證與訊息限制。

Adapter 會從下列環境變數讀取 WhatsApp 憑證:

.env
WHATSAPP_ACCESS_TOKEN=your-meta-access-token
WHATSAPP_APP_SECRET=your-meta-app-secret
WHATSAPP_PHONE_NUMBER_ID=your-whatsapp-phone-number-id
WHATSAPP_VERIFY_TOKEN=your-webhook-verify-token

Webhook URL
「Webhook URL」的直接連結

Mastra 會根據 Agent ID 與 adapter key 產生 WhatsApp webhook 路由:

/api/agents/whatsapp-agent/channels/whatsapp/webhook

使用公開 Mastra 伺服器 URL 作為基底 URL:

https://your-app.example.com/api/agents/whatsapp-agent/channels/whatsapp/webhook

使用此 URL 接收傳入的 WhatsApp 事件。產生的 Mastra 路由會處理 WhatsApp 的 POST 事件;Meta callback 與 webhook 驗證流程請依照 Chat SDK WhatsApp adapter 文件操作。