@warriorteam/redai-zalo-sdk 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,265 @@
1
+ # RedAI Zalo SDK Architecture
2
+
3
+ ## Overview
4
+
5
+ RedAI Zalo SDK là một TypeScript SDK hoàn chỉnh cho các API của Zalo, được thiết kế với kiến trúc modular và type-safe.
6
+
7
+ ## Cấu trúc thư mục
8
+
9
+ ```
10
+ redai-zalo-sdk/
11
+ ├── src/
12
+ │ ├── types/ # Type definitions
13
+ │ │ ├── common.ts # Common types và interfaces
14
+ │ │ ├── auth.ts # Authentication types
15
+ │ │ ├── oa.ts # Official Account types
16
+ │ │ ├── message.ts # Message types
17
+ │ │ └── webhook.ts # Webhook types
18
+ │ ├── clients/ # HTTP clients
19
+ │ │ ├── base-client.ts # Base HTTP client
20
+ │ │ └── zalo-client.ts # Zalo-specific client
21
+ │ ├── services/ # Business logic services
22
+ │ │ ├── auth.service.ts # Authentication service
23
+ │ │ ├── oa.service.ts # Official Account service
24
+ │ │ └── message.service.ts # Message service
25
+ │ ├── utils/ # Utility functions
26
+ │ ├── index.ts # Main export file
27
+ │ └── zalo-sdk.ts # Main SDK class
28
+ ├── examples/ # Usage examples
29
+ ├── dist/ # Build output
30
+ ├── package.json
31
+ ├── tsconfig.json
32
+ └── README.md
33
+ ```
34
+
35
+ ## Kiến trúc chính
36
+
37
+ ### 1. Layered Architecture
38
+
39
+ SDK được thiết kế theo kiến trúc phân lớp:
40
+
41
+ ```
42
+ ┌─────────────────┐
43
+ │ Main SDK │ ← ZaloSDK class (public API)
44
+ ├─────────────────┤
45
+ │ Services │ ← Business logic (AuthService, OAService, MessageService)
46
+ ├─────────────────┤
47
+ │ Clients │ ← HTTP communication (BaseClient, ZaloClient)
48
+ ├─────────────────┤
49
+ │ Types │ ← Type definitions và interfaces
50
+ └─────────────────┘
51
+ ```
52
+
53
+ ### 2. Core Components
54
+
55
+ #### ZaloSDK (Main Class)
56
+ - Entry point cho tất cả các chức năng
57
+ - Khởi tạo và quản lý các services
58
+ - Cung cấp quick methods cho các tác vụ phổ biến
59
+ - Quản lý configuration và lifecycle
60
+
61
+ #### BaseClient
62
+ - HTTP client cơ bản với axios
63
+ - Retry mechanism
64
+ - Error handling
65
+ - Request/response logging
66
+ - File upload support
67
+
68
+ #### ZaloClient
69
+ - Extends BaseClient
70
+ - Zalo-specific endpoints
71
+ - API versioning support
72
+ - OAuth và ZNS endpoint handling
73
+
74
+ #### Services
75
+ - **AuthService**: OAuth flows, token management
76
+ - **OAService**: Official Account operations
77
+ - **MessageService**: Message sending và file upload
78
+
79
+ ### 3. Type System
80
+
81
+ #### Comprehensive Types
82
+ - Tất cả API responses được type-safe
83
+ - Union types cho message types
84
+ - Enum cho constants
85
+ - Generic types cho reusability
86
+
87
+ #### Error Handling
88
+ - Custom `ZaloSDKError` class
89
+ - Structured error information
90
+ - Error code mapping
91
+
92
+ ### 4. Configuration
93
+
94
+ ```typescript
95
+ interface ZaloSDKConfig {
96
+ appId: string;
97
+ appSecret: string;
98
+ timeout?: number;
99
+ debug?: boolean;
100
+ apiBaseUrl?: string;
101
+ retry?: {
102
+ attempts?: number;
103
+ delay?: number;
104
+ };
105
+ }
106
+ ```
107
+
108
+ ## Design Patterns
109
+
110
+ ### 1. Builder Pattern
111
+ SDK configuration với default values và validation.
112
+
113
+ ### 2. Service Pattern
114
+ Mỗi service chịu trách nhiệm cho một domain cụ thể.
115
+
116
+ ### 3. Factory Pattern
117
+ Client creation và service initialization.
118
+
119
+ ### 4. Strategy Pattern
120
+ Different authentication flows (OA vs Social).
121
+
122
+ ### 5. Observer Pattern
123
+ Webhook event handling (planned).
124
+
125
+ ## Key Features
126
+
127
+ ### 1. Type Safety
128
+ - Full TypeScript support
129
+ - Comprehensive type definitions
130
+ - Generic types cho flexibility
131
+ - Union types cho message variants
132
+
133
+ ### 2. Error Handling
134
+ - Structured error responses
135
+ - Retry mechanism
136
+ - Detailed error information
137
+ - Error code mapping
138
+
139
+ ### 3. Authentication
140
+ - OAuth 2.0 flows
141
+ - PKCE support
142
+ - Token refresh
143
+ - Multiple auth scopes
144
+
145
+ ### 4. Extensibility
146
+ - Modular architecture
147
+ - Easy to add new services
148
+ - Plugin-ready design
149
+ - Custom request support
150
+
151
+ ### 5. Developer Experience
152
+ - IntelliSense support
153
+ - Comprehensive documentation
154
+ - Usage examples
155
+ - Debug logging
156
+
157
+ ## API Design Principles
158
+
159
+ ### 1. Consistency
160
+ - Consistent naming conventions
161
+ - Uniform error handling
162
+ - Standard response formats
163
+
164
+ ### 2. Simplicity
165
+ - Easy-to-use public API
166
+ - Quick methods cho common tasks
167
+ - Sensible defaults
168
+
169
+ ### 3. Flexibility
170
+ - Low-level access khi cần
171
+ - Custom request support
172
+ - Configurable behavior
173
+
174
+ ### 4. Reliability
175
+ - Retry mechanisms
176
+ - Error recovery
177
+ - Connection testing
178
+
179
+ ## Future Enhancements
180
+
181
+ ### 1. Additional Services
182
+ - ZNS Service (Zalo Notification Service)
183
+ - User Management Service
184
+ - Group Management Service
185
+ - Webhook Service
186
+
187
+ ### 2. Advanced Features
188
+ - Rate limiting
189
+ - Caching
190
+ - Batch operations
191
+ - Real-time subscriptions
192
+
193
+ ### 3. Developer Tools
194
+ - CLI tools
195
+ - Testing utilities
196
+ - Mock server
197
+ - Documentation generator
198
+
199
+ ## Testing Strategy
200
+
201
+ ### 1. Unit Tests
202
+ - Service logic testing
203
+ - Type validation
204
+ - Error handling
205
+
206
+ ### 2. Integration Tests
207
+ - API endpoint testing
208
+ - Authentication flows
209
+ - File upload/download
210
+
211
+ ### 3. E2E Tests
212
+ - Complete workflows
213
+ - Real API interactions
214
+ - Error scenarios
215
+
216
+ ## Performance Considerations
217
+
218
+ ### 1. HTTP Optimization
219
+ - Connection pooling
220
+ - Request compression
221
+ - Timeout management
222
+
223
+ ### 2. Memory Management
224
+ - Efficient data structures
225
+ - Stream processing cho large files
226
+ - Garbage collection friendly
227
+
228
+ ### 3. Network Efficiency
229
+ - Batch requests
230
+ - Caching strategies
231
+ - Retry with backoff
232
+
233
+ ## Security
234
+
235
+ ### 1. Token Management
236
+ - Secure token storage
237
+ - Automatic refresh
238
+ - Token validation
239
+
240
+ ### 2. Request Security
241
+ - HTTPS only
242
+ - Request signing
243
+ - Parameter validation
244
+
245
+ ### 3. Error Information
246
+ - Sanitized error messages
247
+ - No sensitive data in logs
248
+ - Secure debugging
249
+
250
+ ## Deployment
251
+
252
+ ### 1. Package Distribution
253
+ - NPM package
254
+ - TypeScript declarations
255
+ - Source maps
256
+
257
+ ### 2. Versioning
258
+ - Semantic versioning
259
+ - Backward compatibility
260
+ - Migration guides
261
+
262
+ ### 3. Documentation
263
+ - API documentation
264
+ - Usage examples
265
+ - Migration guides
package/CHANGELOG.md ADDED
@@ -0,0 +1,154 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [1.2.0] - 2025-01-08
9
+
10
+ ### Added
11
+
12
+ #### 🆕 ConsultationService - Customer Support Messaging
13
+ - **New Service**: `ConsultationService` for sending customer support messages within 48-hour interaction window
14
+ - **Text Messages**: Send consultation text messages with automatic validation (max 2000 characters)
15
+ - **Image Messages**: Send consultation images for visual support and guides
16
+ - **File Messages**: Send consultation file attachments (manuals, guides, documents)
17
+ - **Sticker Messages**: Send consultation sticker messages for friendly interactions
18
+ - **General Messages**: Send any type of consultation message with unified interface
19
+
20
+ #### 📚 Documentation & Examples
21
+ - **Comprehensive Guide**: New `docs/CONSULTATION_SERVICE.md` with detailed usage instructions
22
+ - **Practical Examples**: New `examples/consultation-service-example.ts` with 6 real-world scenarios
23
+ - **Smart Customer Support**: Example implementation of intelligent customer support bot
24
+ - **Webhook Integration**: Complete webhook integration examples for consultation service
25
+ - **Error Handling**: Detailed error handling and retry mechanism examples
26
+
27
+ #### 🔧 SDK Integration
28
+ - **Quick Access**: Available via `zalo.consultation` property
29
+ - **Quick Methods**: Added `zalo.sendConsultationText()` and `zalo.sendConsultationImage()` convenience methods
30
+ - **Type Safety**: Full TypeScript support with comprehensive type definitions
31
+ - **Error Handling**: Enhanced error handling with `ZaloSDKError` for consultation-specific errors
32
+
33
+ #### 📖 Documentation Updates
34
+ - **README.md**: Updated with ConsultationService examples and documentation links
35
+ - **SERVICES_ADDED.md**: Added detailed ConsultationService documentation
36
+ - **Keywords**: Enhanced package keywords for better discoverability
37
+
38
+ ### Technical Details
39
+
40
+ #### Consultation Service Features
41
+ - **48-Hour Window**: Enforces Zalo's 48-hour interaction window for consultation messages
42
+ - **Content Validation**: Automatic validation of message content and format
43
+ - **Quota Management**: Built-in quota tracking and management
44
+ - **Anti-Spam**: Follows Zalo's anti-spam guidelines and best practices
45
+ - **Retry Logic**: Built-in retry mechanism for failed requests
46
+
47
+ #### Usage Conditions
48
+ - Messages must be sent within 48 hours of last user interaction
49
+ - Content must be consultation/support related (no direct advertising)
50
+ - User must have followed the OA and not blocked it
51
+ - No daily limit but must follow anti-spam guidelines
52
+
53
+ #### Integration Points
54
+ - Seamless integration with existing webhook system
55
+ - Compatible with all existing SDK features
56
+ - Follows established SDK patterns and conventions
57
+ - Full backward compatibility maintained
58
+
59
+ ### Examples Added
60
+
61
+ 1. **Basic Consultation**: Simple text message consultation
62
+ 2. **Image Support**: Sending images for visual guidance
63
+ 3. **File Attachments**: Sending documents and manuals
64
+ 4. **Smart Customer Support**: AI-powered customer support bot
65
+ 5. **Retry Mechanism**: Robust error handling and retry logic
66
+ 6. **Webhook Integration**: Complete webhook event handling
67
+
68
+ ### Files Added/Modified
69
+
70
+ #### New Files
71
+ - `src/services/consultation.service.ts` - Main ConsultationService implementation
72
+ - `docs/CONSULTATION_SERVICE.md` - Comprehensive documentation
73
+ - `examples/consultation-service-example.ts` - Practical examples
74
+ - `CHANGELOG.md` - This changelog file
75
+
76
+ #### Modified Files
77
+ - `README.md` - Added ConsultationService documentation and examples
78
+ - `SERVICES_ADDED.md` - Added ConsultationService details
79
+ - `package.json` - Updated version, description, keywords, and scripts
80
+ - `src/index.ts` - Export ConsultationService types and classes
81
+ - `src/zalo-sdk.ts` - Integrated ConsultationService into main SDK
82
+
83
+ ### Breaking Changes
84
+ None. This release maintains full backward compatibility.
85
+
86
+ ### Migration Guide
87
+ No migration required. All existing code will continue to work unchanged.
88
+
89
+ To use the new ConsultationService:
90
+
91
+ ```typescript
92
+ import { ZaloSDK } from "@warriorteam/redai-zalo-sdk";
93
+
94
+ const zalo = new ZaloSDK({
95
+ appId: "your-app-id",
96
+ appSecret: "your-app-secret"
97
+ });
98
+
99
+ // Use consultation service
100
+ await zalo.consultation.sendTextMessage(
101
+ accessToken,
102
+ { user_id: "user-id" },
103
+ { type: "text", text: "How can I help you?" }
104
+ );
105
+
106
+ // Or use quick methods
107
+ await zalo.sendConsultationText(accessToken, "user-id", "Hello!");
108
+ ```
109
+
110
+ ---
111
+
112
+ ## [1.1.1] - 2024-12-XX
113
+
114
+ ### Fixed
115
+ - Bug fixes and stability improvements
116
+ - Enhanced error handling
117
+ - Documentation updates
118
+
119
+ ### Added
120
+ - Additional webhook event types
121
+ - Improved TypeScript definitions
122
+
123
+ ---
124
+
125
+ ## [1.1.0] - 2024-11-XX
126
+
127
+ ### Added
128
+ - Group Management Service
129
+ - Article Management Service
130
+ - Video Upload Service
131
+ - Enhanced webhook handling
132
+ - Comprehensive documentation
133
+
134
+ ---
135
+
136
+ ## [1.0.0] - 2024-10-XX
137
+
138
+ ### Added
139
+ - Initial release
140
+ - Official Account API support
141
+ - ZNS (Zalo Notification Service) support
142
+ - Social API support
143
+ - Authentication flow
144
+ - Basic messaging capabilities
145
+ - TypeScript support
146
+ - Comprehensive error handling
147
+
148
+ ### Features
149
+ - OAuth 2.0 authentication
150
+ - Message sending (text, image, file, sticker)
151
+ - User management
152
+ - Template management
153
+ - Quota monitoring
154
+ - Webhook event handling
package/README.md CHANGED
@@ -3,6 +3,7 @@
3
3
  A comprehensive TypeScript/JavaScript SDK for Zalo APIs, providing easy-to-use interfaces for:
