登录开始免费试用
easyCoexistence 官方 API

Python 与 Node.js 的 TikTok API:可运行示例

TikTok 的 API for Business 可以通过普通 HTTPS 请求在 Python 或 Node.js 中使用:每次调用都发送到 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 调用需要哪些内容?

无论执行哪项任务,都需要以下五样内容:

  • 基础 URL 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);

如何通过 URL 发布视频并检查其状态?

以 video_url 和 post_info 调用 POST /business/video/publish/,然后将 share_id 作为 publish_id,轮询 /business/publish/status/。若状态为 FAILED,循环停止并返回 TikTok 给出的原因;若状态为 PUBLISH_COMPLETE,则继续等待,直到出现 post_ids,TikTok 表示这最多可能还需要 3 分钟。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);

如何读取评论并回复?

以帖子的 item_id 作为 video_id 调用 GET /business/comment/list/,每页最多返回 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;如果该渠道需要重新连接,则返回 null 令牌并附带说明。读取、回复和数据洞察随后可直接在您自己的代码中运行,而发布则通过 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 却没有数据?

TikTok 在 HTTP 200 响应的 code 字段中报告错误。请同时读取 code 和 message:40002 表示参数错误,40001 表示缺少权限,40100 表示限流调用。

这些示例需要哪些 Python 和 Node.js 版本?

Python 3.9 或更高版本并安装 requests,Webhook 部分还需要 Flask;Node.js 18 或更高版本,其内置的 fetch 与 node:crypto 可满足其余需求。

我能否从浏览器调用 TikTok API?

请把调用放在您的服务器端。TikTok 的令牌类型为 Bearer,任何持有者都可以使用,而令牌端点需要您应用的 client_secret。

继续阅读

两分钟连接您的第一个渠道。

无需等待平台审核。连接 WhatsApp、Instagram、TikTok 或其他渠道,然后让您的 AI 发布、回复或生成报告,看它如何运作。

  • 免费试用 3 天
  • 随时取消
  • 仅使用官方 API
  • 全天候 24/7 监控

验证时间