@warriorteam/redai-zalo-sdk
Version:
Comprehensive TypeScript/JavaScript SDK for Zalo APIs - Official Account, ZNS, Consultation Service, Group Messaging, and Social APIs
541 lines (417 loc) • 19.1 kB
Markdown
# Services Added to RedAI Zalo SDK
This document summarizes all the services that have been added to the RedAI Zalo SDK from the backend `redai-v201-be-app/src/shared/services/zalo` directory.
## New Services Added
### 1. ConsultationService (`src/services/consultation.service.ts`)
**Purpose**: Customer Service messaging for sending consultation messages within 48-hour window
**Key Features**:
- Send consultation text messages
- Send consultation image messages
- Send consultation file messages
- Send consultation sticker messages
- Send general consultation messages
- Automatic validation of message content
- Built-in error handling and retry logic
- 48-hour interaction window enforcement
**Main Methods**:
- `sendTextMessage()` - Send consultation text message (max 2000 characters)
- `sendImageMessage()` - Send consultation image with support content
- `sendFileMessage()` - Send consultation file attachments (guides, manuals)
- `sendStickerMessage()` - Send consultation sticker messages
- `sendMessage()` - Send any type of consultation message
**Usage Conditions**:
- Must be sent within 48 hours of last user interaction
- Content must be consultation/support related (no direct advertising)
- User must have followed the OA and not blocked it
- No daily limit but must follow anti-spam guidelines
**Integration**:
- Accessible via `zalo.consultation` property
- Quick methods: `zalo.sendConsultationText()`, `zalo.sendConsultationImage()`
- Full webhook integration support
- Comprehensive error handling with ZaloSDKError
### 2. ZNSService (`src/services/zns.service.ts`)
**Purpose**: Zalo Notification Service for sending template-based notifications
**Key Features**:
- Send ZNS messages with templates
- Send hash phone messages
- Send development mode messages
- Send RSA encrypted messages
- Send journey messages
- Get message status
- Get quota information
- Template management (create, update, delete, list)
- Image upload for templates
**Main Methods**:
- `sendMessage()` - Send ZNS notification
- `sendHashPhoneMessage()` - Send with hashed phone
- `sendDevModeMessage()` - Send in development mode
- `getMessageStatus()` - Check message delivery status
- `getQuotaInfo()` - Get remaining quota
- `getTemplateList()` - List all templates
- `createTemplate()` - Create new template
- `updateTemplate()` - Update existing template
- `deleteTemplate()` - Delete template
- `uploadImage()` - Upload image for template
### 2. GroupMessageService (`src/services/group-message.service.ts`)
**Purpose**: Group Message Framework for sending messages to Zalo groups
**Key Features**:
- Send text messages to groups
- Send image messages to groups
- Send file messages to groups
- Send sticker messages to groups
- Send mention messages to groups
- Get group information
- Get group members
**Main Methods**:
- `sendTextMessage()` - Send text to group
- `sendImageMessage()` - Send image to group
- `sendFileMessage()` - Send file to group
- `sendStickerMessage()` - Send sticker to group
- `sendMentionMessage()` - Send message with mentions
- `getGroupInfo()` - Get group details
- `getGroupMembers()` - Get group member list
### 3. GroupManagementService (`src/services/group-management.service.ts`)
**Purpose**: Comprehensive group management for Zalo Official Account GMF
**Key Features**:
- Create and manage groups with asset_id
- Member management (invite, remove, approve)
- Admin management (add/remove admin rights)
- Group information and settings management
- Quota and asset management
- Conversation history access
**Main Methods**:
- `createGroup()` - Create new group with asset_id
- `getGroupInfo()` - Get detailed group information
- `updateGroupInfo()` - Update group information
- `updateGroupAvatar()` - Update group avatar
- `inviteMembers()` - Invite members to group
- `removeMembers()` - Remove members from group
- `getPendingMembers()` - Get pending member requests
- `acceptPendingMembers()` - Accept pending members
- `rejectPendingMembers()` - Reject pending members
- `addAdmins()` - Add admin rights to members
- `removeAdmins()` - Remove admin rights from members
- `deleteGroup()` - Delete/disband group
- `getGroupsOfOA()` - Get list of OA groups
- `getGroupQuota()` - Get group quota information
- `getAssetId()` - Get asset_id for group creation
- `getAssetIds()` - Get list of available asset_ids
- `getRecentChats()` - Get recent chat conversations
- `getGroupConversation()` - Get group conversation history
- `getGroupMembers()` - Get group members list
### 4. ArticleService (`src/services/article.service.ts`)
**Purpose**: Comprehensive article management for Zalo Official Account
**Key Features**:
- Create and manage normal articles with rich content
- Create and manage video articles
- Article validation and error handling
- Progress tracking for article creation/updates
- Article listing and detail retrieval
**Main Methods**:
- `createNormalArticle()` - Create normal article with rich content
- `createVideoArticle()` - Create video article
- `createArticle()` - Create article (auto-detect type)
- `updateNormalArticle()` - Update normal article
- `updateVideoArticle()` - Update video article
- `updateArticle()` - Update article (auto-detect type)
- `getArticleDetail()` - Get article details
- `getArticleList()` - Get article list with pagination
- `removeArticle()` - Remove/delete article
- `checkArticleProcess()` - Check article creation progress
- `verifyArticle()` - Verify article and get ID
### 5. VideoUploadService (`src/services/video-upload.service.ts`)
**Purpose**: Video upload and management for articles
**Key Features**:
- Upload video files for articles
- Video processing status tracking
- Polling for upload completion
- Video upload from URLs
- Video file validation
**Main Methods**:
- `uploadVideo()` - Upload video file for articles
- `checkVideoStatus()` - Check video processing status
- `waitForUploadCompletion()` - Wait for upload completion with polling
- `uploadVideoFromUrl()` - Upload video from URL
- `getVideoInfo()` - Get video information by ID
### 6. Webhook Event DTOs (`src/types/webhook.ts`)
**Purpose**: Comprehensive TypeScript types for Zalo webhook events
**Key Features**:
- Type-safe webhook event handling
- Specific event types for each webhook event
- Attachment payload types for different media types
- Type guards and utility functions
- Backward compatibility with legacy events
**Event Types**:
**User Message Events:**
- `UserSendTextEvent` - User sends text message
- `UserSendImageEvent` - User sends image message
- `UserSendLocationEvent` - User sends location
- `UserSendLinkEvent` - User sends link
- `UserSendStickerEvent` - User sends sticker
- `UserSendGifEvent` - User sends GIF
- `UserSendAudioEvent` - User sends audio/voice
- `UserSendVideoEvent` - User sends video message
- `UserSendFileEvent` - User sends file attachment
- `UserReceivedMessageEvent` - Message delivery confirmation
- `UserSeenMessageEvent` - Message read confirmation
**User Action Events:**
- `UserFollowEvent` - User follows Official Account
- `UserUnfollowEvent` - User unfollows Official Account
- `UserSubmitInfoEvent` - User submits personal information
**OA Message Events:**
- `OASendTextEvent` - OA sends text message
- `OASendImageEvent` - OA sends image message
- `OASendGifEvent` - OA sends GIF message
- `OASendListEvent` - OA sends interactive list message
- `OASendFileEvent` - OA sends file attachment
- `OASendStickerEvent` - OA sends sticker message
**User Interaction Events:**
- `UserClickChatNowEvent` - User clicks "Chat Now" button
- `UserReactedMessageEvent` - User reacts to message with emoji
- `UserReplyConsentEvent` - User replies to consent request
**OA Interaction Events:**
- `OAReactedMessageEvent` - OA reacts to message with emoji
- `OASendConsentEvent` - OA sends consent request for call
**Anonymous User Events:**
- `AnonymousSendTextEvent` - Anonymous user sends text message
- `AnonymousSendImageEvent` - Anonymous user sends image message
- `AnonymousSendFileEvent` - Anonymous user sends file attachment
**Shop Events:**
- `ShopHasOrderEvent` - New order created
**ZNS Events:**
- `ChangeOADailyQuotaEvent` - OA daily quota changed
- `ChangeOATemplateTagsEvent` - OA template tags changed
- `ChangeTemplateQualityEvent` - Template quality changed
- `ChangeTemplateQuotaEvent` - Template quota changed
- `ChangeTemplateStatusEvent` - Template status changed
- `JourneyTimeoutEvent` - Journey timeout
- `JourneyAcknowledgedEvent` - Journey acknowledged/charged
- `ZNSUserReceivedMessageEvent` - User received ZNS message
**Group Events:**
- `CreateGroupEvent` - Group created
- `UserJoinGroupEvent` - User joined group
- `UserRequestJoinGroupEvent` - User requested to join group
- `ReactRequestJoinGroupEvent` - Join request approved
- `RejectRequestJoinGroupEvent` - Join request rejected
- `AddGroupAdminEvent` - Group admin added
- `RemoveGroupAdminEvent` - Group admin removed
- `UpdateGroupInfoEvent` - Group info updated
- `UserOutGroupEvent` - User left group
- `OASendGroupTextEvent` - OA sends text to group
- `OASendGroupImageEvent` - OA sends image to group
- `OASendGroupLinkEvent` - OA sends link to group
- `OASendGroupAudioEvent` - OA sends audio to group
- `OASendGroupLocationEvent` - OA sends location to group
- `OASendGroupVideoEvent` - OA sends video to group
- `OASendGroupBusinessCardEvent` - OA sends business card to group
- `OASendGroupStickerEvent` - OA sends sticker to group
- `OASendGroupGifEvent` - OA sends GIF to group
- `OASendGroupFileEvent` - OA sends file to group
- `UserSendGroupTextEvent` - User sends text to group
- `UserSendGroupLinkEvent` - User sends link to group
- `UserSendGroupAudioEvent` - User sends audio to group
- `UserSendGroupLocationEvent` - User sends location to group
- `UserSendGroupVideoEvent` - User sends video to group
- `UserSendGroupBusinessCardEvent` - User sends business card to group
- `UserSendGroupStickerEvent` - User sends sticker to group
- `UserSendGroupGifEvent` - User sends GIF to group
- `UserSendGroupFileEvent` - User sends file to group
**Widget Events:**
- `WidgetInteractionAcceptedEvent` - User accepted widget interaction
- `WidgetFailedToSyncUserExternalIdEvent` - Failed to sync user external ID
**System Events:**
- `PermissionRevokedEvent` - Permission revoked between app and OA
- `ExtensionPurchasedEvent` - OA purchased extension successfully
- `UpdateUserInfoEvent` - User info updated
- `AddUserToTagEvent` - User added to tag
**Attachment Types**:
- `LocationPayload` - GPS coordinates
- `ImagePayload` - Image with thumbnail
- `LinkPayload` - Link with preview
- `StickerPayload` - Sticker with ID and URL
- `GifPayload` - GIF with thumbnail
- `AudioPayload` - Audio file URL
- `VideoPayload` - Video with thumbnail and description
- `FilePayload` - File with metadata (size, name, checksum, type)
- `EnhancedLinkPayload` - Link with title for OA list messages
**Utility Functions**:
- `isMessageEvent()` - Type guard for all message events (user + OA + anonymous + group)
- `isFollowEvent()` - Type guard for follow/unfollow events
- `isUserActionEvent()` - Type guard for user action events (follow, click, react, consent, feedback)
- `isShopEvent()` - Type guard for shop events
- `isOAMessageEvent()` - Type guard for OA message events
- `isAnonymousEvent()` - Type guard for anonymous user events
- `isCallEvent()` - Type guard for call events (OA call user, user call OA)
- `isReactionEvent()` - Type guard for reaction events (user + OA)
- `isConsentEvent()` - Type guard for consent events (send + reply)
- `isTemplateEvent()` - Type guard for template events
- `isBusinessCardEvent()` - Type guard for business card events
- `isFeedbackEvent()` - Type guard for feedback events
- `isZNSEvent()` - Type guard for ZNS events (quota, template, journey, status)
- `isGroupEvent()` - Type guard for group events (create, join, admin, all message types)
- `isJourneyEvent()` - Type guard for journey events (timeout, acknowledged)
- `isQuotaTemplateEvent()` - Type guard for quota/template change events
- `isWidgetEvent()` - Type guard for widget events (interaction, sync)
- `isSystemEvent()` - Type guard for system events (permission, extension, user info)
- `isPermissionEvent()` - Type guard for permission events
- `isExtensionEvent()` - Type guard for extension events
- `isUpdateUserInfoEvent()` - Type guard for user info update events
- `hasAttachments()` - Type guard for messages with attachments
### 7. SocialService (`src/services/social.service.ts`)
**Purpose**: Zalo Social API for user authentication and social features
**Key Features**:
- PKCE (Proof Key for Code Exchange) support
- OAuth 2.0 authentication flow
- User information retrieval
- Friends list management
- Timeline posting
- Message sending
- Token validation and refresh
**Main Methods**:
- `generatePKCEPair()` - Generate PKCE for security
- `generateAuthUrl()` - Create authorization URL
- `getAccessToken()` - Exchange code for token
- `refreshAccessToken()` - Refresh expired token
- `getUserInfo()` - Get user profile
- `getFriendsList()` - Get user's friends
- `postToTimeline()` - Post to user timeline
- `sendMessage()` - Send message to friend
- `validateToken()` - Validate access token
### 4. UserManagementService (`src/services/user-management.service.ts`)
**Purpose**: Comprehensive user management for OA
**Key Features**:
- User profile management
- User search by phone
- User tagging and segmentation
- User notes management
- User interaction tracking
- Followers list management
**Main Methods**:
- `getUserProfile()` - Get detailed user profile
- `getFollowersList()` - Get OA followers
- `searchUserByPhone()` - Find user by phone number
- `getUserTags()` - Get user's tags
- `tagUser()` - Add tags to user
- `untagUser()` - Remove tags from user
- `getAllTags()` - Get all available tags
- `createTag()` - Create new tag
- `deleteTag()` - Delete tag
- `addUserNote()` - Add note to user
- `getUserNotes()` - Get user notes
- `getUserInteractions()` - Get user interaction history
### 5. TagService (`src/services/tag.service.ts`)
**Purpose**: Dedicated tag management service
**Key Features**:
- Tag creation and deletion
- User tagging operations
- Bulk tagging operations
- Tag-based user retrieval
**Main Methods**:
- `getAllTags()` - Get all OA tags
- `getUserTags()` - Get specific user's tags
- `createTag()` - Create new tag
- `deleteTag()` - Delete existing tag
- `tagUser()` - Tag a user
- `untagUser()` - Remove tags from user
- `getUsersByTag()` - Get users with specific tag
- `bulkTagUsers()` - Tag multiple users at once
- `bulkUntagUsers()` - Remove tags from multiple users
### 6. ContentService (`src/services/content.service.ts`)
**Purpose**: Content and media management
**Key Features**:
- Image, file, and GIF upload
- Article creation and management
- Media information retrieval
- Content sharing
**Main Methods**:
- `uploadImage()` - Upload image files
- `uploadFile()` - Upload general files
- `uploadGif()` - Upload GIF files
- `getMediaInfo()` - Get media details
- `createArticle()` - Create article content
- `updateArticle()` - Update article
- `getArticle()` - Get article details
- `getArticleList()` - List all articles
- `deleteArticle()` - Delete article
- `shareArticle()` - Share article to user
### 7. VideoUploadService (`src/services/video-upload.service.ts`)
**Purpose**: Video upload and management
**Key Features**:
- Video file upload
- Upload status tracking
- Video information management
- Video message sending
- Video analytics
- Thumbnail generation
**Main Methods**:
- `uploadVideo()` - Upload video file
- `getUploadStatus()` - Check upload progress
- `getVideoInfo()` - Get video details
- `sendVideoMessage()` - Send video to user
- `uploadVideoFromUrl()` - Upload from URL
- `getVideoList()` - List uploaded videos
- `deleteVideo()` - Delete video
- `generateThumbnail()` - Create video thumbnail
- `getVideoAnalytics()` - Get video metrics
- `waitForUploadCompletion()` - Wait for processing
## Type Definitions Added
### 1. ZNS Types (`src/types/zns.ts`)
- `ZNSMessage`, `ZNSHashPhoneMessage`, `ZNSDevModeMessage`
- `ZNSRsaMessage`, `ZNSJourneyMessage`
- `ZNSSendResult`, `ZNSTemplate`, `ZNSTemplateList`
- `ZNSCreateTemplateRequest`, `ZNSUpdateTemplateRequest`
- `ZNSUploadImageResult`, `ZNSStatusInfo`, `ZNSMessageStatusInfo`
- `ZNSQuotaInfo`, `ZNSQualityInfo`, `ZNSAnalytics`
### 2. Group Types (`src/types/group.ts`)
- `GroupMessage`, `GroupTextMessage`, `GroupImageMessage`
- `GroupFileMessage`, `GroupStickerMessage`, `GroupMentionMessage`
- `GroupMessageResult`, `GroupInfo`, `GroupMember`
- `GroupSettings`, `GroupStatistics`, `GroupBroadcast`
### 3. Social Types (`src/types/social.ts`)
- `AccessToken`, `RefreshTokenResponse`, `SocialUserInfo`
- `SocialProfile`, `SocialFriend`, `SocialPost`
- `SocialMessage`, `SocialConversation`
- `PKCEConfig`, `OAuthConfig`, `AuthorizationRequest`
### 4. User Management Types (`src/types/user-management.ts`)
- `UserProfile`, `UserList`, `UserTag`, `UserTagList`
- `UserNote`, `UserInteraction`, `UserAnalytics`
- `UserSegment`, `UserCustomField`, `UserBehavior`
- `UserJourney`, `UserPreference`, `BulkUserOperation`
## Integration with Main SDK
All services have been integrated into the main `ZaloSDK` class:
```typescript
const sdk = new ZaloSDK(config);
// Access services
sdk.zns.sendMessage(...)
sdk.groupMessage.sendTextMessage(...)
sdk.social.getUserInfo(...)
sdk.userManagement.getUserProfile(...)
sdk.tag.createTag(...)
sdk.content.uploadImage(...)
sdk.videoUpload.uploadVideo(...)
```
## Export Structure
All services and types are properly exported from the main index file:
```typescript
// Services
export { ZNSService } from "./services/zns.service";
export { GroupMessageService } from "./services/group-message.service";
export { SocialService } from "./services/social.service";
export { UserManagementService } from "./services/user-management.service";
export { TagService } from "./services/tag.service";
export { ContentService } from "./services/content.service";
export { VideoUploadService } from "./services/video-upload.service";
// Types
export * from "./types/zns";
export * from "./types/group";
export * from "./types/social";
export * from "./types/user-management";
```
## Benefits
1. **Complete API Coverage**: All major Zalo APIs are now supported
2. **Type Safety**: Full TypeScript support with comprehensive type definitions
3. **Consistent Interface**: All services follow the same patterns and error handling
4. **Easy Integration**: Services are accessible through the main SDK instance
5. **Comprehensive Documentation**: Each service includes detailed JSDoc comments
6. **Error Handling**: Consistent error handling across all services
7. **Future-Proof**: Easy to extend and maintain
This comprehensive SDK now provides complete coverage of Zalo's API ecosystem, making it easy for developers to integrate all Zalo features into their applications.