UNPKG

@warriorteam/redai-zalo-sdk

Version:

Comprehensive TypeScript/JavaScript SDK for Zalo APIs - Official Account v3.0, ZNS with Full Type Safety, Consultation Service, Broadcast Service, Group Messaging with List APIs, Social APIs, Enhanced Article Management, Promotion Service v3.0 with Multip

325 lines (283 loc) 8.64 kB
/** * Ví dụ sử dụng ConsultationService.sendTemplateMessage() * Gửi tin nhắn template tổng quát với elements và buttons * * API Endpoint: https://openapi.zalo.me/v3.0/oa/message/cs * Method: POST * Content-Type: application/json */ import { ConsultationService, TemplateElement, TemplateButton, TemplateAction } from '../src/services/consultation.service'; import { ZaloClient } from '../src/clients/zalo-client'; // Khởi tạo service const zaloClient = new ZaloClient(); const consultationService = new ConsultationService(zaloClient); const ACCESS_TOKEN = "your_access_token_here"; const USER_ID = "2468458835296117922"; /** * Ví dụ 1: Template request_user_info cơ bản */ async function example1_BasicRequestUserInfo() { try { // Tạo elements (tối đa 5 phần tử) const elements: TemplateElement[] = [ // Element đầu tiên PHẢI có subtitle consultationService.createTemplateElement( "OA Chatbot (Testing)", "Đang yêu cầu thông tin từ bạn", "https://developers.zalo.me/web/static/zalo.png", consultationService.createUrlAction("https://developers.zalo.me/") ), // Các element sau có thể không có subtitle consultationService.createTemplateElement( "Liên hệ hỗ trợ", undefined, // không có subtitle "https://developers.zalo.me/web/static/zalo.png", consultationService.createPhoneAction("84919018791") ) ]; // Tạo buttons (tối đa 5 phần tử) const buttons: TemplateButton[] = [ consultationService.createUrlButton("OPEN URL", "https://developers.zalo.me/"), consultationService.createQueryShowButton("QUERY SHOW", "#callback_data"), consultationService.createQueryHideButton("QUERY HIDE", "#callback_data"), consultationService.createSmsButton("OPEN SMS", "84919018791", "alo"), consultationService.createPhoneButton("OPEN PHONE", "84919018791") ]; // Gửi template message const result = await consultationService.sendTemplateMessage( ACCESS_TOKEN, USER_ID, "request_user_info", elements, buttons ); console.log("✅ Template message sent successfully:", result); return result; } catch (error) { console.error("❌ Error sending template message:", error); throw error; } } /** * Ví dụ 2: Template đơn giản chỉ có 1 element và 2 buttons */ async function example2_SimpleTemplate() { try { // Chỉ 1 element const elements: TemplateElement[] = [ { title: "Chào mừng bạn đến với dịch vụ của chúng tôi!", subtitle: "Chúng tôi có thể hỗ trợ gì cho bạn?", image_url: "https://example.com/welcome.png" } ]; // 2 buttons đơn giản const buttons: TemplateButton[] = [ consultationService.createQueryShowButton("Tư vấn sản phẩm", "product_consultation"), consultationService.createPhoneButton("Gọi hotline", "84919018791") ]; const result = await consultationService.sendTemplateMessage( ACCESS_TOKEN, USER_ID, "request_user_info", elements, buttons ); console.log("✅ Simple template sent successfully:", result); return result; } catch (error) { console.error("❌ Error sending simple template:", error); throw error; } } /** * Ví dụ 3: Template không có buttons (chỉ elements) */ async function example3_ElementsOnly() { try { const elements: TemplateElement[] = [ { title: "Thông báo quan trọng", subtitle: "Hệ thống sẽ bảo trì từ 2:00 - 4:00 sáng ngày mai", image_url: "https://example.com/maintenance.png", default_action: { type: "oa.open.url", url: "https://example.com/maintenance-info" } }, { title: "Liên hệ hỗ trợ khẩn cấp", // Không có subtitle cho element thứ 2 default_action: { type: "oa.open.phone", payload: { phone_code: "84919018791" } } } ]; // Không có buttons const result = await consultationService.sendTemplateMessage( ACCESS_TOKEN, USER_ID, "request_user_info", elements // buttons parameter bỏ qua ); console.log("✅ Elements-only template sent successfully:", result); return result; } catch (error) { console.error("❌ Error sending elements-only template:", error); throw error; } } /** * Ví dụ 4: Template với tất cả loại buttons */ async function example4_AllButtonTypes() { try { const elements: TemplateElement[] = [ { title: "Trung tâm hỗ trợ khách hàng", subtitle: "Chọn hình thức liên hệ phù hợp với bạn", image_url: "https://example.com/support.png" } ]; const buttons: TemplateButton[] = [ // URL button { title: "Xem FAQ", type: "oa.open.url", payload: { url: "https://example.com/faq" } }, // Query show button { title: "Chat với tư vấn viên", type: "oa.query.show", payload: "start_chat_with_agent" }, // Query hide button { title: "Gửi phản hồi", type: "oa.query.hide", payload: "send_feedback" }, // SMS button { title: "Gửi SMS hỗ trợ", type: "oa.open.sms", payload: { phone_code: "84919018791", content: "Tôi cần hỗ trợ" } }, // Phone button { title: "Gọi hotline", type: "oa.open.phone", payload: { phone_code: "84919018791" } } ]; const result = await consultationService.sendTemplateMessage( ACCESS_TOKEN, USER_ID, "request_user_info", elements, buttons ); console.log("✅ All button types template sent successfully:", result); return result; } catch (error) { console.error("❌ Error sending all button types template:", error); throw error; } } /** * Ví dụ 5: Template với validation errors (để test) */ async function example5_ValidationErrors() { try { // Element với title quá dài (> 100 ký tự) const invalidElements: TemplateElement[] = [ { title: "A".repeat(101), // 101 ký tự - sẽ báo lỗi subtitle: "This will cause validation error" } ]; await consultationService.sendTemplateMessage( ACCESS_TOKEN, USER_ID, "request_user_info", invalidElements ); } catch (error) { console.log("✅ Expected validation error caught:", error.message); } try { // Element đầu tiên không có subtitle const invalidElements2: TemplateElement[] = [ { title: "Valid title", // Thiếu subtitle cho element đầu tiên - sẽ báo lỗi } ]; await consultationService.sendTemplateMessage( ACCESS_TOKEN, USER_ID, "request_user_info", invalidElements2 ); } catch (error) { console.log("✅ Expected validation error caught:", error.message); } try { // Quá nhiều elements (> 5) const tooManyElements: TemplateElement[] = Array(6).fill(null).map((_, i) => ({ title: `Element ${i + 1}`, subtitle: i === 0 ? "Required subtitle for first element" : undefined })); await consultationService.sendTemplateMessage( ACCESS_TOKEN, USER_ID, "request_user_info", tooManyElements ); } catch (error) { console.log("✅ Expected validation error caught:", error.message); } } // Chạy các ví dụ async function runExamples() { console.log("🚀 Running Consultation Template Examples...\n"); try { await example1_BasicRequestUserInfo(); console.log("\n"); await example2_SimpleTemplate(); console.log("\n"); await example3_ElementsOnly(); console.log("\n"); await example4_AllButtonTypes(); console.log("\n"); await example5_ValidationErrors(); console.log("\n"); console.log("✅ All examples completed!"); } catch (error) { console.error("❌ Example failed:", error); } } // Export để có thể import và sử dụng export { example1_BasicRequestUserInfo, example2_SimpleTemplate, example3_ElementsOnly, example4_AllButtonTypes, example5_ValidationErrors, runExamples }; // Chạy nếu file được execute trực tiếp if (require.main === module) { runExamples(); }