@warriorteam/redai-zalo-sdk
Version:
Comprehensive TypeScript/JavaScript SDK for Zalo APIs - Official Account v3.0, ZNS with Full Type Safety, Consultation Service, Broadcast Service, Group Messaging with List APIs, Social APIs, Enhanced Article Management, Promotion Service v3.0 with Multip
362 lines (292 loc) • 8.75 kB
Markdown
# RedAI Zalo SDK - Broadcast Service Guide
## Tổng quan
BroadcastService cho phép gửi tin truyền thông broadcast đến nhiều người dùng cùng lúc dựa trên các tiêu chí targeting như tuổi, giới tính, địa điểm, và platform.
## API Endpoint
- **URL**: `https://openapi.zalo.me/v2.0/oa/message`
- **Method**: POST
- **Content-Type**: application/json
- **Header**: `access_token: <your_access_token>`
## Khởi tạo Service
```typescript
import { ZaloSDK } from "@warriorteam/redai-zalo-sdk";
const zalo = new ZaloSDK({
appId: "your-app-id",
appSecret: "your-app-secret"
});
// Access broadcast service
const broadcastService = zalo.broadcast;
```
## Các Phương Thức Chính
### 1. Gửi Broadcast Message
```typescript
// Gửi broadcast đến người dùng ở Hồ Chí Minh
const target = zalo.broadcast.createBroadcastTarget({
cities: ["Hồ Chí Minh"]
});
const result = await zalo.broadcast.sendBroadcastMessage(
accessToken,
{ target },
"article-attachment-id"
);
console.log("Message ID:", result.data.message_id);
```
### 2. Gửi Nhiều Broadcast Messages
```typescript
// Gửi nhiều article attachments tuần tự
const attachmentIds = [
"article-id-1",
"article-id-2",
"article-id-3"
];
const target = zalo.broadcast.createBroadcastTarget({
cities: ["Hồ Chí Minh"]
});
const result = await zalo.broadcast.sendMultipleBroadcastMessages(
accessToken,
{ target },
attachmentIds,
{
mode: 'sequential',
delay: 2000, // 2 giây giữa các tin
onProgress: (progress) => {
console.log(`${progress.completed}/${progress.total} completed`);
}
}
);
console.log(`Sent ${result.successfulMessages}/${result.totalMessages} messages`);
```
### 3. Tạo Targeting Criteria
```typescript
// Targeting phức tạp
const complexTarget = zalo.broadcast.createBroadcastTarget({
gender: "FEMALE", // Nữ giới
ages: ["18-24", "25-34"], // Tuổi 18-34
cities: ["Hà Nội", "Đà Nẵng"], // Hà Nội và Đà Nẵng
platform: ["ANDROID", "IOS"] // Android và iOS
});
```
## Targeting Criteria
### 1. Nhóm Tuổi (Ages)
| Nhóm tuổi | Mã | Mô tả |
|-----------|----|----|
| `"0-12"` | `"0"` | Tuổi từ 0-12 |
| `"13-17"` | `"1"` | Tuổi từ 13-17 |
| `"18-24"` | `"2"` | Tuổi từ 18-24 |
| `"25-34"` | `"3"` | Tuổi từ 25-34 |
| `"35-44"` | `"4"` | Tuổi từ 35-44 |
| `"45-54"` | `"5"` | Tuổi từ 45-54 |
| `"55-64"` | `"6"` | Tuổi từ 55-64 |
| `"65+"` | `"7"` | Tuổi từ 65 trở lên |
```typescript
const target = zalo.broadcast.createBroadcastTarget({
ages: ["18-24", "25-34"] // Targeting 18-34 tuổi
});
```
### 2. Giới Tính (Gender)
| Giới tính | Mã | Mô tả |
|-----------|----|----|
| `"ALL"` | `"0"` | Tất cả giới tính |
| `"MALE"` | `"1"` | Nam |
| `"FEMALE"` | `"2"` | Nữ |
```typescript
const target = zalo.broadcast.createBroadcastTarget({
gender: "MALE" // Chỉ targeting nam giới
});
```
### 3. Tỉnh Thành (Cities)
Hỗ trợ 63 tỉnh thành Việt Nam:
```typescript
const target = zalo.broadcast.createBroadcastTarget({
cities: ["Hồ Chí Minh", "Hà Nội", "Đà Nẵng"]
});
// Xem tất cả mã tỉnh thành
const cityCodes = zalo.broadcast.getCityCodes();
console.log(cityCodes);
```
### 4. Miền (Locations)
| Miền | Mã | Mô tả |
|------|----|----|
| `"NORTH"` | `"0"` | Miền Bắc |
| `"CENTRAL"` | `"1"` | Miền Trung |
| `"SOUTH"` | `"2"` | Miền Nam |
```typescript
const target = zalo.broadcast.createBroadcastTarget({
locations: ["SOUTH"] // Chỉ miền Nam
});
```
### 5. Platform
| Platform | Mã | Mô tả |
|----------|----|----|
| `"IOS"` | `"1"` | iOS |
| `"ANDROID"` | `"2"` | Android |
| `"WINDOWS_PHONE"` | `"3"` | Windows Phone |
```typescript
const target = zalo.broadcast.createBroadcastTarget({
platforms: ["IOS", "ANDROID"] // iOS và Android
});
```
## Ví Dụ Sử Dụng
### 1. Broadcast Đơn Giản
```typescript
// Gửi đến tất cả người dùng ở Hồ Chí Minh
const target = zalo.broadcast.createBroadcastTarget({
cities: ["Hồ Chí Minh"]
});
const result = await zalo.broadcast.sendBroadcastMessage(
accessToken,
{ target },
"bd5ea46bb32e5a0033f"
);
```
### 2. Targeting Theo Nhân Khẩu Học
```typescript
// Nữ giới 25-34 tuổi
const target = zalo.broadcast.createBroadcastTarget({
gender: "FEMALE",
ages: ["25-34"]
});
const result = await zalo.broadcast.sendBroadcastMessage(
accessToken,
{ target },
"article-id"
);
```
### 3. Targeting Phức Tạp
```typescript
// Nam giới 18-34 tuổi, dùng iOS, ở miền Nam
const target = zalo.broadcast.createBroadcastTarget({
gender: "MALE",
ages: ["18-24", "25-34"],
platforms: ["IOS"],
locations: ["SOUTH"]
});
const result = await zalo.broadcast.sendBroadcastMessage(
accessToken,
{ target },
"article-id"
);
```
### 4. Gửi Nhiều Messages Song Song
```typescript
// Gửi nhiều articles cùng lúc (parallel)
const attachmentIds = [
"promo-article-1",
"promo-article-2",
"promo-article-3"
];
const result = await zalo.broadcast.sendMultipleBroadcastMessages(
accessToken,
{ target },
attachmentIds,
{
mode: 'parallel', // Gửi song song
onProgress: (progress) => {
console.log(`Progress: ${progress.completed}/${progress.total}`);
console.log(`Success: ${progress.successful}, Failed: ${progress.failed}`);
}
}
);
console.log("Results:", result.results.map(r => ({
attachmentId: r.attachmentId,
success: r.success,
messageId: r.messageId
})));
```
### 5. Gửi Với Delay Tùy Chỉnh
```typescript
// Gửi tuần tự với delay 5 giây giữa các tin
const result = await zalo.broadcast.sendMultipleBroadcastMessages(
accessToken,
{ target },
attachmentIds,
{
mode: 'sequential',
delay: 5000, // 5 giây
onProgress: (progress) => {
if (progress.isCompleted) {
console.log("All messages sent!");
} else {
console.log(`Sending: ${progress.currentAttachmentId}`);
}
}
}
);
console.log(`Campaign completed in ${result.totalDuration}ms`);
console.log(`Success rate: ${(result.successfulMessages / result.totalMessages * 100).toFixed(1)}%`);
```
## Error Handling
### Các Lỗi Thường Gặp
| Mã lỗi | Mô tả | Giải pháp |
|--------|-------|-----------|
| `3001` | Không có quyền broadcast | Liên hệ Zalo để được cấp quyền |
| `3002` | Article không tồn tại | Kiểm tra attachment_id |
| `3003` | Targeting không hợp lệ | Kiểm tra các tham số targeting |
| `3004` | Vượt quota broadcast | Chờ reset quota hoặc nâng cấp |
| `3005` | Vi phạm chính sách | Kiểm tra nội dung article |
```typescript
try {
const result = await zalo.broadcast.sendBroadcastMessage(
accessToken,
{ target },
articleId
);
console.log("Success:", result.data.message_id);
} catch (error) {
switch (error.code) {
case 3001:
console.error("Không có quyền broadcast");
break;
case 3002:
console.error("Article không tồn tại");
break;
default:
console.error("Lỗi khác:", error.message);
}
}
```
## Yêu Cầu và Giới Hạn
### 1. Quyền Broadcast
- OA phải được Zalo cấp quyền gửi broadcast
- Cần tuân thủ chính sách về spam và nội dung
### 2. Article Attachment
- Chỉ hỗ trợ template type `"media"` với `media_type: "article"`
- Article phải được tạo trước và có attachment_id hợp lệ
### 3. Targeting
- Phải có ít nhất 1 tiêu chí targeting
- Có thể kết hợp nhiều tiêu chí cùng lúc
### 4. Rate Limiting
- Tuân thủ giới hạn số lượng broadcast theo gói dịch vụ
- Tránh gửi quá nhiều broadcast trong thời gian ngắn
## Best Practices
### 1. Targeting Hiệu Quả
```typescript
// Tốt: Targeting cụ thể
const target = zalo.broadcast.createBroadcastTarget({
gender: "FEMALE",
ages: ["25-34"],
cities: ["Hồ Chí Minh"]
});
// Tránh: Targeting quá rộng
const broadTarget = zalo.broadcast.createBroadcastTarget({
gender: "ALL" // Quá rộng, có thể bị spam
});
```
### 2. Nội Dung Chất Lượng
- Sử dụng article có nội dung hữu ích
- Tránh nội dung spam hoặc quảng cáo quá mức
- Tuân thủ chính sách của Zalo
### 3. Monitoring và Analytics
```typescript
// Lưu message_id để tracking
const result = await zalo.broadcast.sendBroadcastMessage(
accessToken,
{ target },
articleId
);
// Lưu vào database để theo dõi
await saveBroadcastLog({
messageId: result.data.message_id,
targetCriteria: target,
sentAt: new Date()
});
```