登入開始免費試用
easyCoexistence 官方 API

Python 與 Node.js 的 TikTok API:實用範例

TikTok 的 API for Business 可在 Python 或 Node.js 中以一般 HTTPS 請求運作:每次呼叫都發送至 https://business-api.tiktok.com/open_api/v1.3,並在 Access-Token 標頭中放入帳戶的存取權杖,同時把其 open_id 作為 business_id。TikTok 大多數呼叫都會回傳 HTTP 200 及 code 欄位,成功時為 0,因此請檢查該欄位,遇到 40100 時則暫停 5 分鐘。

easyCoexistence 將 TikTok 的工作以工具形式提供給 Claude、ChatGPT 或您自己的程式,從 publish_tiktok_post、reply_to_comment 到 get_social_insights,並可透過 get_social_credentials 或 Partner API 為腳本提供最新的存取權杖。

HTTP 200

大多數 TikTok 回應的狀態(包括錯誤):只有回應主體中 code 為 0,才代表呼叫成功。

40100

受速率限制呼叫的代碼:TikTok 在每分鐘限額後要求暫停 5 分鐘,在每日限額後則要求等到 UTC 00:00。

5xx

伺服器錯誤:TikTok 建議在約 5 分鐘後才再次呼叫。

Final /

路徑須以斜線結尾;TikTok 指出缺少斜線的 /tt_user/oauth2/refresh_token 會導致 404 page not found。

3 languages

TikTok API for Business SDK 提供 Python、JavaScript 及 Java 版本,但其端點清單中沒有 /business/ 端點。

HMAC-SHA256

每個 webhook 的 Tiktok-Signature 標頭簽名,由時間戳、一個句號及主體組成,並以應用程式密鑰為金鑰。

每個 TikTok API 呼叫需要哪些內容?

無論執行哪項工作,都需要以下五項:

  • 基本網址 https://business-api.tiktok.com/open_api/v1.3,路徑須以斜線結尾,例如 /business/video/list/。
  • 帳戶的存取權杖,放在 Access-Token 標頭中,並須在 24 小時有效期屆滿前更新。
  • business_id,即帳戶的 open_id:GET 放在查詢字串中,POST 放在 JSON 主體中。
  • GET 的列表與物件參數(例如 fields 及 filters)以 JSON 文字傳送:fields=["item_id","caption"]。
  • 檢查回應中的 code,因為 TikTok 回傳 40002 或 40100 等錯誤時會附 HTTP 200,且只有 code 為 0 時才會有 data。

在 Python 中如何處理 TikTok 的錯誤封裝?

使用一個小型客戶端,在各方法需要的位置放入 business_id,code 為 0 時回傳 data,否則拋出 TikTokError。遇到受速率限制的呼叫時,會在 TikTok 的 5 分鐘暫停後重試,因為 40100 代表 TikTok 拒絕了該呼叫;5xx 錯誤則只對 GET 重試,因為以伺服器錯誤結束的發布仍可能已送達 TikTok。此客戶端需要 requests,後面的 Python 範例都會重用它:

Python: a TikTok client that reads the envelope
import json
import os
import time

import requests

API = "https://business-api.tiktok.com/open_api/v1.3"


class TikTokError(Exception):
    def __init__(self, code, message, request_id):
        super().__init__(f"TikTok {code}: {message} (request_id {request_id})")
        self.code = code


class TikTok:
    """One TikTok account: its access token and its business_id, the open_id."""

    def __init__(self, access_token, business_id, pause=300):
        self.http = requests.Session()
        self.http.headers["Access-Token"] = access_token
        self.business_id = business_id
        self.pause = pause  # TikTok's advice after a 40100 or a 5xx: about 5 minutes

    def call(self, method, path, params=None, body=None, tries=3):
        for attempt in range(1, tries + 1):
            if method == "GET":
                query = {"business_id": self.business_id}
                for key, value in (params or {}).items():
                    is_json = isinstance(value, (list, dict))
                    query[key] = json.dumps(value, separators=(",", ":")) if is_json else value
                res = self.http.get(f"{API}/{path}", params=query, timeout=30)
            else:
                payload = {"business_id": self.business_id, **(body or {})}
                res = self.http.post(f"{API}/{path}", json=payload, timeout=30)
            if res.status_code >= 500 and method == "GET" and attempt < tries:
                time.sleep(self.pause)  # a POST is not repeated: it may have reached TikTok
                continue
            res.raise_for_status()  # a 4xx: a wrong path or method, such as a missing final slash
            answer = res.json()
            if answer.get("code") == 0:
                return answer.get("data") or {}
            if answer.get("code") == 40100 and attempt < tries:
                time.sleep(self.pause)  # throttled: TikTok refused the call, so repeating it is safe
                continue
            raise TikTokError(answer.get("code"), answer.get("message"), answer.get("request_id"))


