@warriorteam/redai-zalo-sdk 1.3.0 → 1.4.1

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.
Files changed (76) hide show
  1. package/README.md +565 -550
  2. package/dist/index.d.ts +0 -2
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +1 -5
  5. package/dist/index.js.map +1 -1
  6. package/dist/services/article.service.d.ts +1 -1
  7. package/dist/services/article.service.d.ts.map +1 -1
  8. package/dist/services/article.service.js +24 -16
  9. package/dist/services/article.service.js.map +1 -1
  10. package/dist/services/auth.service.d.ts +1 -0
  11. package/dist/services/auth.service.d.ts.map +1 -1
  12. package/dist/services/auth.service.js +23 -9
  13. package/dist/services/auth.service.js.map +1 -1
  14. package/dist/services/consultation.service.d.ts +63 -16
  15. package/dist/services/consultation.service.d.ts.map +1 -1
  16. package/dist/services/consultation.service.js +264 -49
  17. package/dist/services/consultation.service.js.map +1 -1
  18. package/dist/services/general-message.service.d.ts +2 -25
  19. package/dist/services/general-message.service.d.ts.map +1 -1
  20. package/dist/services/general-message.service.js +11 -112
  21. package/dist/services/general-message.service.js.map +1 -1
  22. package/dist/services/group-management.service.d.ts +1 -1
  23. package/dist/services/group-management.service.d.ts.map +1 -1
  24. package/dist/services/group-management.service.js +59 -27
  25. package/dist/services/group-management.service.js.map +1 -1
  26. package/dist/services/group-message.service.d.ts +1 -1
  27. package/dist/services/group-message.service.d.ts.map +1 -1
  28. package/dist/services/group-message.service.js +49 -23
  29. package/dist/services/group-message.service.js.map +1 -1
  30. package/dist/services/message-management.service.d.ts +21 -2
  31. package/dist/services/message-management.service.d.ts.map +1 -1
  32. package/dist/services/message-management.service.js +83 -7
  33. package/dist/services/message-management.service.js.map +1 -1
  34. package/dist/services/oa.service.d.ts +1 -0
  35. package/dist/services/oa.service.d.ts.map +1 -1
  36. package/dist/services/oa.service.js +23 -5
  37. package/dist/services/oa.service.js.map +1 -1
  38. package/dist/services/user.service.d.ts +108 -18
  39. package/dist/services/user.service.d.ts.map +1 -1
  40. package/dist/services/user.service.js +260 -59
  41. package/dist/services/user.service.js.map +1 -1
  42. package/dist/services/video-upload.service.d.ts +1 -1
  43. package/dist/services/video-upload.service.d.ts.map +1 -1
  44. package/dist/services/video-upload.service.js +11 -8
  45. package/dist/services/video-upload.service.js.map +1 -1
  46. package/dist/services/zns.service.d.ts +88 -21
  47. package/dist/services/zns.service.d.ts.map +1 -1
  48. package/dist/services/zns.service.js +157 -42
  49. package/dist/services/zns.service.js.map +1 -1
  50. package/dist/types/group.d.ts +5 -5
  51. package/dist/types/group.d.ts.map +1 -1
  52. package/dist/types/user.d.ts +155 -12
  53. package/dist/types/user.d.ts.map +1 -1
  54. package/dist/types/user.js.map +1 -1
  55. package/dist/types/webhook.d.ts +8 -0
  56. package/dist/types/webhook.d.ts.map +1 -1
  57. package/dist/types/webhook.js.map +1 -1
  58. package/dist/types/zns.d.ts +67 -33
  59. package/dist/types/zns.d.ts.map +1 -1
  60. package/dist/zalo-sdk.d.ts +3 -11
  61. package/dist/zalo-sdk.d.ts.map +1 -1
  62. package/dist/zalo-sdk.js +0 -10
  63. package/dist/zalo-sdk.js.map +1 -1
  64. package/docs/CONSULTATION_SERVICE.md +512 -330
  65. package/docs/GROUP_MANAGEMENT.md +2 -2
  66. package/docs/USER_MANAGEMENT.md +481 -1248
  67. package/docs/WEBHOOK_EVENTS.md +55 -3
  68. package/package.json +1 -1
  69. package/dist/services/tag.service.d.ts +0 -144
  70. package/dist/services/tag.service.d.ts.map +0 -1
  71. package/dist/services/tag.service.js +0 -184
  72. package/dist/services/tag.service.js.map +0 -1
  73. package/dist/services/user-management.service.d.ts +0 -117
  74. package/dist/services/user-management.service.d.ts.map +0 -1
  75. package/dist/services/user-management.service.js +0 -239
  76. package/dist/services/user-management.service.js.map +0 -1
