Skip to content

Tích Hợp Với Node.js / TypeScript ​

Hướng dẫn tích hợp xuất bản video lên TikTok bằng TypeScript: hỗ trợ đăng bằng đường dẫn trực tiếp (Direct URL) hoặc tải tệp video nhị phân cục bộ qua Presigned URL.


1. Cài đặt thư viện ​

bash
npm install axios
# hoặc
pnpm add axios

2. Cách 1: Đăng video khi đã có sẵn URL trực tiếp (Khuyên dùng) ​

Nếu video của bạn đã được lưu trữ trên CDN, Amazon S3, Google Cloud, hoặc máy chủ riêng, bạn chỉ cần gọi trực tiếp API Đăng bài:

typescript
import axios from 'axios';

const API_KEY = process.env.STACKVID_API_KEY || 'tk_live_YOUR_KEY';

async function publishWithDirectUrl() {
  const res = await axios.post(
    'https://api.stackvid.dev/api/tiktok/upload',
    {
      videoUrl: 'https://cdn.yourdomain.com/videos/product-demo.mp4',
      text: 'Trải nghiệm sản phẩm mới cực chất! 🔥 #review #trending',
      targetChannel: 'Kênh Thời Trang Hottrend',
      privacyLevel: 0,
    },
    {
      headers: {
        'X-API-Key': API_KEY,
        'Content-Type': 'application/json',
      },
    }
  );

  console.log('✅ Đăng video thành công! Item ID:', res.data.itemId);
}

3. Cách 2: Tải lên tệp video nhị phân cục bộ (publish-local-video.ts) ​

Nếu bạn có file video .mp4 trên máy tính hoặc máy chủ cục bộ (chưa có URL công khai), thực hiện quy trình 2 bước:

typescript
import axios from 'axios';
import fs from 'fs';
import path from 'path';

const API_BASE_URL = 'https://api.stackvid.dev/api';
const API_KEY = process.env.STACKVID_API_KEY || 'tk_live_YOUR_KEY';

const client = axios.create({
  baseURL: API_BASE_URL,
  headers: {
    'X-API-Key': API_KEY,
    'Content-Type': 'application/json',
  },
});

async function publishLocalVideoWorkflow(videoFilePath: string, caption: string, channelName?: string) {
  try {
    const stats = fs.statSync(videoFilePath);
    console.log(`📁 File video: ${path.basename(videoFilePath)} (${stats.size} bytes)`);

    // 1. Yêu cầu cấp Presigned Upload URL
    console.log('⚡ 1. Yêu cầu cấp Presigned Upload URL...');
    const presignedRes = await client.post('/uploads/presigned-url', {
      fileType: 'VIDEO',
      contentType: 'video/mp4',
      fileSizeBytes: stats.size,
    });

    const { uploadUrl, publicUrl } = presignedRes.data;
    console.log('✅ Đã nhận Upload URL!');

    // 2. Upload Binary trực tiếp lên uploadUrl
    console.log('🚀 2. Đang tải video lên...');
    const fileStream = fs.createReadStream(videoFilePath);
    await axios.put(uploadUrl, fileStream, {
      headers: {
        'Content-Type': 'video/mp4',
        'Content-Length': stats.size,
      },
      maxBodyLength: Infinity,
      maxContentLength: Infinity,
    });
    console.log('✅ Tải lên hoàn tất! Public URL:', publicUrl);

    // 3. Đăng video lên TikTok bằng publicUrl
    console.log('📱 3. Đang xuất bản video lên TikTok...');
    const publishRes = await client.post('/tiktok/upload', {
      videoUrl: publicUrl,
      text: caption,
      targetChannel: channelName,
      privacyLevel: 0,
    });

    console.log('🎉 ĐĂNG BÀI THÀNH CÔNG!');
    console.log('🔗 Link video:', publishRes.data.shareUrl);
  } catch (err: any) {
    console.error('❌ Lỗi:', err.response?.data || err.message);
  }
}

// Chạy thử với tệp video cục bộ
publishLocalVideoWorkflow(
  './my-awesome-video.mp4',
  'Video tự động hóa bằng StackVid API! #automation #developer',
  'Kênh Thời Trang Hottrend'
);

StackVid - Multi-Platform Video & Social Commerce Automation Platform.