tt = TikTok(os.environ["TIKTOK_ACCESS_TOKEN"], os.environ["TIKTOK_BUSINESS_ID"])

在 Node.js 中如何處理?

相同的客戶端,基於 Node.js 18 及以後版本內建的 fetch,無需安裝任何額外套件。GET 時將列表參數編碼為 JSON,POST 時把 business_id 放入主體,並在錯誤中保留 TikTok 的 code,讓呼叫者能分辨 40102 或 40105(權杖問題)與 40001(缺少權限)。:

Node.js: the same client on the built-in fetch
const API = "https://business-api.tiktok.com/open_api/v1.3";
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

class TikTokError extends Error {
  constructor(code, message, requestId) {
    super("TikTok " + code + ": " + message + " (request_id " + requestId + ")");
    this.code = code;
  }
}

// One TikTok account: its access token and its business_id, the open_id.
class TikTok {
  constructor(accessToken, businessId, pauseMs = 300000) {
    this.accessToken = accessToken;
    this.businessId = businessId;
    this.pauseMs = pauseMs; // TikTok's advice after a 40100 or a 5xx: about 5 minutes
  }

  async call(method, path, { params = {}, body = {} } = {}, tries = 3) {
    for (let attempt = 1; ; attempt++) {
      const url = new URL(API + "/" + path);
      const init = { method, headers: { "Access-Token": this.accessToken } };
      if (method === "GET") {
        url.searchParams.set("business_id", this.businessId);
        for (const [key, value] of Object.entries(params)) {
          url.searchParams.set(key, typeof value === "object" ? JSON.stringify(value) : String(value));
        }
      } else {
        init.headers["Content-Type"] = "application/json";
        init.body = JSON.stringify({ business_id: this.businessId, ...body });
      }
      const res = await fetch(url, init);
      if (res.status >= 500 && method === "GET" && attempt < tries) {
        await sleep(this.pauseMs); // a POST is not repeated: it may have reached TikTok
        continue;
      }
      if (!res.ok) throw new Error("HTTP " + res.status + " on " + path + ": check the path, its final slash and the method");
      const answer = await res.json();
      if (answer.code === 0) return answer.data ?? {};
      if (answer.code === 40100 && attempt < tries) {
        await sleep(this.pauseMs); // throttled: TikTok refused the call, so repeating it is safe
        continue;
      }
      throw new TikTokError(answer.code, answer.message, answer.request_id);
    }
  }
}

const tt = new TikTok(process.env.TIKTOK_ACCESS_TOKEN, process.env.TIKTOK_BUSINESS_ID);

如何以網址發布影片並查看狀態?

以 video_url 與 post_info 呼叫 POST /business/video/publish/,然後以 share_id 作為 publish_id,輪詢 /business/publish/status/。狀態為 FAILED 時,迴圈會停止並顯示 TikTok 提供的原因;狀態為 PUBLISH_COMPLETE 時,會持續等待直到 post_ids 出現,TikTok 表示這最多可能需要再三分鐘。video_url 必須位於已為您的應用程式通過驗證的網域或 URL 前綴之下:

