@warriorteam/redai-zalo-sdk 1.2.0 → 1.3.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,680 @@
1
+ # RedAI Zalo SDK - API Reference
2
+
3
+ ## Tổng quan
4
+
5
+ RedAI Zalo SDK cung cấp các API hoàn chỉnh để tích hợp với các dịch vụ của Zalo, bao gồm Official Account, ZNS, Social API, và nhiều dịch vụ khác.
6
+
7
+ ## Cấu trúc SDK
8
+
9
+ ```typescript
10
+ import { ZaloSDK } from "@warriorteam/redai-zalo-sdk";
11
+
12
+ const zalo = new ZaloSDK({
13
+ appId: "your-app-id",
14
+ appSecret: "your-app-secret",
15
+ debug: true
16
+ });
17
+ ```
18
+
19
+ ---
20
+
21
+ ## ZaloSDK Class
22
+
23
+ ### Constructor
24
+
25
+ ```typescript
26
+ constructor(config: ZaloSDKConfig)
27
+ ```
28
+
29
+ #### ZaloSDKConfig
30
+
31
+ ```typescript
32
+ interface ZaloSDKConfig {
33
+ appId: string; // App ID từ Zalo Developer
34
+ appSecret: string; // App Secret từ Zalo Developer
35
+ timeout?: number; // Timeout cho request (mặc định: 30000ms)
36
+ debug?: boolean; // Bật chế độ debug (mặc định: false)
37
+ apiBaseUrl?: string; // Base URL API (mặc định: https://openapi.zalo.me)
38
+ retry?: {
39
+ attempts?: number; // Số lần retry (mặc định: 3)
40
+ delay?: number; // Delay giữa các retry (mặc định: 1000ms)
41
+ };
42
+ }
43
+ ```
44
+
45
+ ### Quick Methods
46
+
47
+ #### getOAAccessToken()
48
+ ```typescript
49
+ async getOAAccessToken(code: string, redirectUri: string): Promise<AccessToken>
50
+ ```
51
+ Lấy access token cho Official Account từ authorization code.
52
+
53
+ #### getSocialAccessToken()
54
+ ```typescript
55
+ async getSocialAccessToken(code: string, redirectUri: string, codeVerifier?: string): Promise<AccessToken>
56
+ ```
57
+ Lấy access token cho Social API từ authorization code.
58
+
59
+ #### refreshOAAccessToken()
60
+ ```typescript
61
+ async refreshOAAccessToken(refreshToken: string): Promise<AccessToken>
62
+ ```
63
+ Refresh access token cho Official Account.
64
+
65
+ #### refreshSocialAccessToken()
66
+ ```typescript
67
+ async refreshSocialAccessToken(refreshToken: string): Promise<AccessToken>
68
+ ```
69
+ Refresh access token cho Social API.
70
+
71
+ ---
72
+
73
+ ## AuthService
74
+
75
+ Xử lý authentication flows và quản lý token.
76
+
77
+ ### Methods
78
+
79
+ #### createOAAuthUrl()
80
+ ```typescript
81
+ createOAAuthUrl(redirectUri: string, state?: string): string
82
+ ```
83
+ Tạo URL authorization cho Official Account.
84
+
85
+ #### createSocialAuthUrl()
86
+ ```typescript
87
+ createSocialAuthUrl(redirectUri: string, state?: string): string
88
+ ```
89
+ Tạo URL authorization cho Social API.
90
+
91
+ #### getOAAccessToken()
92
+ ```typescript
93
+ async getOAAccessToken(params: AuthCodeParams): Promise<AccessToken>
94
+ ```
95
+
96
+ #### getSocialAccessToken()
97
+ ```typescript
98
+ async getSocialAccessToken(params: AuthCodeParams): Promise<AccessToken>
99
+ ```
100
+
101
+ #### getSocialUserInfo()
102
+ ```typescript
103
+ async getSocialUserInfo(accessToken: string, fields?: string): Promise<SocialUserInfo>
104
+ ```
105
+
106
+ #### generatePKCE()
107
+ ```typescript
108
+ generatePKCE(): PKCEConfig
109
+ ```
110
+ Tạo PKCE cho Social API authorization.
111
+
112
+ #### validateAccessToken()
113
+ ```typescript
114
+ async validateAccessToken(accessToken: string): Promise<TokenValidation>
115
+ ```
116
+
117
+ ---
118
+
119
+ ## OAService
120
+
121
+ Quản lý Official Account information và quota.
122
+
123
+ ### Methods
124
+
125
+ #### getOAInfo()
126
+ ```typescript
127
+ async getOAInfo(accessToken: string): Promise<OAInfo>
128
+ ```
129
+ Lấy thông tin Official Account.
130
+
131
+ **Response:**
132
+ ```typescript
133
+ interface OAInfo {
134
+ oa_id: string;
135
+ name: string;
136
+ description: string;
137
+ oa_alias: string;
138
+ is_verified: boolean;
139
+ oa_type: number;
140
+ package_name: string;
141
+ package_valid_through_date: string;
142
+ package_auto_renew_date: string;
143
+ linked_zca: string;
144
+ num_follower: number;
145
+ avatar: string;
146
+ cover: string;
147
+ }
148
+ ```
149
+
150
+ #### getMessageQuota()
151
+ ```typescript
152
+ async getMessageQuota(accessToken: string): Promise<MessageQuota>
153
+ ```
154
+ Lấy thông tin quota tin nhắn.
155
+
156
+ #### getQuotaSummary()
157
+ ```typescript
158
+ async getQuotaSummary(accessToken: string): Promise<QuotaSummary>
159
+ ```
160
+ Lấy tổng quan quota chi tiết.
161
+
162
+ #### validateOAToken()
163
+ ```typescript
164
+ async validateOAToken(accessToken: string): Promise<boolean>
165
+ ```
166
+
167
+ ---
168
+
169
+ ## ConsultationService
170
+
171
+ Gửi tin nhắn customer support trong vòng 48 giờ.
172
+
173
+ ### Methods
174
+
175
+ #### sendTextMessage()
176
+ ```typescript
177
+ async sendTextMessage(
178
+ accessToken: string,
179
+ recipient: MessageRecipient,
180
+ message: ConsultationTextMessage
181
+ ): Promise<SendMessageResponse>
182
+ ```
183
+
184
+ **Ví dụ:**
185
+ ```typescript
186
+ await zalo.consultation.sendTextMessage(accessToken,
187
+ { user_id: "user-id" },
188
+ { type: "text", text: "Xin chào! Tôi có thể hỗ trợ gì cho bạn?" }
189
+ );
190
+ ```
191
+
192
+ #### sendImageMessage()
193
+ ```typescript
194
+ async sendImageMessage(
195
+ accessToken: string,
196
+ recipient: MessageRecipient,
197
+ message: ConsultationImageMessage
198
+ ): Promise<SendMessageResponse>
199
+ ```
200
+
201
+ #### sendFileMessage()
202
+ ```typescript
203
+ async sendFileMessage(
204
+ accessToken: string,
205
+ recipient: MessageRecipient,
206
+ message: ConsultationFileMessage
207
+ ): Promise<SendMessageResponse>
208
+ ```
209
+
210
+ #### sendStickerMessage()
211
+ ```typescript
212
+ async sendStickerMessage(
213
+ accessToken: string,
214
+ recipient: MessageRecipient,
215
+ message: ConsultationStickerMessage
216
+ ): Promise<SendMessageResponse>
217
+ ```
218
+
219
+ #### sendQuoteMessage()
220
+ ```typescript
221
+ async sendQuoteMessage(
222
+ accessToken: string,
223
+ recipient: MessageRecipient,
224
+ message: ConsultationQuoteMessage
225
+ ): Promise<SendMessageResponse>
226
+ ```
227
+
228
+ #### sendRequestInfoMessage()
229
+ ```typescript
230
+ async sendRequestInfoMessage(
231
+ accessToken: string,
232
+ recipient: MessageRecipient,
233
+ message: ConsultationRequestInfoMessage
234
+ ): Promise<SendMessageResponse>
235
+ ```
236
+
237
+ ---
238
+
239
+ ## ZNSService
240
+
241
+ Zalo Notification Service - gửi tin nhắn thông báo qua template.
242
+
243
+ ### Methods
244
+
245
+ #### sendMessage()
246
+ ```typescript
247
+ async sendMessage(
248
+ accessToken: string,
249
+ request: ZNSMessageRequest
250
+ ): Promise<ZNSMessageResponse>
251
+ ```
252
+
253
+ **ZNSMessageRequest:**
254
+ ```typescript
255
+ interface ZNSMessageRequest {
256
+ phone: string; // Số điện thoại người nhận
257
+ template_id: string; // ID template được duyệt
258
+ template_data: Record<string, any>; // Data để fill vào template
259
+ tracking_id?: string; // ID để tracking (tùy chọn)
260
+ mode?: 'development' | 'production'; // Môi trường (mặc định: production)
261
+ }
262
+ ```
263
+
264
+ #### getQuotaInfo()
265
+ ```typescript
266
+ async getQuotaInfo(accessToken: string): Promise<ZNSQuotaInfo>
267
+ ```
268
+
269
+ #### getTemplateList()
270
+ ```typescript
271
+ async getTemplateList(accessToken: string, params?: ZNSTemplateListParams): Promise<ZNSTemplateListResponse>
272
+ ```
273
+
274
+ #### createTemplate()
275
+ ```typescript
276
+ async createTemplate(accessToken: string, template: ZNSTemplateCreate): Promise<ZNSTemplateCreateResponse>
277
+ ```
278
+
279
+ #### updateTemplate()
280
+ ```typescript
281
+ async updateTemplate(accessToken: string, templateId: string, template: ZNSTemplateUpdate): Promise<ZNSTemplateUpdateResponse>
282
+ ```
283
+
284
+ #### getTemplateStatus()
285
+ ```typescript
286
+ async getTemplateStatus(accessToken: string, templateId: string): Promise<ZNSTemplateStatus>
287
+ ```
288
+
289
+ ---
290
+
291
+ ## UserService
292
+
293
+ Quản lý thông tin người dùng Social API.
294
+
295
+ ### Methods
296
+
297
+ #### getUserInfo()
298
+ ```typescript
299
+ async getUserInfo(accessToken: string, userId: string): Promise<UserInfo>
300
+ ```
301
+
302
+ #### getUserList()
303
+ ```typescript
304
+ async getUserList(accessToken: string, request: UserListRequest): Promise<UserListResponse>
305
+ ```
306
+
307
+ #### getFollowers()
308
+ ```typescript
309
+ async getFollowers(accessToken: string, params?: FollowersParams): Promise<FollowersResponse>
310
+ ```
311
+
312
+ ---
313
+
314
+ ## UserManagementService
315
+
316
+ Quản lý user profiles và interactions.
317
+
318
+ ### Methods
319
+
320
+ #### getUserProfile()
321
+ ```typescript
322
+ async getUserProfile(accessToken: string, userId: string): Promise<UserManagementProfile>
323
+ ```
324
+
325
+ #### updateUserProfile()
326
+ ```typescript
327
+ async updateUserProfile(accessToken: string, userId: string, profile: UserProfileUpdate): Promise<UserManagementProfile>
328
+ ```
329
+
330
+ #### getUserInteractions()
331
+ ```typescript
332
+ async getUserInteractions(accessToken: string, userId: string, params?: InteractionParams): Promise<UserInteraction[]>
333
+ ```
334
+
335
+ #### getUserAnalytics()
336
+ ```typescript
337
+ async getUserAnalytics(accessToken: string, userId: string): Promise<UserAnalytics>
338
+ ```
339
+
340
+ #### searchUsers()
341
+ ```typescript
342
+ async searchUsers(accessToken: string, search: UserSearch): Promise<UserSearchResult>
343
+ ```
344
+
345
+ #### bulkUserOperation()
346
+ ```typescript
347
+ async bulkUserOperation(accessToken: string, operation: BulkUserOperation): Promise<BulkOperationResult>
348
+ ```
349
+
350
+ ---
351
+
352
+ ## TagService
353
+
354
+ Quản lý user tags và segmentation.
355
+
356
+ ### Methods
357
+
358
+ #### createTag()
359
+ ```typescript
360
+ async createTag(accessToken: string, tagName: string): Promise<TagCreateResponse>
361
+ ```
362
+
363
+ #### deleteTag()
364
+ ```typescript
365
+ async deleteTag(accessToken: string, tagId: string): Promise<TagDeleteResponse>
366
+ ```
367
+
368
+ #### tagUser()
369
+ ```typescript
370
+ async tagUser(accessToken: string, userId: string, tags: string[]): Promise<TagUserResponse>
371
+ ```
372
+
373
+ #### untagUser()
374
+ ```typescript
375
+ async untagUser(accessToken: string, userId: string, tags: string[]): Promise<UntagUserResponse>
376
+ ```
377
+
378
+ #### getUserTags()
379
+ ```typescript
380
+ async getUserTags(accessToken: string, userId: string): Promise<UserTag[]>
381
+ ```
382
+
383
+ #### getTagList()
384
+ ```typescript
385
+ async getTagList(accessToken: string): Promise<UserTagList>
386
+ ```
387
+
388
+ #### getUsersByTag()
389
+ ```typescript
390
+ async getUsersByTag(accessToken: string, tagId: string, params?: TagUsersParams): Promise<TagUsersResponse>
391
+ ```
392
+
393
+ ---
394
+
395
+ ## GroupManagementService
396
+
397
+ Quản lý groups và members.
398
+
399
+ ### Methods
400
+
401
+ #### getGroupsOfOA()
402
+ ```typescript
403
+ async getGroupsOfOA(accessToken: string, params?: GroupsParams): Promise<GroupsOfOAResponse>
404
+ ```
405
+
406
+ #### getGroupDetail()
407
+ ```typescript
408
+ async getGroupDetail(accessToken: string, groupId: string): Promise<GroupDetailResponse>
409
+ ```
410
+
411
+ #### getGroupMembers()
412
+ ```typescript
413
+ async getGroupMembers(accessToken: string, groupId: string, params?: GroupMembersParams): Promise<GroupMembersResponse>
414
+ ```
415
+
416
+ #### getPendingMembers()
417
+ ```typescript
418
+ async getPendingMembers(accessToken: string, groupId: string): Promise<GroupPendingMembersResponse>
419
+ ```
420
+
421
+ #### acceptPendingMembers()
422
+ ```typescript
423
+ async acceptPendingMembers(accessToken: string, request: GroupAcceptPendingMembersRequest): Promise<GroupAcceptPendingMembersResponse>
424
+ ```
425
+
426
+ #### removeMembers()
427
+ ```typescript
428
+ async removeMembers(accessToken: string, request: GroupRemoveMembersRequest): Promise<GroupRemoveMembersResponse>
429
+ ```
430
+
431
+ ---
432
+
433
+ ## GroupMessageService
434
+
435
+ Gửi tin nhắn đến groups.
436
+
437
+ ### Methods
438
+
439
+ #### sendTextMessage()
440
+ ```typescript
441
+ async sendTextMessage(accessToken: string, groupId: string, message: GroupTextMessage): Promise<GroupMessageResult>
442
+ ```
443
+
444
+ #### sendImageMessage()
445
+ ```typescript
446
+ async sendImageMessage(accessToken: string, groupId: string, message: GroupImageMessage): Promise<GroupMessageResult>
447
+ ```
448
+
449
+ #### sendFileMessage()
450
+ ```typescript
451
+ async sendFileMessage(accessToken: string, groupId: string, message: GroupFileMessage): Promise<GroupMessageResult>
452
+ ```
453
+
454
+ #### getQuotaMessage()
455
+ ```typescript
456
+ async getQuotaMessage(accessToken: string, request: GroupQuotaMessageRequest): Promise<GroupQuotaMessageResponse>
457
+ ```
458
+
459
+ ---
460
+
461
+ ## ArticleService
462
+
463
+ Quản lý articles và content.
464
+
465
+ ### Methods
466
+
467
+ #### createArticle()
468
+ ```typescript
469
+ async createArticle(accessToken: string, article: ArticleCreateRequest): Promise<ArticleCreateResponse>
470
+ ```
471
+
472
+ #### updateArticle()
473
+ ```typescript
474
+ async updateArticle(accessToken: string, articleId: string, article: ArticleUpdateRequest): Promise<ArticleUpdateResponse>
475
+ ```
476
+
477
+ #### deleteArticle()
478
+ ```typescript
479
+ async deleteArticle(accessToken: string, articleId: string): Promise<ArticleDeleteResponse>
480
+ ```
481
+
482
+ #### getArticle()
483
+ ```typescript
484
+ async getArticle(accessToken: string, articleId: string): Promise<Article>
485
+ ```
486
+
487
+ #### getArticleList()
488
+ ```typescript
489
+ async getArticleList(accessToken: string, params?: ArticleListParams): Promise<ArticleListResponse>
490
+ ```
491
+
492
+ #### shareArticle()
493
+ ```typescript
494
+ async shareArticle(accessToken: string, userId: string, articleId: string): Promise<ShareArticleResponse>
495
+ ```
496
+
497
+ #### uploadImage()
498
+ ```typescript
499
+ async uploadImage(accessToken: string, image: Buffer): Promise<ImageUploadResponse>
500
+ ```
501
+
502
+ ---
503
+
504
+ ## VideoUploadService
505
+
506
+ Upload và quản lý video content.
507
+
508
+ ### Methods
509
+
510
+ #### uploadVideo()
511
+ ```typescript
512
+ async uploadVideo(accessToken: string, video: Buffer, filename: string): Promise<VideoUploadResponse>
513
+ ```
514
+
515
+ #### getUploadStatus()
516
+ ```typescript
517
+ async getUploadStatus(accessToken: string, token: string): Promise<VideoUploadStatus>
518
+ ```
519
+
520
+ #### waitForUploadCompletion()
521
+ ```typescript
522
+ async waitForUploadCompletion(accessToken: string, token: string, maxAttempts?: number): Promise<VideoUploadComplete>
523
+ ```
524
+
525
+ #### sendVideoMessage()
526
+ ```typescript
527
+ async sendVideoMessage(accessToken: string, userId: string, attachmentId: string, message?: string): Promise<SendMessageResponse>
528
+ ```
529
+
530
+ ---
531
+
532
+ ## TransactionService
533
+
534
+ Gửi tin nhắn transaction (thanh toán, đơn hàng).
535
+
536
+ ### Methods
537
+
538
+ #### sendTransactionMessage()
539
+ ```typescript
540
+ async sendTransactionMessage(
541
+ accessToken: string,
542
+ recipient: MessageRecipient,
543
+ message: TransactionMessage
544
+ ): Promise<SendMessageResponse>
545
+ ```
546
+
547
+ ---
548
+
549
+ ## PromotionService
550
+
551
+ Gửi tin nhắn khuyến mại.
552
+
553
+ ### Methods
554
+
555
+ #### sendPromotionMessage()
556
+ ```typescript
557
+ async sendPromotionMessage(
558
+ accessToken: string,
559
+ recipient: MessageRecipient,
560
+ message: PromotionMessage
561
+ ): Promise<SendMessageResponse>
562
+ ```
563
+
564
+ ---
565
+
566
+ ## GeneralMessageService
567
+
568
+ Gửi tin nhắn general purpose.
569
+
570
+ ### Methods
571
+
572
+ #### sendResponseMessage()
573
+ ```typescript
574
+ async sendResponseMessage(
575
+ accessToken: string,
576
+ recipient: MessageRecipient,
577
+ message: Message
578
+ ): Promise<SendMessageResponse>
579
+ ```
580
+
581
+ #### sendAnonymousMessage()
582
+ ```typescript
583
+ async sendAnonymousMessage(
584
+ accessToken: string,
585
+ recipient: MessageRecipient,
586
+ message: AnonymousMessage
587
+ ): Promise<SendMessageResponse>
588
+ ```
589
+
590
+ ---
591
+
592
+ ## MessageManagementService
593
+
594
+ Quản lý tin nhắn và analytics.
595
+
596
+ ### Methods
597
+
598
+ #### getMessageHistory()
599
+ ```typescript
600
+ async getMessageHistory(accessToken: string, params: MessageHistoryParams): Promise<MessageHistoryResponse>
601
+ ```
602
+
603
+ #### getMessageAnalytics()
604
+ ```typescript
605
+ async getMessageAnalytics(accessToken: string, params: MessageAnalyticsParams): Promise<MessageAnalytics>
606
+ ```
607
+
608
+ #### getMessageStatus()
609
+ ```typescript
610
+ async getMessageStatus(accessToken: string, messageId: string): Promise<MessageStatus>
611
+ ```
612
+
613
+ ---
614
+
615
+ ## Error Handling
616
+
617
+ Tất cả methods có thể throw `ZaloSDKError`:
618
+
619
+ ```typescript
620
+ class ZaloSDKError extends Error {
621
+ code: number; // Mã lỗi từ Zalo API
622
+ details?: any; // Chi tiết lỗi
623
+ statusCode?: number; // HTTP status code
624
+ }
625
+ ```
626
+
627
+ ### Common Error Codes
628
+
629
+ | Code | Description | Giải pháp |
630
+ |------|-------------|-----------|
631
+ | -216 | Invalid access token | Refresh token hoặc re-authenticate |
632
+ | -201 | Invalid parameters | Kiểm tra tham số đầu vào |
633
+ | -223 | Quota exceeded | Chờ reset quota hoặc nâng cấp gói |
634
+ | -204 | User not found | Kiểm tra user_id |
635
+ | -207 | Template not found | Kiểm tra template_id |
636
+
637
+ ---
638
+
639
+ ## Rate Limiting
640
+
641
+ - **OA Messages**: Theo quota package
642
+ - **ZNS Messages**: Theo quota mua
643
+ - **API Calls**: Không giới hạn cụ thể, nhưng nên có throttling
644
+
645
+ ---
646
+
647
+ ## Authentication Requirements
648
+
649
+ | Service | Required Token Type | Scope |
650
+ |---------|-------------------|--------|
651
+ | AuthService | N/A | N/A |
652
+ | OAService | OA Access Token | Official Account |
653
+ | ConsultationService | OA Access Token | Official Account |
654
+ | ZNSService | OA Access Token | Official Account |
655
+ | UserService | Social Access Token | Social API |
656
+ | GroupServices | OA Access Token | Official Account |
657
+ | All Message Services | OA Access Token | Official Account |
658
+
659
+ ---
660
+
661
+ ## Best Practices
662
+
663
+ 1. **Token Management**: Luôn refresh token trước khi hết hạn
664
+ 2. **Error Handling**: Implement retry logic với exponential backoff
665
+ 3. **Rate Limiting**: Implement throttling để tránh hit limit
666
+ 4. **Logging**: Enable debug mode trong development
667
+ 5. **Security**: Không log access token hoặc sensitive data
668
+ 6. **Testing**: Sử dụng development mode cho ZNS khi test
669
+
670
+ ---
671
+
672
+ ## Migration Notes
673
+
674
+ ### From v1.1.x to v1.2.x
675
+ - Added new message services (Consultation, Transaction, Promotion)
676
+ - Deprecated MessageService, use specialized services instead
677
+ - Added VideoUploadService
678
+ - Enhanced error handling
679
+
680
+ Xem [CHANGELOG.md](../CHANGELOG.md) để biết chi tiết về các thay đổi.