Claude cho Ecommerce: Chatbot bán hàng Facebook Messenger
Điểm nổi bật
Nhấn để đến mục tương ứng
- 1 Có thể gửi nhiều tin nhắn liên tiếp nếu cần giải thích dài CHƯƠNG TRÌNH KHUYẾN MÃI HIỆN TẠI: - Mua 2 giảm 10% - Free ship đơn từ 500k - Member giảm thêm 5%`; } async getHistory(userId) { const history = await redis.get(`conv:${userId}`); return history ?
- 2 Nhieu don hang cung luc: - Gop don de tiet kiem ship - "Chi muon em gop chung 1 don de tiet kiem phi ship khong a?" `; Analytics và tracking hiệu quả chatbot Để cải thiện chatbot liên tục, cần tracking các metrics quan trọng.
- 3 { text: message } : message }) } ); return response.json(); } app.listen(3000, () => console.log('Webhook server running')); Bước 2: Conversation Manager với Claude Module quan trọng nhất — quản lý conversation history và gọi Claude API để sinh phản hồi thông minh.
- 4 Bước tiếp theo Bạn đã nắm được cách xây dựng chatbot bán hàng Facebook Messenger với Claude API — từ webhook setup, conversation management, xử lý đơn hàng đến escalation và analytics.
- 5 Hơn 70% shop online nhận đơn qua Messenger, và khách hàng kỳ vọng được phản hồi trong vòng 5 phút.
Facebook Messenger là kênh bán hàng online lớn nhất tại Việt Nam. Hơn 70% shop online nhận đơn qua Messenger, và khách hàng kỳ vọng được phản hồi trong vòng 5 phút. Nhưng hầu hết chủ shop không thể trả lời 24/7, và chatbot rule-based truyền thống chỉ xử lý được những câu hỏi đơn giản nhất. Claude API thay đổi hoàn toàn cục diện — chatbot bán hàng với Claude hiểu ngữ cảnh, tư vấn sản phẩm thông minh, xử lý objections, và chốt đơn tự nhiên như một nhân viên bán hàng giỏi.
Tại sao chatbot Claude khác biệt với chatbot thông thường?
Chatbot rule-based hoạt động theo kịch bản cố định — nếu khách hỏi ngoài kịch bản, chatbot không trả lời được. Chatbot với Claude hiểu ngôn ngữ tự nhiên, xử lý được câu hỏi phức tạp, và có thể "suy nghĩ" để đưa ra tư vấn phù hợp.
Ví dụ cụ thể: Khách nhắn "em ơi có váy nào mặc đi đám cưới mà không quá formal, budget tầm 500-800k, em mập nên thích kiểu suông suông". Chatbot rule-based sẽ không hiểu hoặc hỏi lại từ đầu. Claude chatbot hiểu ngay: cần váy semi-formal, ngân sách 500-800k, body type plus-size, fit suông, và gợi ý 3-5 sản phẩm phù hợp kèm lý do.
Kiến trúc hệ thống chatbot Messenger
Hệ thống gồm 4 thành phần chính. Thứ nhất, Facebook Page + Messenger Platform — tiếp nhận tin nhắn từ khách hàng qua webhook. Thứ hai, Backend Server (Node.js/Python) — nhận webhook events, xử lý logic, gọi Claude API. Thứ ba, Claude API — hiểu tin nhắn, tư vấn, sinh phản hồi. Thứ tư, Product Database — danh mục sản phẩm, tồn kho, giá cả.
// Kiến trúc tổng quan
//
// [Khách hàng] -> [Facebook Messenger] -> [Webhook]
// |
// [Backend Server]
// / | // [Claude API] [Product DB] [Order System]
// |
// [Response]
// |
// [Messenger] -> [Khách hàng]
//
// Tech stack:
// - Server: Node.js + Express
// - Claude: @anthropic-ai/sdk
// - Database: PostgreSQL (products) + Redis (session/conversation history)
// - Hosting: VPS hoặc Cloud Run
// - Facebook: Messenger Platform API v18.0
Bước 1: Setup Facebook Messenger Webhook
Đầu tiên, tạo Facebook App và kết nối với Page để nhận webhook events khi có tin nhắn mới.
// server.js - Webhook setup
const express = require('express');
const Anthropic = require('@anthropic-ai/sdk');
const app = express();
app.use(express.json());
const VERIFY_TOKEN = process.env.FB_VERIFY_TOKEN;
const PAGE_ACCESS_TOKEN = process.env.FB_PAGE_ACCESS_TOKEN;
const anthropic = new Anthropic();
// Webhook verification (Facebook requires this)
app.get('/webhook', (req, res) => {
const mode = req.query['hub.mode'];
const token = req.query['hub.verify_token'];
const challenge = req.query['hub.challenge'];
if (mode === 'subscribe' && token === VERIFY_TOKEN) {
res.status(200).send(challenge);
} else {
res.sendStatus(403);
}
});
// Receive messages
app.post('/webhook', async (req, res) => {
const body = req.body;
if (body.object === 'page') {
for (const entry of body.entry) {
for (const event of entry.messaging) {
if (event.message && event.message.text) {
await handleMessage(event.sender.id, event.message.text);
}
if (event.postback) {
await handlePostback(event.sender.id, event.postback.payload);
}
}
}
res.status(200).send('EVENT_RECEIVED');
} else {
res.sendStatus(404);
}
});
// Send message back to user
async function sendMessage(recipientId, message) {
const response = await fetch(
`https://graph.facebook.com/v18.0/me/messages?access_token=${PAGE_ACCESS_TOKEN}`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
recipient: { id: recipientId },
message: typeof message === 'string'
? { text: message }
: message
})
}
);
return response.json();
}
app.listen(3000, () => console.log('Webhook server running'));
Bước 2: Conversation Manager với Claude
Module quan trọng nhất — quản lý conversation history và gọi Claude API để sinh phản hồi thông minh. Mỗi khách hàng có conversation context riêng được lưu trong Redis.
// conversation-manager.js
const Redis = require('ioredis');
const redis = new Redis(process.env.REDIS_URL);
const { getProductCatalog, searchProducts } = require('./product-db');
const CONVERSATION_TTL = 3600 * 24; // 24 giờ
class ConversationManager {
constructor(anthropicClient) {
this.claude = anthropicClient;
this.systemPrompt = `Bạn là nhân viên bán hàng online cho shop thời trang [TÊN SHOP].
THÔNG TIN SHOP:
- Chuyên thời trang nữ: váy, đầm, áo, quần
- Phân khúc: trung cấp, giá 200k-1.5 triệu
- Ship toàn quốc, COD hoặc chuyển khoản
- Đổi trả trong 7 ngày nếu lỗi từ shop
- Giờ làm việc: 8h-22h, ngoài giờ chatbot tự động
QUY TẮC:
1. Trả lời ngắn gọn, thân thiện, dùng "em/chị" (gọi khách là chị/anh)
2. Khi khách hỏi về sản phẩm, gợi ý 2-3 sản phẩm phù hợp kèm giá
3. Hỏi size và màu khi khách quan tâm sản phẩm cụ thể
4. Nếu hết hàng, gợi ý sản phẩm tương tự
5. Khi khách muốn đặt hàng, thu thập: tên, SĐT, địa chỉ, sản phẩm + size + màu
6. KHÔNG tự ý giảm giá — chỉ áp dụng chương trình khuyến mãi hiện có
7. Nếu câu hỏi ngoài phạm vi (kỹ thuật, khiếu nại phức tạp), nói sẽ chuyển nhân viên
8. Tin nhắn tối đa 200 ký tự mỗi lần (phù hợp đọc trên mobile)
9. Có thể gửi nhiều tin nhắn liên tiếp nếu cần giải thích dài
CHƯƠNG TRÌNH KHUYẾN MÃI HIỆN TẠI:
- Mua 2 giảm 10%
- Free ship đơn từ 500k
- Member giảm thêm 5%`;
}
async getHistory(userId) {
const history = await redis.get(`conv:${userId}`);
return history ? JSON.parse(history) : [];
}
async saveHistory(userId, messages) {
// Keep last 20 messages to control context length
const trimmed = messages.slice(-20);
await redis.setex(`conv:${userId}`, CONVERSATION_TTL, JSON.stringify(trimmed));
}
async processMessage(userId, userMessage) {
// 1. Get conversation history
const history = await this.getHistory(userId);
// 2. Search relevant products if message mentions products
const productContext = await this.getProductContext(userMessage);
// 3. Build messages array
const messages = [
...history,
{
role: 'user',
content: productContext
? `${userMessage}
[SẢN PHẨM LIÊN QUAN: ${productContext}]`
: userMessage
}
];
// 4. Call Claude
const response = await this.claude.messages.create({
model: 'sonnet',
max_tokens: 300,
system: this.systemPrompt,
messages: messages
});
const assistantMessage = response.content[0].text;
// 5. Save updated history
history.push(
{ role: 'user', content: userMessage },
{ role: 'assistant', content: assistantMessage }
);
await this.saveHistory(userId, history);
// 6. Check for order intent
const orderData = this.detectOrderIntent(assistantMessage, history);
return {
reply: assistantMessage,
orderData: orderData,
shouldEscalate: this.shouldEscalate(userMessage, assistantMessage)
};
}
async getProductContext(message) {
// Simple keyword matching + search
const keywords = message.toLowerCase();
const categories = [];
if (keywords.includes('váy') || keywords.includes('đầm')) categories.push('dress');
if (keywords.includes('áo')) categories.push('top');
if (keywords.includes('quần')) categories.push('bottom');
if (categories.length > 0) {
const products = await searchProducts({ categories, inStock: true, limit: 5 });
return products.map(p =>
`${p.name} - ${p.price.toLocaleString()}đ - Size: ${p.sizes.join(',')} - Màu: ${p.colors.join(',')}`
).join('
');
}
return null;
}
detectOrderIntent(reply, history) {
// Detect if conversation has reached order stage
const fullConv = history.map(m => m.content).join(' ').toLowerCase();
if (fullConv.includes('đặt hàng') || fullConv.includes('order') ||
fullConv.includes('mua ngay') || fullConv.includes('chốt đơn')) {
return { intent: 'order', stage: 'collecting_info' };
}
return null;
}
shouldEscalate(userMessage, reply) {
const escalateKeywords = ['khiếu nại', 'trả hàng', 'lỗi', 'manager',
'quản lý', 'không hài lòng', 'scam', 'lừa đảo'];
return escalateKeywords.some(k => userMessage.toLowerCase().includes(k));
}
}
module.exports = ConversationManager;
Bước 3: Rich Messages — Carousel, Quick Reply, Buttons
Messenger hỗ trợ nhiều loại message ngoài text — carousel sản phẩm, nút bấm, quick replies. Claude có thể quyết định khi nào dùng loại nào.
// rich-messages.js - Messenger message templates
function createProductCarousel(products) {
return {
attachment: {
type: 'template',
payload: {
template_type: 'generic',
elements: products.slice(0, 10).map(product => ({
title: product.name,
subtitle: `${product.price.toLocaleString()}d | Size: ${product.sizes.join(', ')}`,
image_url: product.image_url,
buttons: [
{
type: 'postback',
title: 'Xem chi tiet',
payload: `VIEW_PRODUCT_${product.id}`
},
{
type: 'postback',
title: 'Dat hang',
payload: `ORDER_PRODUCT_${product.id}`
}
]
}))
}
}
};
}
function createQuickReplies(text, options) {
return {
text: text,
quick_replies: options.map(opt => ({
content_type: 'text',
title: opt,
payload: opt
}))
};
}
function createSizeSelector(productId) {
return createQuickReplies(
'Chi chon size nhe:',
['S', 'M', 'L', 'XL', 'XXL']
);
}
function createOrderConfirmation(order) {
return {
attachment: {
type: 'template',
payload: {
template_type: 'receipt',
recipient_name: order.customer_name,
order_number: order.id,
currency: 'VND',
payment_method: order.payment_method,
summary: {
subtotal: order.subtotal,
shipping_cost: order.shipping,
total_cost: order.total
},
elements: order.items.map(item => ({
title: item.name,
subtitle: `Size: ${item.size} | Mau: ${item.color}`,
quantity: item.quantity,
price: item.price,
image_url: item.image_url
}))
}
}
};
}
module.exports = { createProductCarousel, createQuickReplies,
createSizeSelector, createOrderConfirmation };
Bước 4: Xử lý đặt hàng qua chat
Khi khách quyết định mua, chatbot cần thu thập thông tin đơn hàng một cách tự nhiên, không phải form cứng nhắc. Claude xử lý quá trình này bằng cách extract thông tin từ tin nhắn tự nhiên của khách.
// order-handler.js
class OrderHandler {
constructor(claudeClient) {
this.claude = claudeClient;
}
async extractOrderInfo(conversationHistory) {
const response = await this.claude.messages.create({
model: 'sonnet',
max_tokens: 500,
system: `Extract thong tin don hang tu cuoc hoi thoai.
Output JSON:
{
"complete": true/false,
"customer_name": "...",
"phone": "...",
"address": "...",
"items": [{"product": "...", "size": "...", "color": "...", "quantity": 1}],
"payment_method": "COD/transfer",
"missing_fields": ["field1", "field2"],
"next_question": "Cau hoi tiep theo de thu thap thong tin con thieu"
}`,
messages: conversationHistory
});
return JSON.parse(response.content[0].text);
}
async createOrder(orderData) {
// Validate inventory
for (const item of orderData.items) {
const inStock = await checkInventory(item.product, item.size, item.color);
if (!inStock) {
return {
success: false,
message: `Xin loi chi, ${item.product} size ${item.size} mau ${item.color} hien het hang.`
};
}
}
// Calculate total
const total = await calculateTotal(orderData.items);
// Save order to database
const order = await saveOrder({
...orderData,
subtotal: total.subtotal,
shipping: total.shipping,
discount: total.discount,
total: total.total,
status: 'pending',
source: 'messenger'
});
return {
success: true,
order: order,
message: `Da tao don hang #${order.id}. Tong: ${order.total.toLocaleString()}d. Ship du kien 2-3 ngay.`
};
}
}
Bước 5: Escalation — Chuyển nhân viên thật
Chatbot không thể xử lý mọi tình huống. Cần cơ chế chuyển sang nhân viên thật khi gặp khiếu nại, yêu cầu phức tạp, hoặc khách yêu cầu nói chuyện với người.
// escalation.js
async function handleEscalation(userId, reason, conversationHistory) {
// 1. Thông báo khách
await sendMessage(userId,
'Em chuyen chi qua nhan vien ho tro nhe. Nhan vien se phan hoi trong 5 phut.');
// 2. Tạo summary cho nhân viên
const summary = await claude.messages.create({
model: 'sonnet',
max_tokens: 300,
messages: [{
role: 'user',
content: `Tom tat cuoc hoi thoai nay cho nhan vien CSKH:
${conversationHistory.map(m => `${m.role}: ${m.content}`).join('
')}
Trich xuat:
1. Van de chinh cua khach
2. San pham lien quan (neu co)
3. Cam xuc cua khach (binh thuong/khong hai long/rat gian)
4. Hanh dong can lam`
}]
});
// 3. Gửi notification cho nhân viên (qua Slack/Telegram/Dashboard)
await notifyStaff({
customer_id: userId,
summary: summary.content[0].text,
priority: reason === 'complaint' ? 'high' : 'normal',
conversation: conversationHistory
});
// 4. Đánh dấu conversation là "human-handling"
await redis.set(`escalated:${userId}`, 'true', 'EX', 86400);
}
Xử lý các tình huống đặc biệt
Chatbot bán hàng cần xử lý nhiều tình huống ngoài việc tư vấn và đặt hàng. Claude đặc biệt mạnh trong việc xử lý các tình huống đòi hỏi sự khéo léo.
// Prompt bổ sung cho các tình huống đặc biệt
const SPECIAL_SCENARIOS = `
TINH HUONG DAC BIET:
1. Khach doi giam gia:
- Khong tu y giam gia
- Nhac chuong trinh khuyen mai hien co
- "Chi oi, hien tai shop dang co chuong trinh mua 2 giam 10% a.
Neu chi mua 2 mon se duoc giam ngay chi a!"
2. Khach so sánh voi shop khac:
- Khong noi xau doi thu
- Nhan manh chat luong va dich vu cua minh
- "Du bên nào thì quan trọng nhất là chị ưng sản phẩm chị nhé.
Bên em cam kết hàng chuẩn, đổi trả 7 ngày nếu không ưng ạ."
3. Khach hoi ngoai gio:
- Tra loi cac cau hoi co ban (gia, size, ton kho)
- Don hang phuc tap: "Em ghi nhan don cho chi. Sang mai nhan vien
se xac nhan lai voi chi nhe!"
4. Khach gui hinh anh:
- Nhan biet va phan hoi: "Chi gui hinh san pham chi quan tam dung
khong a? De em kiem tra thong tin cho chi nhe."
- Neu khong nhan dien duoc: "Chi co the mo ta them giup em duoc
khong a?"
5. Tin nhan khong ro rang:
- Hoi lai lich su, khong hoi tu dau
- "Chi oi, y chi la muon hoi ve [san pham da noi truoc do] dung
khong a?"
6. Nhieu don hang cung luc:
- Gop don de tiet kiem ship
- "Chi muon em gop chung 1 don de tiet kiem phi ship khong a?"
`;
Analytics và tracking hiệu quả chatbot
Để cải thiện chatbot liên tục, cần tracking các metrics quan trọng. Metrics chính bao gồm: response time (trung bình bao lâu chatbot trả lời), conversion rate (bao nhiêu % conversation dẫn đến đơn hàng), escalation rate (bao nhiêu % phải chuyển nhân viên), customer satisfaction (rating sau conversation), average order value (giá trị đơn trung bình qua chatbot), và containment rate (bao nhiêu % được giải quyết hoàn toàn bởi chatbot).
// analytics.js - Track chatbot performance
class ChatbotAnalytics {
async trackConversation(userId, data) {
await db.insert('chatbot_analytics', {
user_id: userId,
timestamp: new Date(),
message_count: data.messageCount,
response_time_avg_ms: data.avgResponseTime,
resulted_in_order: data.hasOrder,
order_value: data.orderValue || 0,
escalated: data.escalated,
sentiment: data.sentiment, // Claude phan tich sentiment
topics: data.topics, // Chu de cuoc hoi thoai
session_duration_s: data.duration
});
}
async getWeeklyReport() {
const report = await db.query(`
SELECT
COUNT(*) as total_conversations,
AVG(response_time_avg_ms) as avg_response_time,
SUM(CASE WHEN resulted_in_order THEN 1 ELSE 0 END) as orders,
SUM(order_value) as total_revenue,
AVG(CASE WHEN escalated THEN 1.0 ELSE 0.0 END) * 100 as escalation_rate,
AVG(message_count) as avg_messages_per_conv
FROM chatbot_analytics
WHERE timestamp >= NOW() - INTERVAL '7 days'
`);
return report;
}
}
Chi phí vận hành chatbot Claude Messenger
Chi phí gồm 3 khoản chính. Claude API: trung bình mỗi conversation 10 tin nhắn, mỗi tin khoảng 500 tokens input + 200 tokens output, tổng khoảng $0.05-0.10/conversation. Với 100 conversations/ngày, chi phí khoảng $5-10/ngày hay $150-300/tháng. Server hosting: VPS nhỏ đủ chạy, khoảng $10-30/tháng. Redis: $0-15/tháng (tùy provider). Tổng: $160-350/tháng. So sánh: 1 nhân viên bán hàng online lương 7-10 triệu/tháng, chỉ làm 8 tiếng/ngày. Chatbot Claude làm 24/7 với chi phí bằng 1/3-1/5.
Mẹo xây dựng chatbot bán hàng hiệu quả
- Giữ tin nhắn ngắn — Tối đa 200 ký tự mỗi tin. Người dùng mobile không đọc tin dài. Chia thành nhiều tin nhắn ngắn nếu cần.
- Dùng quick replies cho câu hỏi có đáp án giới hạn — Size S/M/L, COD/chuyển khoản. Giảm effort cho khách.
- Product carousel cho gợi ý sản phẩm — Hình ảnh bán hàng tốt hơn text mô tả.
- Luôn có nút "Nói chuyện với nhân viên" — Không bao giờ ép khách phải nói chuyện với bot.
- Test với tiếng Việt thực tế — Khách hàng viết tắt, sai chính tả, dùng tiếng lóng. Claude xử lý tốt nhưng cần test kỹ.
- Thu thập feedback — Sau mỗi conversation, hỏi "Em phục vụ được không ạ?" để cải thiện.
Bước tiếp theo
Bạn đã nắm được cách xây dựng chatbot bán hàng Facebook Messenger với Claude API — từ webhook setup, conversation management, xử lý đơn hàng đến escalation và analytics. Chatbot này giúp shop online phục vụ khách hàng 24/7, tăng conversion rate và giảm chi phí nhân sự. Khám phá thêm tại Thư viện Ứng dụng Claude.
Bai viet co huu ich khong?
Bản quyền thuộc về tác giả. Vui lòng dẫn nguồn khi chia sẻ.