Publish a video and wait until it is public: Python, then Node.js
# Python
def wait_until_live(tt, share_id, interval=30, give_up_after=7200):
    deadline = time.time() + give_up_after
    while time.time() < deadline:
        status = tt.call("GET", "business/publish/status/", params={"publish_id": share_id})
        if status["status"] == "FAILED":
            raise RuntimeError(f"TikTok did not publish {share_id}: {status.get('reason')}")
        if status["status"] == "PUBLISH_COMPLETE" and status.get("post_ids"):
            return status["post_ids"]
        time.sleep(interval)  # post_ids can follow PUBLISH_COMPLETE by up to three minutes
    raise TimeoutError(f"{share_id} was not public after {give_up_after} s")


video = tt.call("POST", "business/video/publish/", body={
    "video_url": "https://media.example.com/tiktok/launch.mp4",  # on a verified domain or URL prefix
    "post_info": {
        "caption": "Our spring menu is live #food",
        "is_brand_organic": True,  # the Promotional content label, for the account's own business
        "is_branded_content": False,
    },
})
print("Live:", wait_until_live(tt, video["share_id"]))

// Node.js
async function waitUntilLive(tt, shareId, everyMs = 30000, giveUpAfterMs = 7200000) {
  const deadline = Date.now() + giveUpAfterMs;
  while (Date.now() < deadline) {
    const s = await tt.call("GET", "business/publish/status/", { params: { publish_id: shareId } });
    if (s.status === "FAILED") throw new Error("TikTok did not publish " + shareId + ": " + s.reason);
    if (s.status === "PUBLISH_COMPLETE" && s.post_ids && s.post_ids.length) return s.post_ids;
    await sleep(everyMs); // post_ids can follow PUBLISH_COMPLETE by up to three minutes
  }
  throw new Error(shareId + " was not public after " + giveUpAfterMs / 1000 + " s");
}

async function publishVideo(tt) {
  const video = await tt.call("POST", "business/video/publish/", {
    body: {
      video_url: "https://media.example.com/tiktok/launch.mp4", // on a verified domain or URL prefix
      post_info: { caption: "Our spring menu is live #food", is_brand_organic: true, is_branded_content: false },
    },
  });
  return waitUntilLive(tt, video.share_id);
}

publishVideo(tt).then((postIds) => console.log("Live:", postIds), console.error);

如何發布相片?

先讀取帳戶允許的設定,然後 POST /business/photo/publish/。相片發布需要 privacy_level,且其值必須是 /business/video/settings/ 中 privacy_level_options 的其中一個;若該處 comment_disabled 為 true,disable_comment 也必須為 true。回傳的 share_id 會以與影片相同的等待函式跟進:

Publish a photo post: Python, then Node.js
# Python
def publish_photos(tt, image_urls, title, caption):
    settings = tt.call("GET", "business/video/settings/")
    if "PUBLIC_TO_EVERYONE" not in settings["privacy_level_options"]:
        raise RuntimeError(f"Private account, choose from {settings['privacy_level_options']}")
    photo = tt.call("POST", "business/photo/publish/", body={
        "photo_images": image_urls,  # 1 to 35 JPG, JPEG or WebP links on a verified domain or prefix
        "photo_cover_index": 0,
        "post_info": {
            "title": title,  # up to 90 UTF-16 code units
            "caption": caption,  # up to 4,000
            "privacy_level": "PUBLIC_TO_EVERYONE",
            "disable_comment": settings["comment_disabled"],  # True when the account takes no comments
            "is_brand_organic": True,
            "is_branded_content": False,
        },
    })
    return wait_until_live(tt, photo["share_id"])


print(publish_photos(tt, ["https://media.example.com/menu/1.jpg", "https://media.example.com/menu/2.jpg"],
                     "Spring menu", "Four new dishes, from Friday #food"))

// Node.js
async function publishPhotos(tt, imageUrls, title, caption) {
  const settings = await tt.call("GET", "business/video/settings/");
  if (!settings.privacy_level_options.includes("PUBLIC_TO_EVERYONE")) {
    throw new Error("Private account, choose from " + settings.privacy_level_options.join(", "));
  }
  const photo = await tt.call("POST", "business/photo/publish/", {
    body: {
      photo_images: imageUrls, // 1 to 35 JPG, JPEG or WebP links on a verified domain or prefix
      photo_cover_index: 0,
      post_info: {
        title, // up to 90 UTF-16 code units
        caption, // up to 4,000
        privacy_level: "PUBLIC_TO_EVERYONE",
        disable_comment: settings.comment_disabled, // true when the account takes no comments
        is_brand_organic: true,
        is_branded_content: false,
      },
    },
  });
  return waitUntilLive(tt, photo.share_id);
}

