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

173 lines (155 loc) 6.02 kB
/** * Ví dụ sử dụng sendCustomMessageSequenceToMultipleUsers API * API này cho phép gửi tin nhắn tùy chỉnh riêng cho từng user * thay vì gửi cùng một tin nhắn cho tất cả users */ const { ZaloSDK } = require('../dist/index'); async function sendCustomMessagesToUsers() { // Khởi tạo SDK const zalo = new ZaloSDK({ appId: 'your_app_id', appSecret: 'your_app_secret' }); const accessToken = 'your_access_token'; try { // Tạo tin nhắn tùy chỉnh cho từng user const userCustomMessages = [ { userId: 'user_1', messages: [ { type: 'text', text: 'Chào bạn Nguyễn Văn A! Chúng tôi có ưu đãi đặc biệt dành riêng cho bạn.', delay: 1000 }, { type: 'text', text: 'Giảm 20% cho đơn hàng tiếp theo của bạn với mã: VANA20', delay: 2000 }, { type: 'image', imageUrl: 'https://example.com/promotion-vana.jpg', text: 'Xem chi tiết ưu đãi' } ] }, { userId: 'user_2', messages: [ { type: 'text', text: 'Xin chào anh Trần Văn B! Cảm ơn anh đã luôn tin tưởng sản phẩm của chúng tôi.', delay: 1000 }, { type: 'text', text: 'Với tư cách khách hàng VIP, anh được giảm 30% với mã: VANB30', delay: 2000 }, { type: 'sticker', stickerAttachmentId: 'sticker_thankyou_id' } ] }, { userId: 'user_3', messages: [ { type: 'text', text: 'Chào chị Mai! Chúng tôi có sản phẩm mới phù hợp với sở thích của chị.' }, { type: 'request_user_info', title: 'Cập nhật thông tin', subtitle: 'Vui lòng cập nhật số điện thoại để nhận ưu đãi', imageUrl: 'https://example.com/update-info.jpg' } ] } ]; // Callback để tracking tiến trình const progressCallback = (progress) => { console.log(`[${progress.userId}] Status: ${progress.status}`); if (progress.status === 'completed') { console.log(`✅ User ${progress.userId}: ${progress.result.successCount}/${progress.result.results.length} tin nhắn thành công`); } else if (progress.status === 'failed') { console.log(`❌ User ${progress.userId}: ${progress.error}`); } }; console.log('🚀 Bắt đầu gửi tin nhắn tùy chỉnh cho nhiều users...'); const result = await zalo.consultation.sendCustomMessageSequenceToMultipleUsers({ accessToken, userCustomMessages, defaultDelay: 500, // Delay mặc định giữa các tin nhắn delayBetweenUsers: 2000, // Delay giữa các user để tránh rate limit onProgress: progressCallback }); // Hiển thị kết quả tổng kết console.log('\n📊 KẾT QUẢ TỔNG KẾT:'); console.log(`👥 Tổng số users: ${result.totalUsers}`); console.log(`✅ Users thành công: ${result.successfulUsers}`); console.log(`❌ Users thất bại: ${result.failedUsers}`); console.log(`📱 Tổng tin nhắn thành công: ${result.messageStats.totalSuccessfulMessages}`); console.log(`📱 Tổng tin nhắn thất bại: ${result.messageStats.totalFailedMessages}`); console.log(`⏱️ Thời gian thực hiện: ${result.totalDuration}ms`); // Hiển thị chi tiết từng user console.log('\n📝 CHI TIẾT TỪNG USER:'); result.userResults.forEach((userResult, index) => { console.log(`\n${index + 1}. User: ${userResult.userId}`); console.log(` Status: ${userResult.success ? '✅ Thành công' : '❌ Thất bại'}`); if (userResult.success && userResult.messageSequenceResult) { console.log(` Tin nhắn: ${userResult.messageSequenceResult.successCount}/${userResult.messageSequenceResult.results.length} thành công`); } if (!userResult.success && userResult.error) { console.log(` Lỗi: ${userResult.error}`); } console.log(` Thời gian: ${userResult.duration}ms`); }); } catch (error) { console.error('❌ Lỗi khi gửi tin nhắn:', error.message); if (error.data) { console.error('Chi tiết lỗi:', error.data); } } } // So sánh với API cũ (sendMessageSequenceToMultipleUsers) async function sendSameMessagesToUsers() { const zalo = new ZaloSDK({ appId: 'your_app_id', appSecret: 'your_app_secret' }); const accessToken = 'your_access_token'; // API cũ - gửi cùng tin nhắn cho tất cả users const result = await zalo.consultation.sendMessageSequenceToMultipleUsers({ accessToken, userIds: ['user_1', 'user_2', 'user_3'], messages: [ { type: 'text', text: 'Tin nhắn chung cho tất cả users', delay: 1000 }, { type: 'text', text: 'Cùng một ưu đãi cho tất cả: COMMON20' } ], defaultDelay: 500, delayBetweenUsers: 1000 }); console.log('📊 Kết quả API cũ (tin nhắn chung):', result); } // Chạy ví dụ if (require.main === module) { console.log('📝 VÍ DỤ SỬ DỤNG CUSTOM MESSAGE API\n'); console.log('🎯 API MỚI - Tin nhắn tùy chỉnh cho từng user:'); sendCustomMessagesToUsers(); console.log('\n🔄 API CŨ - Tin nhắn chung cho tất cả users:'); // sendSameMessagesToUsers(); // Uncomment để chạy so sánh } module.exports = { sendCustomMessagesToUsers, sendSameMessagesToUsers };