AccediInizia la prova gratuita
easyCoexistence API ufficiali

TikTok API in Python e Node.js: esempi funzionanti

L'API for Business di TikTok funziona da Python o Node.js con semplici richieste HTTPS: ogni chiamata va a https://business-api.tiktok.com/open_api/v1.3 con il token dell'account nell'header Access-Token e il suo open_id come business_id. TikTok risponde alla maggior parte delle chiamate con HTTP 200 e un campo code, pari a 0 in caso di successo: verificalo e attendi 5 minuti in caso di 40100.

easyCoexistence offre a Claude, ChatGPT o al tuo codice le stesse operazioni TikTok come strumenti, da publish_tiktok_post e reply_to_comment fino a get_social_insights, e consegna agli script un token attuale tramite get_social_credentials o la Partner API.

HTTP 200

Stato della maggior parte delle risposte di TikTok, errori compresi: solo un code pari a 0 nel corpo indica che la chiamata è riuscita.

40100

Codice per una chiamata limitata: TikTok chiede una pausa di 5 minuti dopo un limite al minuto, e fino alle 00:00 UTC dopo uno giornaliero.

5xx

Errori del server, dopo i quali TikTok suggerisce di attendere circa 5 minuti prima di richiamare.

Final /

I percorsi terminano con una barra; TikTok indica /tt_user/oauth2/refresh_token senza di essa come causa di 404 page not found.

3 languages

Python, JavaScript e Java nell'SDK API for Business di TikTok, il cui elenco di endpoint non include alcun endpoint /business/.

HMAC-SHA256

Firma nell'header Tiktok-Signature di ogni webhook, calcolata su timestamp, un punto e il corpo, con il segreto dell'app come chiave.

Di cosa ha bisogno ogni chiamata all'API di TikTok?

Le stesse cinque cose, qualunque sia l'operazione:

  • L'URL base https://business-api.tiktok.com/open_api/v1.3, con un percorso che termina con una barra, come /business/video/list/.
  • Il token di accesso dell'account nell'header Access-Token, rinnovato prima che scadano le sue 24 ore.
  • business_id, cioè l'open_id dell'account: nella stringa di query nelle GET, nel corpo JSON nelle POST.
  • Parametri di elenco e di oggetto nelle GET, come fields e filters, inviati come testo JSON: fields=["item_id","caption"].
  • Un controllo del code nella risposta, perché TikTok invia errori come 40002 o 40100 con HTTP 200 e i dati solo quando code è 0.

Come gestisci la struttura degli errori di TikTok in Python?

Con un piccolo client che inserisce business_id dove ogni metodo se lo aspetta, restituisce i dati quando code è 0 e solleva un TikTokError altrimenti. Ripete una chiamata limitata dopo la pausa di 5 minuti di TikTok, perché 40100 significa che TikTok ha rifiutato la chiamata, e ripete un 5xx solo nelle GET, perché una pubblicazione conclusasi con un errore del server potrebbe comunque essere arrivata a TikTok. Richiede requests, e i successivi esempi Python lo riutilizzano:

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

Come lo gestisci in Node.js?

Lo stesso client con fetch integrato in Node.js 18 e versioni successive, senza nulla da installare. Codifica i parametri di elenco come JSON per le GET, inserisce business_id nel corpo per le POST e mantiene il code di TikTok nell'errore, così i chiamanti possono distinguere 40102 o 40105, un problema di token, da 40001, un permesso mancante:

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

Come pubblichi un video tramite URL e ne controlli lo stato?

POST /business/video/publish/ con video_url e post_info, poi interroghi /business/publish/status/ con lo share_id come publish_id. Il ciclo si interrompe su FAILED con il motivo di TikTok e, su PUBLISH_COMPLETE, continua ad attendere finché non arriva post_ids, cosa che TikTok dice possa richiedere fino a tre minuti in più. Il video_url deve trovarsi su un dominio o un prefisso URL verificato per la tua 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);

Come pubblichi le foto?

Leggi prima le impostazioni consentite dell'account, poi fai POST a /business/photo/publish/. Un post di foto richiede privacy_level, che deve essere uno dei privacy_level_options da /business/video/settings/, e se lì comment_disabled è true, anche disable_comment deve essere true. Lo share_id restituito si segue con la stessa funzione di attesa usata per un video:

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

Come elenchi i video di un account?

GET /business/video/list/ con i campi che ti servono, item_id tra questi, fino a 20 post per pagina, dal più recente. Passa il cursor restituito, un timestamp UTC in millisecondi, finché has_more è true, e aspettati pagine più corte del previsto: le regole di moderazione di TikTok possono restituire meno di max_count prima che l'elenco finisca.

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

Come leggi i commenti e vi rispondi?