publishPhotos(tt, ["https://media.example.com/menu/1.jpg", "https://media.example.com/menu/2.jpg"],
  "Spring menu", "Four new dishes, from Friday #food").then(console.log, console.error);

如何列出帳戶的影片?

以 GET 呼叫 /business/video/list/,並指定所需欄位(其中包括 item_id),每頁最多 20 則貼文,由最新開始排列。當 has_more 為 true 時,以回傳的 cursor(UTC 毫秒時間戳)繼續翻頁。請預期頁面可能較短,因為 TikTok 的信任與安全規則可能使回傳數量少於 max_count,直至列表結束。

List recent videos across pages: Python, then Node.js
# Python
def recent_videos(tt, how_many=60):
    params = {"fields": ["item_id", "create_time", "caption", "share_url", "video_views", "likes", "comments"],
              "max_count": 20}
    videos = []
    while len(videos) < how_many:
        page = tt.call("GET", "business/video/list/", params=params)
        videos += page.get("videos", [])
        if not page.get("has_more"):
            break
        params["cursor"] = page["cursor"]  # posts published before this UTC time, in milliseconds
    return videos[:how_many]


for v in recent_videos(tt):
    print(v["item_id"], v.get("video_views"), (v.get("caption") or "")[:60])

// Node.js
async function recentVideos(tt, howMany = 60) {
  const params = {
    fields: ["item_id", "create_time", "caption", "share_url", "video_views", "likes", "comments"],
    max_count: 20,
  };
  const videos = [];
  while (videos.length < howMany) {
    const page = await tt.call("GET", "business/video/list/", { params });
    videos.push(...(page.videos ?? []));
    if (!page.has_more) break;
    params.cursor = page.cursor; // posts published before this UTC time, in milliseconds
  }
  return videos.slice(0, howMany);
}

recentVideos(tt).then((videos) => {
  for (const v of videos) console.log(v.item_id, v.video_views, (v.caption || "").slice(0, 60));
}, console.error);

如何讀取留言並回覆?

以 GET 呼叫 /business/comment/list/,並以貼文的 item_id 作為 video_id,每頁最多回傳 30 則留言;POST /business/comment/reply/create/ 可公開回覆其中一則,文字最多 1,200 個字元。範例會回覆尚未有回覆的頂層公開留言,略過帳戶自己的留言,回覆措辭則交由您自行編寫的函式決定,因為 TikTok 可能會把短時間內相隔很近、內容大致相似的留言視為垃圾留言而隱藏:

Reply to new comments on a video: Python, then Node.js
# Python
def reply_to_new_comments(tt, video_id, write_reply):
    page = tt.call("GET", "business/comment/list/", params={
        "video_id": video_id,  # the post's item_id
        "status": "PUBLIC",
        "sort_field": "create_time",
        "sort_order": "desc",
        "max_count": 30,
    })
    for comment in page.get("comments", []):
        if comment.get("owner") or comment.get("replies") or comment.get("parent_comment_id"):
            continue  # the account's own comments, threads with replies, and replies
        text = write_reply(comment)
        if text:
            tt.call("POST", "business/comment/reply/create/", body={
                "video_id": video_id, "comment_id": comment["comment_id"], "text": text,  # up to 1,200 characters
            })


def reply_for(comment):
    if "price" in (comment.get("text") or "").lower():
        return f"Hi {comment.get('display_name') or 'there'}, the price list is pinned on our profile."
    return None  # leave the rest to a person


reply_to_new_comments(tt, "<ITEM_ID>", reply_for)