package/README.md CHANGED
@@ -1,550 +1,565 @@
1
- # RedAI Zalo SDK
2
-
3
- A comprehensive TypeScript/JavaScript SDK for Zalo APIs, providing easy-to-use interfaces for:
4
-
5
- - **Official Account (OA) API** - Manage your Zalo Official Account
6
- - **Consultation Service** - Send customer support messages within 48-hour window
7
- - **Zalo Notification Service (ZNS)** - Send template-based notification messages
8
- - **Social API** - Access user social information and authentication
9
- - **Group Message Framework (GMF)** - Send messages to Zalo groups
10
- - **User Management** - Comprehensive user profile and tag management
11
- - **Content Management** - Upload and manage media content (images, files, articles)
12
- - **Video Upload** - Upload and manage video content with processing
13
- - **Tag Management** - User tagging and segmentation
14
- - **Webhook handling** - Process Zalo webhook events
15
-
16
- ## Features
17
-
18
- - 🚀 **TypeScript Support** - Full type safety and IntelliSense
19
- - 🔐 **OAuth 2.0 Flow** - Complete authentication handling
20
- - 🔄 **Auto Retry** - Built-in retry mechanism for failed requests
21
- - 📝 **Comprehensive Logging** - Debug and monitor API calls
22
- - 🛡️ **Error Handling** - Detailed error information and handling
23
- - 📦 **Zero Dependencies** - Only requires axios and form-data
24
- - 🎯 **Promise-based** - Modern async/await support
25
-
26
- ## Installation
27
-
28
- ```bash
29
- npm install @warriorteam/redai-zalo-sdk
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
-
41
- ## Development
42
-
43
- ### Build from source
44
-
45
- ```bash
46
- # Clone the repository
47
- git clone https://github.com/redai/redai-zalo-sdk.git
48
- cd redai-zalo-sdk
49
-
50
- # Install dependencies
51
- npm install
52
-
53
- # Build the SDK
54
- npm run build
55
-
56
- # Run examples
57
- npm run dev
58
- ```
59
-
60
- ## Quick Start
61
-
62
- ### Initialize the SDK
63
-
64
- ```typescript
65
- import { ZaloSDK } from "@warriorteam/redai-zalo-sdk";
66
-
67
- const zalo = new ZaloSDK({
68
- appId: "your-app-id",
69
- appSecret: "your-app-secret",
70
- debug: true, // Enable debug logging
71
- });
72
- ```
73
-
74
- ### Authentication Flow
75
-
76
- #### Official Account (OA) Authentication
77
-
78
- ```typescript
79
- // 1. Create authorization URL
80
- const authUrl = zalo.createOAAuthUrl("https://your-app.com/callback");
81
- console.log("Visit:", authUrl);
82
-
83
- // 2. Exchange authorization code for access token
84
- const accessToken = await zalo.getOAAccessToken(
85
- "authorization-code-from-callback",
86
- "https://your-app.com/callback"
87
- );
88
-
89
- console.log("Access Token:", accessToken.access_token);
90
- ```
91
-
92
- #### Social API Authentication
93
-
94
- ```typescript
95
- // 1. Generate PKCE for security (recommended)
96
- const pkce = zalo.generatePKCE();
97
-
98
- // 2. Create authorization URL
99
- const authUrl = zalo.createSocialAuthUrl("https://your-app.com/callback");
100
-
101
- // 3. Exchange code for access token
102
- const accessToken = await zalo.getSocialAccessToken(
103
- "authorization-code",
104
- "https://your-app.com/callback",
105
- pkce.code_verifier
106
- );
107
- ```
108
-
109
- ### Official Account Operations
110
-
111
- ```typescript
112
- // Get OA information
113
- const oaInfo = await zalo.getOAInfo(accessToken.access_token);
114
- console.log("OA Name:", oaInfo.name);
115
- console.log("Followers:", oaInfo.num_follower);
116
-
117
- // Check message quota
118
- const quota = await zalo.getMessageQuota(accessToken.access_token);
119
- console.log("Daily Quota:", quota.daily_quota);
120
- console.log("Remaining:", quota.remaining_quota);
121
-
122
- // Get detailed quota information
123
- const detailedQuota = await zalo.oa.getQuotaSummary(accessToken.access_token);
124
- console.log("Consultation Quota:", detailedQuota.consultation);
125
- console.log("Transaction Quota:", detailedQuota.transaction);
126
- ```
127
-
128
- ### Social API Operations
129
-
130
- ```typescript
131
- // Get user information
132
- const userInfo = await zalo.getSocialUserInfo(
133
- accessToken.access_token,
134
- "id,name,picture,birthday"
135
- );
136
-
137
- console.log("User ID:", userInfo.id);
138
- console.log("Name:", userInfo.name);
139
- console.log("Avatar:", userInfo.picture?.data.url);
140
- ```
141
-
142
- ### Token Management
143
-
144
- ```typescript
145
- // Refresh OA access token
146
- const newOAToken = await zalo.refreshOAAccessToken(refreshToken);
147
-
148
- // Refresh Social access token
149
- const newSocialToken = await zalo.refreshSocialAccessToken(refreshToken);
150
-
151
- // Validate token
152
- const isValid = await zalo.validateAccessToken(accessToken.access_token, "oa");
153
- ```
154
-
155
- ## Advanced Usage
156
-
157
- ### Custom API Requests
158
-
159
- ```typescript
160
- // Make custom API calls
161
- const customData = await zalo.customRequest(
162
- "POST",
163
- "/v3.0/oa/message/cs",
164
- accessToken.access_token,
165
- {
166
- recipient: { user_id: "user-id" },
167
- message: { text: "Hello from SDK!" },
168
- }
169
- );
170
- ```
171
-
172
- ### File Upload
173
-
174
- ```typescript
175
- import fs from "fs";
176
-
177
- // Upload image
178
- const fileBuffer = fs.readFileSync("image.jpg");
179
- const uploadResult = await zalo.uploadFile(
180
- "/v2.0/oa/upload/image",
181
- accessToken.access_token,
182
- fileBuffer,
183
- "image.jpg"
184
- );
185
-
186
- console.log("Uploaded URL:", uploadResult.data.url);
187
- ```
188
-
189
- ### Error Handling
190
-
191
- ```typescript
192
- import { ZaloSDKError } from "redai-zalo-sdk";
193
-
194
- try {
195
- const oaInfo = await zalo.getOAInfo(accessToken.access_token);
196
- } catch (error) {
197
- if (error instanceof ZaloSDKError) {
198
- console.error("Zalo API Error:", error.message);
199
- console.error("Error Code:", error.code);
200
- console.error("Details:", error.details);
201
- } else {
202
- console.error("Unexpected error:", error);
203
- }
204
- }
205
- ```
206
-
207
- ## Configuration Options
208
-
209
- ```typescript
210
- const zalo = new ZaloSDK({
211
- appId: "your-app-id",
212
- appSecret: "your-app-secret",
213
-
214
- // Optional configurations
215
- timeout: 30000, // Request timeout in ms (default: 30000)
216
- debug: false, // Enable debug logging (default: false)
217
- apiBaseUrl: "https://openapi.zalo.me", // Custom API base URL
218
-
219
- // Retry configuration
220
- retry: {
221
- attempts: 3, // Number of retry attempts (default: 3)
222
- delay: 1000, // Delay between retries in ms (default: 1000)
223
- },
224
- });
225
- ```
226
-
227
- ## API Reference
228
-
229
- ### ZaloSDK Class
230
-
231
- #### Constructor
232
-
233
- - `new ZaloSDK(config: ZaloSDKConfig)`
234
-
235
- #### Authentication Methods
236
-
237
- - `createOAAuthUrl(redirectUri: string, state?: string): string`
238
- - `createSocialAuthUrl(redirectUri: string, state?: string): string`
239
- - `getOAAccessToken(code: string, redirectUri: string): Promise<AccessToken>`
240
- - `getSocialAccessToken(code: string, redirectUri: string, codeVerifier?: string): Promise<AccessToken>`
241
- - `refreshOAAccessToken(refreshToken: string): Promise<AccessToken>`
242
- - `refreshSocialAccessToken(refreshToken: string): Promise<AccessToken>`
243
-
244
- #### OA Methods
245
-
246
- - `getOAInfo(accessToken: string): Promise<OAInfo>`
247
- - `getMessageQuota(accessToken: string): Promise<MessageQuota>`
248
-
249
- #### Social Methods
250
-
251
- - `getSocialUserInfo(accessToken: string, fields?: string): Promise<SocialUserInfo>`
252
-
253
- #### Utility Methods
254
-
255
- - `validateAccessToken(accessToken: string, scope?: 'oa' | 'social'): Promise<boolean>`
256
- - `generatePKCE(): PKCEConfig`
257
- - `testConnection(): Promise<boolean>`
258
-
259
- ### Services
260
-
261
- #### AuthService
262
-
263
- - Complete OAuth 2.0 flow handling
264
- - PKCE support for Social API
265
- - Token validation and refresh
266
-
267
- #### OAService
268
-
269
- - Official Account information management
270
- - Quota monitoring and management
271
- - Profile updates
272
-
273
- ## Error Handling
274
-
275
- The SDK throws `ZaloSDKError` for all Zalo API related errors:
276
-
277
- ```typescript
278
- class ZaloSDKError extends Error {
279
- code: number; // Zalo API error code
280
- details?: any; // Additional error details
281
- }
282
- ```
283
-
284
- Common error codes:
285
-
286
- - `-216`: Invalid access token
287
- - `-201`: Invalid parameters
288
- - `-223`: Quota exceeded
289
-
290
- ## TypeScript Support
291
-
292
- The SDK is written in TypeScript and provides comprehensive type definitions:
293
-
294
- ```typescript
295
- import {
296
- ZaloSDK,
297
- ZaloSDKConfig,
298
- AccessToken,
299
- OAInfo,
300
- SocialUserInfo,
301
- ZaloSDKError,
302
- } from "redai-zalo-sdk";
303
- ```
304
-
305
- ## Contributing
306
-
307
- 1. Fork the repository
308
- 2. Create your feature branch (`git checkout -b feature/amazing-feature`)
309
- 3. Commit your changes (`git commit -m 'Add some amazing feature'`)
310
- 4. Push to the branch (`git push origin feature/amazing-feature`)
311
- 5. Open a Pull Request
312
-
313
- ## License
314
-
315
- This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
316
-
317
- ## Support
318
-
319
- For support and questions:
320
-
321
- - Create an issue on GitHub
322
- - Contact RedAI team
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
-
367
- ### ZNS (Zalo Notification Service)
368
-
369
- ```typescript
370
- // Send ZNS notification
371
- await zalo.zns.sendMessage(accessToken, {
372
- phone: "0123456789",
373
- template_id: "your-template-id",
374
- template_data: {
375
- customer_name: "John Doe",
376
- order_id: "12345",
377
- },
378
- });
379
-
380
- // Get ZNS quota
381
- const quota = await zalo.zns.getQuotaInfo(accessToken);
382
-
383
- // Manage ZNS templates
384
- const templates = await zalo.zns.getTemplateList(accessToken);
385
- const template = await zalo.zns.createTemplate(accessToken, {
386
- templateName: "Order Confirmation",
387
- templateContent:
388
- "Hello {{customer_name}}, your order {{order_id}} is confirmed.",
389
- templateType: 3, // Confirmation type
390
- });
391
- ```
392
-
393
- ### Group Messaging
394
-
395
- ```typescript
396
- // Send text message to group
397
- await zalo.groupMessage.sendTextMessage(accessToken, groupId, {
398
- type: "text",
399
- text: "Hello everyone!",
400
- });
401
-
402
- // Send image to group
403
- await zalo.groupMessage.sendImageMessage(accessToken, groupId, {
404
- type: "image",
405
- imageUrl: "https://example.com/image.jpg",
406
- caption: "Check this out!",
407
- });
408
-
409
- // Get group information
410
- const groupInfo = await zalo.groupMessage.getGroupInfo(accessToken, groupId);
411
- const members = await zalo.groupMessage.getGroupMembers(accessToken, groupId);
412
- ```
413
-
414
- ### User Management
415
-
416
- ```typescript
417
- // Get user profile
418
- const profile = await zalo.userManagement.getUserProfile(accessToken, userId);
419
-
420
- // Tag management
421
- await zalo.tag.createTag(accessToken, "VIP Customer");
422
- await zalo.tag.tagUser(accessToken, userId, ["VIP Customer", "Premium"]);
423
- const userTags = await zalo.tag.getUserTags(accessToken, userId);
424
-
425
- // Get followers list
426
- const followers = await zalo.userManagement.getFollowersList(accessToken);
427
- ```
428
-
429
- ### Content Management
430
-
431
- ```typescript
432
- // Upload image
433
- const imageResult = await zalo.content.uploadImage(accessToken, imageBuffer);
434
-
435
- // Create article
436
- const article = await zalo.content.createArticle(accessToken, {
437
- title: "Welcome to our service",
438
- body: "Article content here...",
439
- cover_photo_id: imageResult.data.attachment_id,
440
- });
441
-
442
- // Share article to user
443
- await zalo.content.shareArticle(accessToken, userId, article.data.id);
444
- ```
445
-
446
- ### Video Upload
447
-
448
- ```typescript
449
- // Upload video
450
- const uploadResult = await zalo.videoUpload.uploadVideo(
451
- accessToken,
452
- videoBuffer,
453
- "video.mp4"
454
- );
455
-
456
- // Wait for processing completion
457
- const finalResult = await zalo.videoUpload.waitForUploadCompletion(
458
- accessToken,
459
- uploadResult.data.token
460
- );
461
-
462
- if (finalResult.status === "ready") {
463
- // Send video message
464
- await zalo.videoUpload.sendVideoMessage(
465
- accessToken,
466
- userId,
467
- finalResult.attachment_id,
468
- "Check out this video!"
469
- );
470
- }
471
- ```
472
-
473
- ### Social API
474
-
475
- ```typescript
476
- // Get user social information
477
- const userInfo = await zalo.social.getUserInfo(accessToken);
478
-
479
- // Get friends list
480
- const friends = await zalo.social.getFriendsList(accessToken);
481
-
482
- // Post to timeline
483
- await zalo.social.postToTimeline(accessToken, "Hello from Zalo SDK!");
484
- ```
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
-
535
- ## Changelog
536
-
537
- ### v1.0.0
538
-
539
- - Initial release
540
- - Official Account API support
541
- - ZNS (Zalo Notification Service) support
542
- - Group Message Framework (GMF) support
543
- - Social API support
544
- - User Management features
545
- - Content and Video Upload capabilities
546
- - Tag Management system
547
- - Comprehensive webhook handling
548
- - Social API support
549
- - Authentication flow
550
- - TypeScript support
1
+ # RedAI Zalo SDK
2
+
3
+ A comprehensive TypeScript/JavaScript SDK for Zalo APIs, providing easy-to-use interfaces for:
4
+
5
+ - **Official Account (OA) API** - Manage your Zalo Official Account
6
+ - **Consultation Service** - Send customer support messages within 48-hour window
7
+ - **Zalo Notification Service (ZNS)** - Send template-based notification messages
8
+ - **Social API** - Access user social information and authentication
9
+ - **Group Message Framework (GMF)** - Send messages to Zalo groups
10
+ - **User Management** - Comprehensive user profile and tag management
11
+ - **Content Management** - Upload and manage media content (images, files, articles)
12
+ - **Video Upload** - Upload and manage video content with processing
13
+ - **Tag Management** - User tagging and segmentation
14
+ - **Webhook handling** - Process Zalo webhook events
15
+
16
+ ## Features
17
+
18
+ - 🚀 **TypeScript Support** - Full type safety and IntelliSense
19
+ - 🔐 **OAuth 2.0 Flow** - Complete authentication handling
20
+ - 🔄 **Auto Retry** - Built-in retry mechanism for failed requests
21
+ - 📝 **Comprehensive Logging** - Debug and monitor API calls
22
+ - 🛡️ **Error Handling** - Detailed error information and handling
23
+ - 📦 **Zero Dependencies** - Only requires axios and form-data
24
+ - 🎯 **Promise-based** - Modern async/await support
25
+
26
+ ## Installation
27
+
28
+ ```bash
29
+ npm install @warriorteam/redai-zalo-sdk
30
+ ```
31
+
32
+ ## 📚 Documentation
33
+
34
+ ### 🚀 Getting Started
35
+ - **[API Reference](./docs/API_REFERENCE.md)** - Complete API documentation and method reference
36
+ - **[Authentication Guide](./docs/AUTHENTICATION.md)** - OAuth 2.0 flows for OA and Social APIs
37
+ - **[Architecture Overview](./ARCHITECTURE.md)** - SDK architecture and design patterns
38
+ - **[Services Added](./SERVICES_ADDED.md)** - Detailed breakdown of all services and features
39
+
40
+ ### 📨 Messaging & Communication
41
+ - **[Message Services](./docs/MESSAGE_SERVICES.md)** - Complete guide for all message types and services
42
+ - **[Consultation Service](./docs/CONSULTATION_SERVICE.md)** - Customer service messaging guide
43
+ - **[ZNS Service](./docs/ZNS_SERVICE.md)** - Zalo Notification Service for template messages
44
+ - **[Group Management](./docs/GROUP_MANAGEMENT.md)** - Group messaging and management
45
+
46
+ ### 👥 User & Content Management
47
+ - **[User Management](./docs/USER_MANAGEMENT.md)** - User profiles, followers, and management
48
+ - **[Tag Management](./docs/TAG_MANAGEMENT.md)** - User tagging and segmentation system
49
+ - **[Article Management](./docs/ARTICLE_MANAGEMENT.md)** - Content and article management
50
+
51
+ - **[Webhook Types (Source of Truth)](./src/types/webhook.ts)** - Strongly-typed webhook event definitions
52
+
53
+ ### 🔔 Events & Integration
54
+ - **[Webhook Events Guide](./docs/WEBHOOK_EVENTS.md)** - Complete guide for all 70+ webhook event types
55
+
56
+ ## Development
57
+
58
+ ### Build from source
59
+
60
+ ```bash
61
+ # Clone the repository
62
+ git clone https://github.com/redai/redai-zalo-sdk.git
63
+ cd redai-zalo-sdk
64
+
65
+ # Install dependencies
66
+ npm install
67
+
68
+ # Build the SDK
69
+ npm run build
70
+
71
+ # Run examples
72
+ npm run dev
73
+ ```
74
+
75
+ ## Quick Start
76
+
77
+ ### Initialize the SDK
78
+
79
+ ```typescript
80
+ import { ZaloSDK } from "@warriorteam/redai-zalo-sdk";
81
+
82
+ const zalo = new ZaloSDK({
83
+ appId: "your-app-id",
84
+ appSecret: "your-app-secret",
85
+ debug: true, // Enable debug logging
86
+ });
87
+ ```
88
+
89
+ ### Authentication Flow
90
+
91
+ #### Official Account (OA) Authentication
92
+
93
+ ```typescript
94
+ // 1. Create authorization URL
95
+ const authUrl = zalo.createOAAuthUrl("https://your-app.com/callback");
96
+ console.log("Visit:", authUrl);
97
+
98
+ // 2. Exchange authorization code for access token
99
+ const accessToken = await zalo.getOAAccessToken(
100
+ "authorization-code-from-callback",
101
+ "https://your-app.com/callback"
102
+ );
103
+
104
+ console.log("Access Token:", accessToken.access_token);
105
+ ```
106
+
107
+ #### Social API Authentication
108
+
109
+ ```typescript
110
+ // 1. Generate PKCE for security (recommended)
111
+ const pkce = zalo.generatePKCE();
112
+
113
+ // 2. Create authorization URL
114
+ const authUrl = zalo.createSocialAuthUrl("https://your-app.com/callback");
115
+
116
+ // 3. Exchange code for access token
117
+ const accessToken = await zalo.getSocialAccessToken(
118
+ "authorization-code",
119
+ "https://your-app.com/callback",
120
+ pkce.code_verifier
121
+ );
122
+ ```
123
+
124
+ ### Official Account Operations
125
+
126
+ ```typescript
127
+ // Get OA information
128
+ const oaInfo = await zalo.getOAInfo(accessToken.access_token);
129
+ console.log("OA Name:", oaInfo.name);
130
+ console.log("Followers:", oaInfo.num_follower);
131
+
132
+ // Check message quota
133
+ const quota = await zalo.getMessageQuota(accessToken.access_token);
134
+ console.log("Daily Quota:", quota.daily_quota);
135
+ console.log("Remaining:", quota.remaining_quota);
136
+
137
+ // Get detailed quota information
138
+ const detailedQuota = await zalo.oa.getQuotaSummary(accessToken.access_token);
139
+ console.log("Consultation Quota:", detailedQuota.consultation);
140
+ console.log("Transaction Quota:", detailedQuota.transaction);
141
+ ```
142
+
143
+ ### Social API Operations
144
+
145
+ ```typescript
146
+ // Get user information
147
+ const userInfo = await zalo.getSocialUserInfo(
148
+ accessToken.access_token,
149
+ "id,name,picture,birthday"
150
+ );
151
+
152
+ console.log("User ID:", userInfo.id);
153
+ console.log("Name:", userInfo.name);
154
+ console.log("Avatar:", userInfo.picture?.data.url);
155
+ ```
156
+
157
+ ### Token Management
158
+
159
+ ```typescript
160
+ // Refresh OA access token
161
+ const newOAToken = await zalo.refreshOAAccessToken(refreshToken);
162
+
163
+ // Refresh Social access token
164
+ const newSocialToken = await zalo.refreshSocialAccessToken(refreshToken);
165
+
166
+ // Validate token
167
+ const isValid = await zalo.validateAccessToken(accessToken.access_token, "oa");
168
+ ```
169
+
170
+ ## Advanced Usage
171
+
172
+ ### Custom API Requests
173
+
174
+ ```typescript
175
+ // Make custom API calls
176
+ const customData = await zalo.customRequest(
177
+ "POST",
178
+ "/v3.0/oa/message/cs",
179
+ accessToken.access_token,
180
+ {
181
+ recipient: { user_id: "user-id" },
182
+ message: { text: "Hello from SDK!" },
183
+ }
184
+ );
185
+ ```
186
+
187
+ ### File Upload
188
+
189
+ ```typescript
190
+ import fs from "fs";
191
+
192
+ // Upload image
193
+ const fileBuffer = fs.readFileSync("image.jpg");
194
+ const uploadResult = await zalo.uploadFile(
195
+ "/v2.0/oa/upload/image",
196
+ accessToken.access_token,
197
+ fileBuffer,
198
+ "image.jpg"
199
+ );
200
+
201
+ console.log("Uploaded URL:", uploadResult.data.url);
202
+ ```
203
+
204
+ ### Error Handling
205
+
206
+ ```typescript
207
+ import { ZaloSDKError } from "redai-zalo-sdk";
208
+
209
+ try {
210
+ const oaInfo = await zalo.getOAInfo(accessToken.access_token);
211
+ } catch (error) {
212
+ if (error instanceof ZaloSDKError) {
213
+ console.error("Zalo API Error:", error.message);
214
+ console.error("Error Code:", error.code);
215
+ console.error("Details:", error.details);
216
+ } else {
217
+ console.error("Unexpected error:", error);
218
+ }
219
+ }
220
+ ```
221
+
222
+ ## Configuration Options
223
+
224
+ ```typescript
225
+ const zalo = new ZaloSDK({
226
+ appId: "your-app-id",
227
+ appSecret: "your-app-secret",
228
+
229
+ // Optional configurations
230
+ timeout: 30000, // Request timeout in ms (default: 30000)
231
+ debug: false, // Enable debug logging (default: false)
232
+ apiBaseUrl: "https://openapi.zalo.me", // Custom API base URL
233
+
234
+ // Retry configuration
235
+ retry: {
236
+ attempts: 3, // Number of retry attempts (default: 3)
237
+ delay: 1000, // Delay between retries in ms (default: 1000)
238
+ },
239
+ });
240
+ ```
241
+
242
+ ## API Reference
243
+
244
+ ### ZaloSDK Class
245
+
246
+ #### Constructor
247
+
248
+ - `new ZaloSDK(config: ZaloSDKConfig)`
249
+
250
+ #### Authentication Methods
251
+
252
+ - `createOAAuthUrl(redirectUri: string, state?: string): string`
253
+ - `createSocialAuthUrl(redirectUri: string, state?: string): string`
254
+ - `getOAAccessToken(code: string, redirectUri: string): Promise<AccessToken>`
255
+ - `getSocialAccessToken(code: string, redirectUri: string, codeVerifier?: string): Promise<AccessToken>`
256
+ - `refreshOAAccessToken(refreshToken: string): Promise<AccessToken>`
257
+ - `refreshSocialAccessToken(refreshToken: string): Promise<AccessToken>`
258
+
259
+ #### OA Methods
260
+
261
+ - `getOAInfo(accessToken: string): Promise<OAInfo>`
262
+ - `getMessageQuota(accessToken: string): Promise<MessageQuota>`
263
+
264
+ #### Social Methods
265
+
266
+ - `getSocialUserInfo(accessToken: string, fields?: string): Promise<SocialUserInfo>`
267
+
268
+ #### Utility Methods
269
+
270
+ - `validateAccessToken(accessToken: string, scope?: 'oa' | 'social'): Promise<boolean>`
271
+ - `generatePKCE(): PKCEConfig`
272
+ - `testConnection(): Promise<boolean>`
273
+
274
+ ### Services
275
+
276
+ #### AuthService
277
+
278
+ - Complete OAuth 2.0 flow handling
279
+ - PKCE support for Social API
280
+ - Token validation and refresh
281
+
282
+ #### OAService
283
+
284
+ - Official Account information management
285
+ - Quota monitoring and management
286
+ - Profile updates
287
+
288
+ ## Error Handling
289
+
290
+ The SDK throws `ZaloSDKError` for all Zalo API related errors:
291
+
292
+ ```typescript
293
+ class ZaloSDKError extends Error {
294
+ code: number; // Zalo API error code
295
+ details?: any; // Additional error details
296
+ }
297
+ ```
298
+
299
+ Common error codes:
300
+
301
+ - `-216`: Invalid access token
302
+ - `-201`: Invalid parameters
303
+ - `-223`: Quota exceeded
304
+
305
+ ## TypeScript Support
306
+
307
+ The SDK is written in TypeScript and provides comprehensive type definitions:
308
+
309
+ ```typescript
310
+ import {
311
+ ZaloSDK,
312
+ ZaloSDKConfig,
313
+ AccessToken,
314
+ OAInfo,
315
+ SocialUserInfo,
316
+ ZaloSDKError,
317
+ } from "redai-zalo-sdk";
318
+ ```
319
+
320
+ ## Contributing
321
+
322
+ 1. Fork the repository
323
+ 2. Create your feature branch (`git checkout -b feature/amazing-feature`)
324
+ 3. Commit your changes (`git commit -m 'Add some amazing feature'`)
325
+ 4. Push to the branch (`git push origin feature/amazing-feature`)
326
+ 5. Open a Pull Request
327
+
328
+ ## License
329
+
330
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
331
+
332
+ ## Support
333
+
334
+ For support and questions:
335
+
336
+ - Create an issue on GitHub
337
+ - Contact RedAI team
338
+
339
+ ### Consultation Service (Customer Support)
340
+
341
+ ```typescript
342
+ // Send consultation text message
343
+ await zalo.consultation.sendTextMessage(accessToken,
344
+ { user_id: "user-id" },
345
+ {
346
+ type: "text",
347
+ text: "Xin chào! Tôi có thể hỗ trợ gì cho bạn?"
348
+ }
349
+ );
350
+
351
+ // Send consultation image with guide
352
+ await zalo.consultation.sendImageMessage(accessToken,
353
+ { user_id: "user-id" },
354
+ {
355
+ type: "image",
356
+ attachment: {
357
+ type: "image",
358
+ payload: {
359
+ url: "https://example.com/support-guide.jpg"
360
+ }
361
+ }
362
+ }
363
+ );
364
+
365
+ // Send file attachment for support
366
+ await zalo.consultation.sendFileMessage(accessToken,
367
+ { user_id: "user-id" },
368
+ {
369
+ type: "file",
370
+ url: "https://example.com/manual.pdf",
371
+ filename: "User Manual.pdf",
372
+ attachment: {
373
+ type: "file",
374
+ payload: {
375
+ url: "https://example.com/manual.pdf"
376
+ }
377
+ }
378
+ }
379
+ );
380
+ ```
381
+
382
+ ### ZNS (Zalo Notification Service)
383
+
384
+ ```typescript
385
+ // Send ZNS notification
386
+ await zalo.zns.sendMessage(accessToken, {
387
+ phone: "0123456789",
388
+ template_id: "your-template-id",
389
+ template_data: {
390
+ customer_name: "John Doe",
391
+ order_id: "12345",
392
+ },
393
+ });
394
+
395
+ // Get ZNS quota
396
+ const quota = await zalo.zns.getQuotaInfo(accessToken);
397
+
398
+ // Manage ZNS templates
399
+ const templates = await zalo.zns.getTemplateList(accessToken);
400
+ const template = await zalo.zns.createTemplate(accessToken, {
401
+ templateName: "Order Confirmation",
402
+ templateContent:
403
+ "Hello {{customer_name}}, your order {{order_id}} is confirmed.",
404
+ templateType: 3, // Confirmation type
405
+ });
406
+ ```
407
+
408
+ ### Group Messaging
409
+
410
+ ```typescript
411
+ // Send text message to group
412
+ await zalo.groupMessage.sendTextMessage(accessToken, groupId, {
413
+ type: "text",
414
+ text: "Hello everyone!",
415
+ });
416
+
417
+ // Send image to group
418
+ await zalo.groupMessage.sendImageMessage(accessToken, groupId, {
419
+ type: "image",
420
+ imageUrl: "https://example.com/image.jpg",
421
+ caption: "Check this out!",
422
+ });
423
+
424
+ // Get group information
425
+ const groupInfo = await zalo.groupMessage.getGroupInfo(accessToken, groupId);
426
+ const members = await zalo.groupMessage.getGroupMembers(accessToken, groupId);
427
+ ```
428
+
429
+ ### User Management
430
+
431
+ ```typescript
432
+ // Get user profile
433
+ const profile = await zalo.userManagement.getUserProfile(accessToken, userId);
434
+
435
+ // Tag management
436
+ await zalo.tag.createTag(accessToken, "VIP Customer");
437
+ await zalo.tag.tagUser(accessToken, userId, ["VIP Customer", "Premium"]);
438
+ const userTags = await zalo.tag.getUserTags(accessToken, userId);
439
+
440
+ // Get followers list
441
+ const followers = await zalo.userManagement.getFollowersList(accessToken);
442
+ ```
443
+
444
+ ### Content Management
445
+
446
+ ```typescript
447
+ // Upload image
448
+ const imageResult = await zalo.content.uploadImage(accessToken, imageBuffer);
449
+
450
+ // Create article
451
+ const article = await zalo.content.createArticle(accessToken, {
452
+ title: "Welcome to our service",
453
+ body: "Article content here...",
454
+ cover_photo_id: imageResult.data.attachment_id,
455
+ });
456
+
457
+ // Share article to user
458
+ await zalo.content.shareArticle(accessToken, userId, article.data.id);
459
+ ```
460
+
461
+ ### Video Upload
462
+
463
+ ```typescript
464
+ // Upload video
465
+ const uploadResult = await zalo.videoUpload.uploadVideo(
466
+ accessToken,
467
+ videoBuffer,
468
+ "video.mp4"
469
+ );
470
+
471
+ // Wait for processing completion
472
+ const finalResult = await zalo.videoUpload.waitForUploadCompletion(
473
+ accessToken,
474
+ uploadResult.data.token
475
+ );
476
+
477
+ if (finalResult.status === "ready") {
478
+ // Send video message
479
+ await zalo.videoUpload.sendVideoMessage(
480
+ accessToken,
481
+ userId,
482
+ finalResult.attachment_id,
483
+ "Check out this video!"
484
+ );
485
+ }
486
+ ```
487
+
488
+ ### Social API
489
+
490
+ ```typescript
491
+ // Get user social information
492
+ const userInfo = await zalo.social.getUserInfo(accessToken);
493
+
494
+ // Get friends list
495
+ const friends = await zalo.social.getFriendsList(accessToken);
496
+
497
+ // Post to timeline
498
+ await zalo.social.postToTimeline(accessToken, "Hello from Zalo SDK!");
499
+ ```
500
+
501
+ ## 🔔 Webhook Events
502
+
503
+ The SDK provides comprehensive webhook event handling with **70+ event types**:
504
+
505
+ ```typescript
506
+ import { WebhookHandlers } from "@warriorteam/redai-zalo-sdk";
507
+
508
+ const handlers: WebhookHandlers = {
509
+ // User message events
510
+ user_send_text: async (event) => {
511
+ console.log("User sent:", event.message.text);
512
+ },
513
+
514
+ // Group events
515
+ user_send_group_audio: async (event) => {
516
+ console.log("Audio in group:", event.message.attachments[0].payload.url);
517
+ },
518
+
519
+ // ZNS events
520
+ change_template_status: async (event) => {
521
+ console.log("Template status:", event.status);
522
+ },
523
+
524
+ // Widget events
525
+ widget_interaction_accepted: async (event) => {
526
+ console.log("Widget accepted:", event.data.user_external_id);
527
+ },
528
+
529
+ // System events
530
+ permission_revoked: async (event) => {
531
+ console.log("Permission revoked by:", event.data.action_by);
532
+ },
533
+ };
534
+ ```
535
+
536
+ ### Event Categories:
537
+
538
+ - **User Message Events** (11 types): text, image, video, audio, file, sticker, gif, location, link, business card, reaction
539
+ - **OA Message Events** (11 types): All message types + anonymous + template
540
+ - **Group Events** (22 types): Create, join, admin, leave + all message types for both user and OA
541
+ - **ZNS Events** (8 types): Quota, template, journey, delivery, status changes
542
+ - **Widget Events** (2 types): Interaction accepted, sync failures
543
+ - **System Events** (4 types): Permission, extension, user info, tags
544
+ - **Call Events** (2 types): OA call user, user call OA
545
+ - **Anonymous Events** (4 types): Anonymous chat support
546
+ - **Shop Events** (1 type): Order management
547
+
548
+ For complete webhook documentation, see [Webhook Events Guide](./docs/WEBHOOK_EVENTS.md).
549
+
550
+ ## Changelog
551
+
552
+ ### v1.0.0
553
+
554
+ - Initial release
555
+ - Official Account API support
556
+ - ZNS (Zalo Notification Service) support
557
+ - Group Message Framework (GMF) support
558
+ - Social API support
559
+ - User Management features
560
+ - Content and Video Upload capabilities
561
+ - Tag Management system
562
+ - Comprehensive webhook handling
563
+ - Social API support
564
+ - Authentication flow
565
+ - TypeScript support