4
4
 
5
5
  - **Official Account (OA) API** - Manage your Zalo Official Account
6
+ - **Consultation Service** - Send customer support messages within 48-hour window
6
7
  - **Zalo Notification Service (ZNS)** - Send template-based notification messages
7
8
  - **Social API** - Access user social information and authentication
8
9
  - **Group Message Framework (GMF)** - Send messages to Zalo groups
@@ -25,9 +26,18 @@ A comprehensive TypeScript/JavaScript SDK for Zalo APIs, providing easy-to-use i
25
26
  ## Installation
26
27
 
27
28
  ```bash
28
- npm install redai-zalo-sdk
29
+ npm install @warriorteam/redai-zalo-sdk
29
30
  ```
30
31
 
32
+ ## 📚 Documentation
33
+
34
+ - **[Webhook Events Guide](./docs/WEBHOOK_EVENTS.md)** - Complete guide for all 70+ webhook event types
35
+ - **[Architecture Overview](./ARCHITECTURE.md)** - SDK architecture and design patterns
36
+ - **[Services Added](./SERVICES_ADDED.md)** - Detailed breakdown of all services and features
37
+ - **[Group Management](./docs/GROUP_MANAGEMENT.md)** - Group messaging and management
38
+ - **[Article Management](./docs/ARTICLE_MANAGEMENT.md)** - Content and article management
39
+ - **[Consultation Service](./docs/CONSULTATION_SERVICE.md)** - Customer service messaging guide
40
+
31
41
  ## Development
