@warriorteam/redai-zalo-sdk 1.12.3 → 1.13.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.
@@ -43,7 +43,7 @@ async function oaAuthWithPKCE() {
43
43
  console.log('- Challenge Method:', pkce.code_challenge_method);
44
44
 
45
45
  // Step 2: Create auth URL with manual PKCE
46
- const authResult = sdk.auth.createOAAuthUrl(redirectUri, undefined, true, pkce);
46
+ const authResult = sdk.auth.createOAAuthUrl(redirectUri, undefined, pkce, true);
47
47
 
48
48
  console.log('\nAuthorization URL with PKCE:', authResult.url);
49
49
  console.log('Generated State:', authResult.state);
@@ -64,8 +64,8 @@ async function oaAuthWithAutoPKCE() {
64
64
 
65
65
  const redirectUri = 'https://your-app.com/callback';
66
66
 
67
- // Create auth URL with auto-generated PKCE (usePkce=true, pkce=undefined)
68
- const authResult = sdk.auth.createOAAuthUrl(redirectUri, undefined, true);
67
+ // Create auth URL with auto-generated PKCE (pkce=undefined, usePkce=true)
68
+ const authResult = sdk.auth.createOAAuthUrl(redirectUri, undefined, undefined, true);
69
69
 
70
70
  console.log('Authorization URL with Auto PKCE:', authResult.url);
71
71
  console.log('Generated State:', authResult.state);
@@ -0,0 +1,285 @@
1
+ /**
2
+ * Ví dụ sử dụng các hàm helper để phân loại tin nhắn webhook
3
+ */
4
+
5
+ import {
6
+ isUserMessageEvent,
7
+ isGroupMessageEvent,
8
+ isOAToUserMessageEvent,
9
+ isOAToGroupMessageEvent,
10
+ getMessageDirection,
11
+ WebhookEvent,
12
+ UserMessageWebhookEvent,
13
+ GroupWebhookEvent,
14
+ OAMessageWebhookEvent,
15
+ } from '@warriorteam/redai-zalo-sdk';
16
+
17
+ /**
18
+ * Service xử lý webhook với phân loại tin nhắn
19
+ */
20
+ export class ZaloWebhookMessageHandler {
21
+ /**
22
+ * Xử lý webhook event chính
23
+ */
24
+ public handleWebhook(event: WebhookEvent): void {
25
+ console.log('=== Webhook Event Received ===');
26
+ console.log('Event Name:', event.event_name);
27
+ console.log('Timestamp:', event.timestamp);
28
+
29
+ // Phương pháp 1: Sử dụng các hàm kiểm tra riêng lẻ
30
+ this.classifyBySpecificChecks(event);
31
+
32
+ // Phương pháp 2: Sử dụng getMessageDirection
33
+ this.classifyByDirection(event);
34
+
35
+ // Xử lý tin nhắn dựa trên loại
36
+ this.processMessage(event);
37
+ }
38
+
39
+ /**
40
+ * Phân loại bằng các hàm kiểm tra riêng lẻ
41
+ */
42
+ private classifyBySpecificChecks(event: WebhookEvent): void {
43
+ console.log('\n--- Classification by Specific Checks ---');
44
+
45
+ if (isUserMessageEvent(event)) {
46
+ console.log('✅ Tin nhắn từ người dùng cá nhân');
47
+ this.logUserMessageDetails(event);
48
+ } else if (isGroupMessageEvent(event)) {
49
+ console.log('✅ Tin nhắn từ group');
50
+ this.logGroupMessageDetails(event);
51
+ } else if (isOAToUserMessageEvent(event)) {
52
+ console.log('✅ OA gửi tin nhắn cho người dùng cá nhân');
53
+ this.logOAToUserDetails(event);
54
+ } else if (isOAToGroupMessageEvent(event)) {
55
+ console.log('✅ OA gửi tin nhắn tới group');
56
+ this.logOAToGroupDetails(event);
57
+ } else {
58
+ console.log('❓ Sự kiện không phải tin nhắn hoặc không xác định');
59
+ }
60
+ }
61
+
62
+ /**
63
+ * Phân loại bằng getMessageDirection
64
+ */
65
+ private classifyByDirection(event: WebhookEvent): void {
66
+ console.log('\n--- Classification by Direction ---');
67
+
68
+ const messageInfo = getMessageDirection(event);
69
+ console.log(`Direction: ${messageInfo.direction}`);
70
+ console.log(`Target: ${messageInfo.target}`);
71
+ console.log(`Description: ${messageInfo.description}`);
72
+
73
+ // Xử lý dựa trên direction và target
74
+ const key = `${messageInfo.direction}-${messageInfo.target}`;
75
+ switch (key) {
76
+ case 'incoming-user':
77
+ console.log('🔵 Xử lý tin nhắn đến từ user cá nhân');
78
+ break;
79
+ case 'incoming-group':
80
+ console.log('🟢 Xử lý tin nhắn đến từ group');
81
+ break;
82
+ case 'outgoing-user':
83
+ console.log('🟡 Xử lý tin nhắn OA gửi cho user');
84
+ break;
85
+ case 'outgoing-group':
86
+ console.log('🟠 Xử lý tin nhắn OA gửi tới group');
87
+ break;
88
+ default:
89
+ console.log('⚪ Sự kiện không xác định');
90
+ }
91
+ }
92
+
93
+ /**
94
+ * Xử lý tin nhắn dựa trên loại
95
+ */
96
+ private processMessage(event: WebhookEvent): void {
97
+ console.log('\n--- Message Processing ---');
98
+
99
+ if (isUserMessageEvent(event)) {
100
+ this.processUserMessage(event);
101
+ } else if (isGroupMessageEvent(event)) {
102
+ this.processGroupMessage(event);
103
+ } else if (isOAToUserMessageEvent(event)) {
104
+ this.processOAToUserMessage(event);
105
+ } else if (isOAToGroupMessageEvent(event)) {
106
+ this.processOAToGroupMessage(event);
107
+ }
108
+ }
109
+
110
+ /**
111
+ * Xử lý tin nhắn từ user cá nhân
112
+ */
113
+ private processUserMessage(event: UserMessageWebhookEvent): void {
114
+ console.log('Processing user message...');
115
+
116
+ // Logic xử lý tin nhắn từ user cá nhân
117
+ // - Lưu vào database
118
+ // - Trigger AI response
119
+ // - Update conversation state
120
+
121
+ console.log('✅ User message processed');
122
+ }
123
+
124
+ /**
125
+ * Xử lý tin nhắn từ group
126
+ */
127
+ private processGroupMessage(event: GroupWebhookEvent): void {
128
+ console.log('Processing group message...');
129
+
130
+ // Logic xử lý tin nhắn từ group
131
+ // - Check if OA is mentioned
132
+ // - Apply group-specific rules
133
+ // - Handle group moderation
134
+
135
+ console.log('✅ Group message processed');
136
+ }
137
+
138
+ /**
139
+ * Xử lý tin nhắn OA gửi cho user
140
+ */
141
+ private processOAToUserMessage(event: OAMessageWebhookEvent): void {
142
+ console.log('Processing OA to user message...');
143
+
144
+ // Logic xử lý tin nhắn OA gửi
145
+ // - Log outbound message
146
+ // - Update delivery status
147
+ // - Track engagement metrics
148
+
149
+ console.log('✅ OA to user message processed');
150
+ }
151
+
152
+ /**
153
+ * Xử lý tin nhắn OA gửi tới group
154
+ */
155
+ private processOAToGroupMessage(event: GroupWebhookEvent): void {
156
+ console.log('Processing OA to group message...');
157
+
158
+ // Logic xử lý tin nhắn OA gửi tới group
159
+ // - Log group broadcast
160
+ // - Track group engagement
161
+ // - Update group statistics
162
+
163
+ console.log('✅ OA to group message processed');
164
+ }
165
+
166
+ /**
167
+ * Log chi tiết tin nhắn user
168
+ */
169
+ private logUserMessageDetails(event: UserMessageWebhookEvent): void {
170
+ console.log(` - Sender ID: ${event.sender.id}`);
171
+ console.log(` - Recipient ID: ${event.recipient.id}`);
172
+ if ('message' in event && event.message.text) {
173
+ console.log(` - Text: ${event.message.text}`);
174
+ }
175
+ }
176
+
177
+ /**
178
+ * Log chi tiết tin nhắn group
179
+ */
180
+ private logGroupMessageDetails(event: GroupWebhookEvent): void {
181
+ console.log(` - Sender ID: ${event.sender.id}`);
182
+ console.log(` - Group ID: ${event.recipient.id}`);
183
+ if ('oa_id' in event) {
184
+ console.log(` - OA ID: ${event.oa_id}`);
185
+ }
186
+ if ('message' in event && event.message.text) {
187
+ console.log(` - Text: ${event.message.text}`);
188
+ }
189
+ }
190
+
191
+ /**
192
+ * Log chi tiết OA to user
193
+ */
194
+ private logOAToUserDetails(event: OAMessageWebhookEvent): void {
195
+ console.log(` - OA ID: ${event.sender.id}`);
196
+ console.log(` - User ID: ${event.recipient.id}`);
197
+ if ('message' in event && event.message.text) {
198
+ console.log(` - Text: ${event.message.text}`);
199
+ }
200
+ }
201
+
202
+ /**
203
+ * Log chi tiết OA to group
204
+ */
205
+ private logOAToGroupDetails(event: GroupWebhookEvent): void {
206
+ console.log(` - OA ID: ${event.sender.id}`);
207
+ console.log(` - Group ID: ${event.recipient.id}`);
208
+ if ('oa_id' in event) {
209
+ console.log(` - OA ID: ${event.oa_id}`);
210
+ }
211
+ if ('message' in event && event.message.text) {
212
+ console.log(` - Text: ${event.message.text}`);
213
+ }
214
+ }
215
+ }
216
+
217
+ /**
218
+ * Ví dụ sử dụng
219
+ */
220
+ export function exampleUsage(): void {
221
+ const handler = new ZaloWebhookMessageHandler();
222
+
223
+ // Ví dụ 1: Tin nhắn từ user cá nhân
224
+ const userMessage = {
225
+ app_id: 'test-app',
226
+ user_id_by_app: 'test-user',
227
+ event_name: 'user_send_text',
228
+ timestamp: '1234567890',
229
+ sender: { id: 'user123' },
230
+ recipient: { id: 'oa123' },
231
+ message: { msg_id: 'msg123', text: 'Xin chào!' }
232
+ };
233
+
234
+ console.log('=== Example 1: User Message ===');
235
+ handler.handleWebhook(userMessage as any);
236
+
237
+ // Ví dụ 2: Tin nhắn từ group
238
+ const groupMessage = {
239
+ app_id: 'test-app',
240
+ user_id_by_app: 'test-user',
241
+ event_name: 'user_send_group_text',
242
+ timestamp: '1234567890',
243
+ oa_id: 'oa123',
244
+ sender: { id: 'user456' },
245
+ recipient: { id: 'group789' },
246
+ message: { msg_id: 'msg456', text: 'Hello group!' }
247
+ };
248
+
249
+ console.log('\n=== Example 2: Group Message ===');
250
+ handler.handleWebhook(groupMessage as any);
251
+
252
+ // Ví dụ 3: OA gửi cho user
253
+ const oaToUserMessage = {
254
+ app_id: 'test-app',
255
+ user_id_by_app: 'test-user',
256
+ event_name: 'oa_send_text',
257
+ timestamp: '1234567890',
258
+ sender: { id: 'oa123' },
259
+ recipient: { id: 'user789' },
260
+ message: { msg_id: 'msg789', text: 'Cảm ơn bạn đã liên hệ!' }
261
+ };
262
+
263
+ console.log('\n=== Example 3: OA to User Message ===');
264
+ handler.handleWebhook(oaToUserMessage as any);
265
+
266
+ // Ví dụ 4: OA gửi tới group
267
+ const oaToGroupMessage = {
268
+ app_id: 'test-app',
269
+ user_id_by_app: 'test-user',
270
+ event_name: 'oa_send_group_text',
271
+ timestamp: '1234567890',
272
+ oa_id: 'oa123',
273
+ sender: { id: 'oa123' },
274
+ recipient: { id: 'group456' },
275
+ message: { msg_id: 'msg101', text: 'Thông báo từ OA!' }
276
+ };
277
+
278
+ console.log('\n=== Example 4: OA to Group Message ===');
279
+ handler.handleWebhook(oaToGroupMessage as any);
280
+ }
281
+
282
+ // Chạy ví dụ nếu file được execute trực tiếp
283
+ if (require.main === module) {
284
+ exampleUsage();
285
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@warriorteam/redai-zalo-sdk",
3
- "version": "1.12.3",
4
- "description": "Comprehensive TypeScript/JavaScript SDK for Zalo APIs - Official Account, ZNS, Consultation Service, Group Messaging, and Social APIs",
3
+ "version": "1.13.0",
4
+ "description": "Comprehensive TypeScript/JavaScript SDK for Zalo APIs - Official Account, ZNS, Consultation Service, Group Messaging, Social APIs, and Enhanced Article Management with Auto-Pagination",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
7
7
  "scripts": {
@@ -29,7 +29,11 @@
29
29
  "notification-service",
30
30
  "consultation-service",
31
31
  "customer-support",
32
- "messaging"
32
+ "messaging",
33
+ "article-management",
34
+ "auto-pagination",
35
+ "bulk-fetch",
36
+ "progress-tracking"
33
37
  ],
34
38
  "author": "RedAI Team",
35
39
  "license": "MIT",
package/ARCHITECTURE.md DELETED
@@ -1,265 +0,0 @@
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