// Node.js
async function replyToNewComments(tt, videoId, writeReply) {
  const page = await tt.call("GET", "business/comment/list/", {
    params: { video_id: videoId, status: "PUBLIC", sort_field: "create_time", sort_order: "desc", max_count: 30 },
  });
  for (const comment of page.comments ?? []) {
    if (comment.owner || comment.replies || comment.parent_comment_id) continue; // own, already replied to, or a reply
    const text = writeReply(comment);
    if (text) {
      await tt.call("POST", "business/comment/reply/create/", {
        body: { video_id: videoId, comment_id: comment.comment_id, text }, // up to 1,200 characters
      });
    }
  }
}

function replyFor(comment) {
  if ((comment.text || "").toLowerCase().includes("price")) {
    return "Hi " + (comment.display_name || "there") + ", the price list is pinned on our profile.";
  }
  return null; // leave the rest to a person
}

replyToNewComments(tt, "<ITEM_ID>", replyFor).catch(console.error);

如何讀取帳戶的數據分析?

以 GET 呼叫 /business/get/,在 fields 中指定欄位名稱,並搭配最長 60 天的 UTC 日期範圍。followers_count 會出現兩次:data 頂層為目前總數,metrics 內每天也有一個當日總數,並與當日的 video_views、profile_views、likes、comments 及 shares 並列。範例以昨天為結束日期,因為每日數字會延遲 24 至 48 小時才會出現:

Daily account metrics for the last 7 days: Python, then Node.js
# Python
from datetime import datetime, timedelta, timezone


def daily_insights(tt, days=7):
    yesterday = datetime.now(timezone.utc).date() - timedelta(days=1)  # counts arrive 24 to 48 h late
    data = tt.call("GET", "business/get/", params={
        "fields": ["followers_count", "video_views", "profile_views", "likes", "comments", "shares"],
        "start_date": (yesterday - timedelta(days=days - 1)).isoformat(),  # UTC, up to 60 days back
        "end_date": yesterday.isoformat(),
    })
    print("Followers now:", data.get("followers_count"))
    for day in data.get("metrics", []):
        print(day["date"], day.get("followers_count"), day.get("video_views"), day.get("likes"))


daily_insights(tt)

// Node.js
async function dailyInsights(tt, days = 7) {
  const utcDay = (daysAgo) => new Date(Date.now() - daysAgo * 86400000).toISOString().slice(0, 10);
  const data = await tt.call("GET", "business/get/", {
    params: {
      fields: ["followers_count", "video_views", "profile_views", "likes", "comments", "shares"],
      start_date: utcDay(days), // UTC, up to 60 days back
      end_date: utcDay(1), // counts arrive 24 to 48 h late
    },
  });
  console.log("Followers now:", data.followers_count);
  for (const day of data.metrics ?? []) console.log(day.date, day.followers_count, day.video_views, day.likes);
}

dailyInsights(tt).catch(console.error);

如何驗證 webhook 簽名?

以應用程式密鑰為金鑰,重新計算 t 值、句號及原始主體的 HMAC-SHA256,以常數時間與 s 比較,並檢查 t 是否為近期時間。在任何解析動作之前,先以位元組讀取主體,立即回覆 200,驗證失敗時記錄 x-tt-logid。Python 使用 Flask,Node.js 則使用內建的 http 模組:

Receive a signed TikTok webhook: Python with Flask, then Node.js
# Python
import hashlib
import hmac
import json
import os
import time
from queue import Queue

from flask import Flask, request

app = Flask(__name__)
events = Queue()


def signature_ok(raw, header, secret, max_age=300):
    fields = {}
    for part in (header or "").split(","):
        key, sep, value = part.strip().partition("=")
        if sep:
            fields[key] = value
    t, s = fields.get("t", ""), fields.get("s", "").lower()
    if not t.isdigit() or len(s) != 64:
        return False
    expected = hmac.new(secret.encode(), t.encode() + b"." + raw, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, s) and abs(time.time() - int(t)) <= max_age


@app.post("/tiktok/webhook")
def tiktok_webhook():
    raw = request.get_data()  # the bytes TikTok signed, before any JSON parsing
    if not signature_ok(raw, request.headers.get("Tiktok-Signature"), os.environ["TIKTOK_APP_SECRET"]):
        app.logger.warning("Bad signature, x-tt-logid %s", request.headers.get("X-Tt-Logid"))
        return "", 401
    events.put(json.loads(raw))  # its content field is itself a JSON string: work on it elsewhere
    return "", 200

