EntrarComeçar teste grátis
easyCoexistence APIs oficiais

API do TikTok em Python e Node.js: exemplos que funcionam

A API for Business do TikTok funciona em Python ou Node.js com requisições HTTPS simples: envie cada chamada para https://business-api.tiktok.com/open_api/v1.3 com o token da conta no cabeçalho Access-Token e o open_id dela como business_id. O TikTok responde à maioria das chamadas com HTTP 200 e um campo code, sendo 0 em caso de sucesso; verifique-o e pause 5 minutos no código 40100.

O easyCoexistence oferece ao Claude, ao ChatGPT ou ao seu próprio código as mesmas tarefas do TikTok como ferramentas, de publish_tiktok_post e reply_to_comment até get_social_insights, e entrega aos seus scripts um token atual por get_social_credentials ou pela Partner API.

HTTP 200

Status da maioria das respostas do TikTok, inclusive erros; só um code 0 no corpo indica que a chamada funcionou.

40100

Código para chamada limitada: o TikTok pede uma pausa de 5 minutos após um limite por minuto, e até 00:00 UTC após um limite diário.

5xx

Erros de servidor, após os quais o TikTok sugere esperar cerca de 5 minutos antes de chamar de novo.

Final /

Os caminhos terminam com barra; o TikTok indica /tt_user/oauth2/refresh_token sem ela como causa de 404 page not found.

3 languages

Python, JavaScript e Java no SDK da API for Business do TikTok, cuja lista de endpoints não inclui nenhum endpoint /business/.

HMAC-SHA256

Assinatura no cabeçalho Tiktok-Signature de cada webhook, calculada sobre o timestamp, um ponto e o corpo, com a chave secreta do app.

O que cada chamada à API do TikTok precisa?

As mesmas cinco coisas, qualquer que seja a tarefa:

  • A URL base https://business-api.tiktok.com/open_api/v1.3, com um caminho que termina em barra, como /business/video/list/.
  • O token de acesso da conta em um cabeçalho Access-Token, renovado antes que suas 24 horas acabem.
  • business_id, o open_id da conta: na query string em GET, no corpo JSON em POST.
  • Parâmetros de lista e objeto em GET, como fields e filters, enviados como texto JSON: fields=["item_id","caption"].
  • Uma verificação de code na resposta, já que o TikTok envia erros como 40002 ou 40100 com HTTP 200 e dados apenas quando code é 0.

Como tratar o envelope de erro do TikTok em Python?

Com um pequeno cliente que coloca business_id onde cada método espera, devolve data quando code é 0 e lança um TikTokError nos demais casos. Ele repete uma chamada limitada após a pausa de 5 minutos do TikTok, já que 40100 significa que o TikTok recusou a chamada, e repete um 5xx apenas em GET, porque uma publicação que terminou em erro de servidor pode ter chegado ao TikTok. Precisa de requests, e os exemplos Python seguintes reutilizam o cliente:

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"])

Como tratar isso em Node.js?

O mesmo cliente sobre o fetch embutido no Node.js 18 e versões posteriores, sem nada para instalar. Ele codifica os parâmetros de lista como JSON em GET, coloca business_id no corpo em POST e mantém o code do TikTok no erro, para que quem chama distinga 40102 ou 40105, um problema de token, de 40001, uma permissão ausente:

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);

Como publicar um vídeo por URL e verificar seu status?

POST /business/video/publish/ com video_url e post_info, depois consulte /business/publish/status/ com o share_id como publish_id. O laço para em FAILED com o motivo do TikTok e, em PUBLISH_COMPLETE, continua esperando até que post_ids chegue, o que o TikTok diz poder levar até mais três minutos. O video_url precisa estar em um domínio ou prefixo de URL verificado para o seu app:

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);

Como publicar fotos?

Leia primeiro as configurações permitidas da conta e depois faça POST em /business/photo/publish/. Uma publicação de foto exige privacy_level, que deve ser um dos privacy_level_options de /business/video/settings/; quando comment_disabled é true ali, disable_comment também precisa ser true. O share_id retornado é acompanhado com a mesma função de espera de um vídeo:

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);

Como listar os vídeos de uma conta?

GET /business/video/list/ com os campos desejados, item_id entre eles, até 20 publicações por página, da mais nova para a mais antiga. Passe o cursor retornado, um timestamp UTC em milissegundos, enquanto has_more for true, e espere páginas curtas: as regras de confiança e segurança do TikTok podem retornar menos de max_count antes do fim da lista.

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);

Como ler comentários e respondê-los?

GET /business/comment/list/ com o item_id da publicação como video_id retorna até 30 comentários por página, e POST /business/comment/reply/create/ responde um deles publicamente com até 1.200 caracteres de texto. O exemplo responde a comentários públicos de primeiro nível que ainda não têm respostas, ignora os da própria conta e deixa o texto a cargo de uma função que você escreve, já que o TikTok pode ocultar comentários muito parecidos publicados em sequência como spam:

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);