GET /business/comment/list/ con l'item_id del post come video_id restituisce fino a 30 commenti per pagina, e POST /business/comment/reply/create/ risponde pubblicamente a uno di essi con fino a 1.200 caratteri di testo. L'esempio risponde ai commenti pubblici di primo livello che non hanno ancora risposte, salta quelli dell'account stesso e lascia il testo a una funzione che scrivi tu, perché TikTok può nascondere come spam commenti molto simili pubblicati a breve distanza:

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

Come leggi gli insight dell'account?

GET /business/get/ con i nomi dei campi in fields e un intervallo di date UTC fino a 60 giorni. followers_count compare due volte: il totale attuale in cima a data, e il totale di ciascun giorno dentro metrics, accanto a video_views, profile_views, likes, comments e shares di quel giorno. L'esempio finisce a ieri, perché i conteggi giornalieri arrivano con 24-48 ore di ritardo:

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

Come verifichi la firma di un webhook?

Ricalcola un HMAC-SHA256 del valore t, un punto e il corpo grezzo, con il segreto dell'app come chiave, confronta il risultato con s in tempo costante e verifica che t sia recente. Leggi il corpo come byte prima che qualsiasi parser lo elabori, rispondi subito con 200 e registra x-tt-logid quando un controllo fallisce. Flask per Python, e il modulo http integrato per 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);

Come esegui le stesse operazioni tramite easyCoexistence?

Come chiamate di strumenti da Claude, ChatGPT o un altro client MCP collegato a https://easycoexistence.com/api/mcp, ognuna con l'account_id preso da list_social_accounts. easyCoexistence invia i tuoi link multimediali a TikTok tramite il proprio prefisso URL verificato, segue ogni post finché TikTok non lo completa o non lo respinge, e rinnova il token, mentre una chiamata rifiutata torna con il code e il message di 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/" }

Come usa il tuo codice un account collegato a easyCoexistence?

Recupera le credenziali dell'account per ogni operazione dalla Partner API e passale allo stesso client. GET /channels/{id}?credentials=1 con la tua chiave ec_live_ restituisce api_base, business_id e un access_token attuale con token_expires_at, oppure un token null con una nota quando il canale va ricollegato. Letture, risposte e insight vengono eseguiti dal tuo codice, mentre i post passano da POST /channels/{id}/posts o da publish_tiktok_post, che instradano i media attraverso il prefisso verificato:

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

Errori comuni

  • Leggere i dati senza controllare il code. Una risposta può avere HTTP 200, code 40002 e nessun dato, quindi un campo mancante è spesso un errore che il codice ha ignorato.
  • Omettere la barra finale. I percorsi di TikTok terminano con /, e la sua appendice dei codici di ritorno indica /tt_user/oauth2/refresh_token, senza barra, come chiamata che termina con HTTP 404 page not found.
  • Prendere gli ID delle risposte da reply_list in Node.js. I tipi di riferimento di TikTok definiscono comment_id e video_id di reply_list come numeri, che JSON.parse può arrotondare; /business/comment/reply/list/ li restituisce come stringhe.
  • Inviare fields come elenco separato da virgole. L'API for Business vuole testo JSON, fields=["item_id","caption"], a differenza della Display API su developers.tiktok.com, che accetta fields=open_id,union_id.
Farlo con EasyCoexistence

Da US$ 9 a US$ 0,75 per connessione al mese, con prezzo che scende man mano che aggiungi connessioni, e con i primi 3 giorni di prova gratuita.

Domande frequenti

TikTok offre un SDK ufficiale per Python o Node.js per l'Accounts API?

L'SDK API for Business di TikTok è disponibile in Python, JavaScript e Java, ma il suo elenco di endpoint copre annunci, reportistica e Business Center, senza endpoint /business/ o /tt_user/.

Perché una chiamata TikTok restituisce HTTP 200 senza dati?

TikTok segnala gli errori nel campo code di una risposta HTTP 200. Leggi code e message: 40002 è un errore di parametro, 40001 un permesso mancante e 40100 una chiamata limitata.

Quali versioni di Python e Node.js richiedono questi esempi?

Python 3.9 o successiva con requests, più Flask per il webhook, e Node.js 18 o successiva, il cui fetch integrato e node:crypto coprono il resto.

Posso chiamare l'API TikTok dal browser?

Mantieni le chiamate sul tuo server. Il tipo di token di TikTok è Bearer, utilizzabile da chiunque lo detenga, e gli endpoint dei token richiedono il client_secret della tua app.

Continua a leggere

Collega il tuo primo canale in due minuti.

Nessuna revisione delle piattaforme da aspettare. Collega WhatsApp, Instagram, TikTok o un altro canale, poi chiedi alla tua AI di pubblicare, rispondere o fare un report, e guardala al lavoro.

  • 3 giorni gratis
  • Disdici quando vuoi
  • Solo API ufficiali
  • Monitorato 24/7

Verificato il