32
42
 
33
43
  ### Build from source
@@ -52,7 +62,7 @@ npm run dev
52
62
  ### Initialize the SDK
53
63
 
54
64
  ```typescript
55
- import { ZaloSDK } from "redai-zalo-sdk";
65
+ import { ZaloSDK } from "@warriorteam/redai-zalo-sdk";
56
66
 
57
67
  const zalo = new ZaloSDK({
58
68
  appId: "your-app-id",
@@ -311,6 +321,49 @@ For support and questions:
311
321
  - Create an issue on GitHub
312
322
  - Contact RedAI team
313
323
 
324
+ ### Consultation Service (Customer Support)
325
+
326
+ ```typescript
327
+ // Send consultation text message
328
+ await zalo.consultation.sendTextMessage(accessToken,
329
+ { user_id: "user-id" },
330
+ {
331
+ type: "text",
332
+ text: "Xin chào! Tôi có thể hỗ trợ gì cho bạn?"
333
+ }
334
+ );
335
+
336
+ // Send consultation image with guide
337
+ await zalo.consultation.sendImageMessage(accessToken,
338
+ { user_id: "user-id" },
339
+ {
340
+ type: "image",
341
+ attachment: {
342
+ type: "image",
343
+ payload: {
344
+ url: "https://example.com/support-guide.jpg"
345
+ }
346
+ }
347
+ }
348
+ );
349
+
350
+ // Send file attachment for support
351
+ await zalo.consultation.sendFileMessage(accessToken,
352
+ { user_id: "user-id" },
353
+ {
354
+ type: "file",
355
+ url: "https://example.com/manual.pdf",
356
+ filename: "User Manual.pdf",
357
+ attachment: {
358
+ type: "file",
359
+ payload: {
360
+ url: "https://example.com/manual.pdf"
361
+ }
362
+ }
363
+ }
364
+ );
365
+ ```
366
+
314
367
  ### ZNS (Zalo Notification Service)
315
368
 
316
369
  ```typescript