Como ler os insights da conta?

GET /business/get/ com os nomes dos campos em fields e um intervalo de datas UTC de até 60 dias. followers_count aparece duas vezes: o total atual no topo de data e o total de cada dia dentro de metrics, junto com video_views, profile_views, likes, comments e shares daquele dia. O exemplo termina em ontem, já que as contagens diárias chegam com 24 a 48 horas de atraso:

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);

Como verificar a assinatura de um webhook?

Recalcule um HMAC-SHA256 do valor t, um ponto e o corpo bruto, com a chave secreta do app, compare-o com s em tempo constante e confirme que t é recente. Leia o corpo como bytes antes que qualquer coisa o interprete, responda 200 imediatamente e registre x-tt-logid quando uma verificação falhar. Flask para Python e o módulo http nativo para Node.js:

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);

Como executar as mesmas tarefas pelo easyCoexistence?

Como chamadas de ferramentas a partir do Claude, do ChatGPT ou de outro cliente MCP conectado a https://easycoexistence.com/api/mcp, cada uma recebendo o account_id de list_social_accounts. O easyCoexistence envia seus links de mídia ao TikTok pelo prefixo de URL verificado dele, acompanha cada publicação até que o TikTok a conclua ou falhe e renova o token, enquanto uma chamada recusada volta com o code e a message do TikTok:

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/" }

Como o seu próprio código usa uma conta conectada ao easyCoexistence?

Busque as credenciais da conta em cada tarefa pela Partner API e passe-as ao mesmo cliente. GET /channels/{id}?credentials=1 com sua chave ec_live_ retorna api_base, business_id e um access_token atual com token_expires_at, ou um token nulo com uma nota quando o canal precisa ser reconectado. Leituras, respostas e insights passam então a rodar no seu código, enquanto as publicações seguem por POST /channels/{id}/posts ou publish_tiktok_post, que roteiam a mídia pelo prefixo verificado:

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);

Erros comuns

  • Ler dados sem verificar o code. Uma resposta pode trazer HTTP 200, code 40002 e nenhum dado, então um campo ausente costuma ser um erro que o código ignorou.
  • Omitir a barra final. Os caminhos do TikTok terminam em /, e o apêndice de códigos de retorno dele indica /tt_user/oauth2/refresh_token, sem a barra, como uma chamada que termina em HTTP 404 page not found.
  • Obter IDs de respostas de reply_list no Node.js. A referência do TikTok tipa comment_id e video_id de reply_list como números, que JSON.parse pode arredondar; /business/comment/reply/list/ os devolve como strings.
  • Enviar fields como lista separada por vírgulas. A API for Business quer texto JSON, fields=["item_id","caption"], diferentemente da Display API em developers.tiktok.com, que aceita fields=open_id,union_id.
Fazendo isso com o EasyCoexistence

De US$ 9 a US$ 0.75 por conexão por mês, caindo conforme você adiciona conexões, com os primeiros 3 dias grátis.

O easyCoexistence é uma API e um servidor MCP multicanal que conecta agentes de IA, como o Claude e o ChatGPT, ao WhatsApp, Instagram, TikTok, Facebook e mais. No WhatsApp, ele usa o Coexistence: a empresa continua usando o número no app WhatsApp Business enquanto a IA trabalha pela API oficial da Meta.

Perguntas frequentes

O TikTok tem um SDK oficial em Python ou Node.js para a Accounts API?

O SDK da API for Business do TikTok existe em Python, JavaScript e Java, mas a lista de endpoints cobre anúncios, relatórios e Business Center, sem nenhum endpoint /business/ ou /tt_user/.

Por que uma chamada ao TikTok retorna HTTP 200 sem dados?

O TikTok informa erros no campo code de uma resposta HTTP 200. Leia code e message: 40002 é um erro de parâmetro, 40001 é uma permissão ausente e 40100 é uma chamada limitada.

Quais versões de Python e Node.js esses exemplos exigem?

Python 3.9 ou posterior com requests, mais Flask para o webhook, e Node.js 18 ou posterior, cujos fetch e node:crypto embutidos cobrem o restante.

Posso chamar a API do TikTok a partir do navegador?

Mantenha as chamadas no seu servidor. O tipo de token do TikTok é Bearer, utilizável por quem o possuir, e os endpoints de token exigem o client_secret do seu app.

Continue lendo

Conecte seu primeiro canal em dois minutos.

Sem esperar aprovação das plataformas. Conecte o WhatsApp, o Instagram, o TikTok ou outro canal, peça para a sua IA publicar, responder ou trazer os números, e veja funcionando.

  • 3 dias grátis
  • Cancele quando quiser
  • Só APIs oficiais
  • Monitorado 24/7

Verificado em