// Node.js
const { createServer } = require("node:http");
const { createHmac, timingSafeEqual } = require("node:crypto");

function signatureOk(raw, header, secret, maxAgeSec = 300) {
  const fields = {};
  for (const part of String(header ?? "").split(",")) {
    const i = part.indexOf("=");
    if (i > 0) fields[part.slice(0, i).trim()] = part.slice(i + 1).trim();
  }
  if (!/^\d+$/.test(fields.t ?? "") || !/^[0-9a-f]{64}$/i.test(fields.s ?? "")) return false;
  const expected = createHmac("sha256", secret).update(fields.t + ".").update(raw).digest();
  const fresh = Math.abs(Date.now() / 1000 - Number(fields.t)) <= maxAgeSec;
  return timingSafeEqual(expected, Buffer.from(fields.s, "hex")) && fresh;
}

const inbox = [];
createServer((req, res) => {
  if (req.method !== "POST" || req.url !== "/tiktok/webhook") return res.writeHead(404).end();
  const chunks = [];
  req.on("data", (chunk) => chunks.push(chunk));
  req.on("end", () => {
    const raw = Buffer.concat(chunks); // the bytes TikTok signed
    if (!signatureOk(raw, req.headers["tiktok-signature"], process.env.TIKTOK_APP_SECRET)) {
      console.warn("Bad signature, x-tt-logid", req.headers["x-tt-logid"]);
      return res.writeHead(401).end();
    }
    res.writeHead(200).end(); // answer first: TikTok retries anything but a 200 for up to 72 hours
    inbox.push(JSON.parse(raw.toString("utf8")));
  });
}).listen(3000);

如何透過 easyCoexistence 執行相同工作?

以工具呼叫的形式,由 Claude、ChatGPT 或其他 MCP 客戶端執行,這些客戶端須連接至 https://easycoexistence.com/api/mcp,並從 list_social_accounts 取得各次呼叫所需的 account_id。easyCoexistence 會透過其已驗證的 URL 前綴,把您的媒體連結送交 TikTok,並追蹤每則貼文直至 TikTok 完成或失敗,同時更新存取權杖;若呼叫被拒絕,則會回傳 TikTok 的 code 與 message:

The six jobs as MCP tool calls
// Publish a video by URL, then see where it stands
publish_tiktok_post { "account_id": "<ACCOUNT_ID>", "video_url": "https://media.example.com/tiktok/launch.mp4", "caption": "Our spring menu is live #food" }
get_tiktok_publish_status { "account_id": "<ACCOUNT_ID>", "share_id": "<SHARE_ID>" }

// Post photos
publish_tiktok_post { "account_id": "<ACCOUNT_ID>", "image_urls": ["https://media.example.com/menu/1.jpg", "https://media.example.com/menu/2.jpg"], "title": "Spring menu", "caption": "Four new dishes, from Friday #food" }

// List videos
list_social_posts { "account_id": "<ACCOUNT_ID>", "limit": 20 }

// Read comments and reply in public
list_social_comments { "account_id": "<ACCOUNT_ID>", "post_id": "<ITEM_ID>" }
reply_to_comment { "account_id": "<ACCOUNT_ID>", "post_id": "<ITEM_ID>", "comment_id": "<COMMENT_ID>", "text": "The price list is pinned on our profile." }

// Account insights
get_social_insights { "account_id": "<ACCOUNT_ID>", "metrics": ["followers_count", "video_views", "likes"], "params": { "start_date": "2026-10-26", "end_date": "2026-11-01" } }

// Comment events, signed by easyCoexistence, at your endpoint
set_social_webhook_destination { "account_id": "<ACCOUNT_ID>", "url": "https://hooks.example.com/tiktok/" }

您自己的程式如何使用連接到 easyCoexistence 的帳戶?