@@ -430,6 +483,55 @@ const friends = await zalo.social.getFriendsList(accessToken);
430
483
  await zalo.social.postToTimeline(accessToken, "Hello from Zalo SDK!");
431
484
  ```
432
485
 
486
+ ## 🔔 Webhook Events
487
+
488
+ The SDK provides comprehensive webhook event handling with **70+ event types**:
489
+
490
+ ```typescript
491
+ import { WebhookHandlers } from "@warriorteam/redai-zalo-sdk";
492
+
493
+ const handlers: WebhookHandlers = {
494
+ // User message events
495
+ user_send_text: async (event) => {
496
+ console.log("User sent:", event.message.text);
497
+ },
498
+
499
+ // Group events
500
+ user_send_group_audio: async (event) => {
501
+ console.log("Audio in group:", event.message.attachments[0].payload.url);
502
+ },
503
+
504
+ // ZNS events
505
+ change_template_status: async (event) => {
506
+ console.log("Template status:", event.status);
507
+ },
508
+
509
+ // Widget events
510
+ widget_interaction_accepted: async (event) => {
511
+ console.log("Widget accepted:", event.data.user_external_id);
512
+ },
513
+
514
+ // System events
515
+ permission_revoked: async (event) => {
516
+ console.log("Permission revoked by:", event.data.action_by);
517
+ },
518
+ };
519
+ ```
520
+
521
+ ### Event Categories:
522
+
523
+ - **User Message Events** (11 types): text, image, video, audio, file, sticker, gif, location, link, business card, reaction
524
+ - **OA Message Events** (11 types): All message types + anonymous + template
525
+ - **Group Events** (22 types): Create, join, admin, leave + all message types for both user and OA
526
+ - **ZNS Events** (8 types): Quota, template, journey, delivery, status changes
527
+ - **Widget Events** (2 types): Interaction accepted, sync failures
528
+ - **System Events** (4 types): Permission, extension, user info, tags
529
+ - **Call Events** (2 types): OA call user, user call OA
530
+ - **Anonymous Events** (4 types): Anonymous chat support
531
+ - **Shop Events** (1 type): Order management
532
+
533
+ For complete webhook documentation, see [Webhook Events Guide](./docs/WEBHOOK_EVENTS.md).
534
+
433
535
  ## Changelog
434
536
 
435
537
  ### v1.0.0