每項工作前,透過 Partner API 取得帳戶憑證,再傳入同一客戶端。使用您的 ec_live_ 金鑰呼叫 GET /channels/{id}?credentials=1,會回傳 api_base、business_id,以及目前的 access_token 與 token_expires_at;若頻道需要重新連接,則回傳空值的權杖並附註說明。讀取、回覆及數據分析均由您自己的程式執行,而發布則透過 POST /channels/{id}/posts 或 publish_tiktok_post 進行,它們會經由已驗證的前綴傳送媒體:

A current token from the Partner API, into the same client: Python, then Node.js
# Python
def tiktok_for(channel_id):
    res = requests.get(f"https://easycoexistence.com/api/v1/channels/{channel_id}", params={"credentials": "1"},
                       headers={"Authorization": f"Bearer {os.environ['EC_API_KEY']}"}, timeout=30)
    res.raise_for_status()
    creds = res.json()["credentials"]
    if not creds.get("access_token"):
        raise RuntimeError(creds.get("note"))  # the channel needs reconnecting
    return TikTok(creds["access_token"], creds["business_id"])


print(recent_videos(tiktok_for("<CHANNEL_ID>"), 20))

// Node.js
async function tiktokFor(channelId) {
  const res = await fetch("https://easycoexistence.com/api/v1/channels/" + channelId + "?credentials=1", {
    headers: { Authorization: "Bearer " + process.env.EC_API_KEY },
  });
  if (!res.ok) throw new Error("HTTP " + res.status + " from easyCoexistence");
  const { credentials } = await res.json();
  if (!credentials.access_token) throw new Error(credentials.note); // the channel needs reconnecting
  return new TikTok(credentials.access_token, credentials.business_id);
}

tiktokFor("<CHANNEL_ID>").then((account) => recentVideos(account, 20)).then(console.log, console.error);

常見錯誤

  • 讀取數據而不檢查 code。回應可能是 HTTP 200、code 為 40002,且完全沒有 data,因此欄位缺失往往代表程式略過了一個錯誤。
  • 省略結尾斜線。TikTok 的路徑以 / 結尾,其回傳代碼附錄指出,不帶斜線的 /tt_user/oauth2/refresh_token 會以 HTTP 404 page not found 結束。
  • 在 Node.js 中從 reply_list 取得回覆 ID。TikTok 的參考文件將 reply_list 的 comment_id 與 video_id 定義為數字,而 JSON.parse 可能會將其捨入;/business/comment/reply/list/ 則以字串回傳。
  • 以逗號分隔列表傳送 fields。API for Business 要求 JSON 文字,即 fields=["item_id","caption"],這不同於 developers.tiktok.com 的 Display API,後者使用 fields=open_id,union_id。
使用 EasyCoexistence 完成這項設定

每個連接每月 US$ 9 至 US$ 0.75,連接越多單價越低,首 3 天免費試用。

常見問題

TikTok 是否為 Accounts API 提供官方的 Python 或 Node.js SDK?

TikTok 的 API for Business SDK 提供 Python、JavaScript 及 Java 版本,但其端點清單涵蓋廣告、報告及 Business Center,沒有 /business/ 或 /tt_user/ 端點。

為何 TikTok 呼叫會回傳 HTTP 200 卻沒有 data?

TikTok 會在 HTTP 200 回應的 code 欄位中回報錯誤。請讀取 code 與 message:40002 為參數錯誤,40001 為缺少權限,40100 為受速率限制的呼叫。

這些範例需要哪些 Python 與 Node.js 版本?

Python 3.9 或以上版本,並需 requests,另需 Flask 以供 webhook 使用;Node.js 18 或以上版本,其內建的 fetch 與 node:crypto 可涵蓋其餘所需。

我可以在瀏覽器中呼叫 TikTok API 嗎?

請把呼叫留在您的伺服器上。TikTok 的權杖類型為 Bearer,任何持有人均可使用,而權杖端點需要您應用程式的 client_secret。

繼續閱讀

兩分鐘內連接您的第一個頻道。

無需等待平台審核。連接 WhatsApp、Instagram、TikTok 或其他頻道,然後請您的 AI 發佈貼文、回覆訊息或匯報數據,並看着它運作。

  • 免費試用 3 天
  • 隨時取消
  • 只用官方 API
  • 24/7 監察

驗證日期