Python සහ Node.js හි TikTok API: ක්රියාත්මක උදාහරණ
TikTok හි API for Business Python හෝ Node.js වලින් සරල HTTPS request වලින් ක්රියා කරයි: සෑම call එකක්ම https://business-api.tiktok.com/open_api/v1.3 වෙත යවන්න, ගිණුමේ token එක Access-Token header එකෙහි ද, එහි open_id business_id ලෙසද දෙන්න. TikTok බොහෝ call වලට HTTP 200 සමඟ code field එකක් ලබා දෙයි, සාර්ථක වූ විට 0; එය පරීක්ෂා කර 40100 ලැබුණු විට මිනිත්තු 5ක් රැඳී සිටින්න.
easyCoexistence Claude, ChatGPT හෝ ඔබේම code එකට එම TikTok කාර්යයන් tools ලෙස ලබා දෙයි, publish_tiktok_post සහ reply_to_comment සිට get_social_insights දක්වා, සහ get_social_credentials හෝ Partner API හරහා ඔබේ scripts වලට වර්තමාන token එකක් ලබා දෙයි.
බොහෝ TikTok පිළිතුරුවල HTTP status එක, දෝෂ ඇතුළුව; body එකේ code 0 පමණක් call එක සාර්ථක වූ බව අර්ථ දක්වයි.
සීමා ඉක්මවූ call සඳහා code: එක් මිනිත්තු සීමාවකට පසු TikTok මිනිත්තු 5ක විරාමයක් ඉල්ලයි, දෛනික සීමාවකට පසු UTC 00:00 දක්වා.
server එකේ දෝෂ, ඉන් පසු TikTok නැවත call කිරීමට පෙර විනාඩි 5ක් පමණ බලා සිටින ලෙස යෝජනා කරයි.
Paths අවසානයේ slash තිබිය යුතුය; TikTok /tt_user/oauth2/refresh_token (slash නැතිව) 404 page not found ඇතිවීමට හේතුවක් ලෙස ලියා ඇත.
TikTok හි API for Business SDK හි Python, JavaScript සහ Java ඇත; එහි endpoint ලැයිස්තුවේ /business/ endpoint එකක් නැත.
සෑම webhook එකකම Tiktok-Signature header එකේ signature එක, timestamp, තිත (.) සහ body මත ගණනය කර, යෙදුමේ secret සමඟ යතුරු කර ඇත.
එක TikTok API call එකකට අවශ්ය වන්නේ කුමක්ද?
කාර්යය කුමක් වුවත්, එකම දේවල් පහක්:
- මූලික URL එක https://business-api.tiktok.com/
open_api/v1.3, සහ /business/video/list/ වැනි slash වලින් අවසන් වන path එකක්. - ගිණුමේ access token එක Access-Token header එකෙහි, පැය 24 අවසන් වීමට පෙර අලුත් කරන ලද.
business_id, එනම් ගිණුමේopen_id: GET හි query string එකේ, POST හි JSON body එකේ.- GET හි list සහ object පරාමිතීන්, fields සහ filters වැනි, JSON text ලෙස යවන්න: fields=["
item_id","caption"]. - පිළිතුරේ code පරීක්ෂා කරන්න, මන්ද TikTok 40002 හෝ 40100 වැනි දෝෂ HTTP 200 සමඟ යවයි, data එක ලැබෙන්නේ code 0 වූ විට පමණි.
Python හි TikTok දෝෂ envelope එක කෙසේ හසුරුවන්නද?
කුඩා client එකක් මගින්, එක් එක් method එක බලාපොරොත්තු වන තැන business_id තබමින්, code 0 නම් data ලබා දී, එසේ නොවේ නම් TikTokError එකක් මතු කරයි. සීමා ඉක්මවූ call එක TikTok හි මිනිත්තු 5ක විරාමයෙන් පසු නැවත යවයි, මන්ද 40100 යනු TikTok call එක ප්රතික්ෂේප කළ බවයි, සහ 5xx එක GET සඳහා පමණක් නැවත යවයි, මන්ද server එකේ දෝෂයකින් අවසන් වූ publish එක තවමත් TikTok වෙත ළඟා වී තිබිය හැක. requests අවශ්යයි, පසු Python උදාහරණ මෙය නැවත භාවිතා කරයි:
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 හි එය කෙසේ හසුරුවන්නද?
එම client එක Node.js 18 සහ ඊට පසු වලින් ඇති built-in fetch මත, ස්ථාපනය කිරීමට කිසිවක් නැතිව. එය GET සඳහා list පරාමිතීන් JSON ලෙස encode කරයි, POST සඳහා business_id body එකට දමයි, සහ දෝෂයක TikTok හි code එක තබා ගනී, එවිට call කරන්නන්ට 40102 හෝ 40105 (token ගැටලුවක්) සහ 40001 (අවසරය නොමැති වීම) අතර වෙනස හඳුනාගත හැක:
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 මගින් පළ කර එහි status එක කෙසේ පරීක්ෂා කරන්නද?
POST /business/video/publish/ එකට video_url සහ post_info යවන්න, ඉන්පසු /business/publish/status/ එක publish_id ලෙස share_id සමඟ poll කරන්න. FAILED නම් TikTok හේතුව සමඟ loop එක නවතී, PUBLISH_COMPLETE නම් post_ids පැමිණෙන තෙක් බලා සිටී, මෙයට තවත් මිනිත්තු තුනක් ගත හැකි බව TikTok කියයි. video_url එක ඔබේ යෙදුම සඳහා සත්යාපනය කළ domain හෝ URL prefix එකක තිබිය යුතුය:
# 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 එක video සඳහා වූ එම wait function එකෙන් අනුගමනය කරයි:
# 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/ ඔබට අවශ්ය fields සමඟ, අතර item_id, නව පළ කිරීම් වලින් පිටුවකට 20ක් දක්වා. ලැබෙන cursor එක, මිලි තත්පරවලින් UTC timestamp එකක්, has_more true වන තෙක් යවන්න, සහ කෙටි පිටු බලාපොරොත්තු වන්න: TikTok හි විශ්වාසනීයත්ව හා ආරක්ෂණ රීති නිසා ලැයිස්තුව අවසන් වීමට පෙර max_count ට වඩා අඩු ප්රතිඵල ලැබිය හැක.
# 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/ video_id ලෙස පළ කිරීමේ item_id සමඟ, පිටුවකට අදහස් 30ක් දක්වා ලබා දෙයි, සහ POST /business/comment/reply/create/ එය ප්රසිද්ධියේ, අක්ෂර 1,200ක් දක්වා පෙළ සමඟ පිළිතුරු දෙයි. උදාහරණය පිළිතුරු නොමැති, ප්රසිද්ධ top-level අදහස් වලට පමණක් පිළිතුරු දෙයි, ගිණුමේම අදහස් මඟ හරියි, සහ පෙළ ඔබ ලියන function එකකට භාර දෙයි, මන්ද ආසන්න වශයෙන් සමාන අදහස් වේගයෙන් පළ වූ විට TikTok ඒවා spam ලෙස සඟවා ඇත:
# 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);ගිණුමේ insights කියවන්නේ කෙසේද?
GET /business/get/ fields තුළ field නම් සමඟ සහ UTC දින පරාසයක් දින 60ක් දක්වා. followers_count දෙවරක් පැමිණේ: data හි ඉහළ ඇති වර්තමාන මුළු එකතුව, සහ metrics තුළ එක් එක් දිනය සඳහා එම දිනයේ video_views, profile_views, likes, comments සහ shares අසල ඇති මුළු එකතුව. උදාහරණය ඊයේ දක්වා අවසන් වේ, මන්ද දෛනික ගණන් පැය 24 සිට 48 දක්වා ප්රමාදයෙන් ලැබේ:
# 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 signature එක කෙසේ තහවුරු කරන්නද?
t අගයේ, තිත සහ raw body එකේ HMAC-SHA256 නැවත ගණනය කර, යෙදුමේ secret සමඟ යතුරු කර, s සමඟ constant time හි සංසන්දනය කර, t අලුත් දැයි පරීක්ෂා කරන්න. කිසිවක් parse කිරීමට පෙර body එක bytes ලෙස කියවන්න, වහාම 200 පිළිතුරු දෙන්න, සහ පරීක්ෂාව අසාර්ථක වූ විට x-tt-logid ලොග් කරන්න. Python සඳහා Flask, Node.js සඳහා built-in http module එක:
# 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 හරහා කෙසේ ක්රියාත්මක කරන්නද?
https://easycoexistence.com/api/mcp වෙත සම්බන්ධ වූ Claude, ChatGPT හෝ වෙනත් MCP client එකෙන් tool calls ලෙස, එක් එක් call එක list_social_accounts වෙතින් account_id ගනී. easyCoexistence ඔබේ media links TikTok වෙත එහි තමන්ගේ සත්යාපනය කළ URL prefix හරහා යවයි, TikTok සම්පූර්ණ හෝ අසාර්ථක කරන තෙක් එක් එක් පළ කිරීම අනුගමනය කරයි, සහ token එක අලුත් කරයි, ප්රතික්ෂේප කළ call එකක් TikTok හි code සහ පණිවිඩය සමඟ ආපසු ලැබේ:
// 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/" }ඔබේම code එක easyCoexistence හි සම්බන්ධ කළ ගිණුමක් භාවිතා කරන්නේ කෙසේද?
එක් එක් කාර්යය සඳහා Partner API වෙතින් ගිණුමේ credentials ලබාගෙන, එම client එකට යවන්න. ec_live_ යතුර සමඟ GET /channels/{id}?credentials=1 මගින් api_base, business_id සහ token_expires_at සමඟ වර්තමාන access_token එක ලබා දෙයි, නැතහොත් channel එකට නැවත සම්බන්ධ කිරීම අවශ්ය නම් note එකක් සමඟ null token එකක්. කියවීම්, පිළිතුරු සහ insights ඔබේම code එකෙන් ක්රියා කරයි, පළ කිරීම් POST /channels/{id}/posts හෝ publish_tiktok_post හරහා යයි, ඒවා සත්යාපනය කළ prefix හරහා media මෙහෙයවයි:
# 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 කිසිවක් නොමැතිව ලැබිය හැක, එබැවින් නැතිවූ field එකක් බොහෝ විට code එක මඟ හැරි දෝෂයකි.
- අවසාන slash එක අතහැරීම. TikTok හි paths / වලින් අවසන් වන අතර, එහි return code අනුබද්ධය හි /tt_user/oauth2/refresh_token, slash නැතිව, HTTP 404 page not found සමඟ අවසන් වන call එකක් ලෙස දක්වයි.
- Node.js හි reply_list වෙතින් reply IDs ගැනීම. TikTok හි reference reply_list හි comment_id සහ video_id සංඛ්යා ලෙස සටහන් කරයි, ඒවා JSON.parse මඟින් වටකර විය හැක; /business/comment/reply/list/ ඒවා string ලෙස ලබා දෙයි.
- fields කොමා-ලැයිස්තුවක් ලෙස යැවීම. API for Business හට JSON text අවශ්යයි, fields=["item_id","caption"], developers.tiktok.com හි Display API එක මෙන් නොව, එය fields=open_id,union_id ගනී.
සම්බන්ධතාවයකට මාසිකව US$ 9 සිට US$ 0.75 දක්වා, සම්බන්ධතා එකතු කරන විට අඩු වේ, පළමු දින 3 සඳහා නොමිලේ.
නිතර අසන ප්රශ්න
TikTok හට Accounts API සඳහා නිල Python හෝ Node.js SDK එකක් තිබේද?
TikTok හි API for Business SDK එක Python, JavaScript සහ Java වලින් පැමිණේ, නමුත් එහි endpoint ලැයිස්තුව ads, reporting සහ Business Center ආවරණය කරයි, /business/ හෝ /tt_user/ endpoint එකක් නැතිව.
TikTok call එකක් දත්ත නැතිව HTTP 200 ආපසු දෙන්නේ ඇයි?
TikTok දෝෂ HTTP 200 පිළිතුරක code field එකේ වාර්තා කරයි. code සහ පණිවිඩය කියවන්න: 40002 පරාමිති දෝෂයකි, 40001 අවසරය නොමැති වීම සහ 40100 සීමා ඉක්මවූ call එකකි.
මෙම උදාහරණවලට කුමන Python සහ Node.js අනුවාද අවශ්යද?
requests සමඟ Python 3.9 හෝ ඊට පසු, webhook සඳහා Flask ද, සහ Node.js 18 හෝ ඊට පසු, එහි built-in fetch සහ node:crypto ඉතිරි දේ ආවරණය කරයි.
browser එකෙන් TikTok API call කළ හැකිද?
Calls ඔබේ server එකේම තබන්න. TikTok token වර්ගය Bearer වන අතර එය ඇත්තේ ඇති ඕනෑම කෙනෙකුට භාවිතා කළ හැක, සහ token endpoints වලට ඔබේ යෙදුමේ client_secret අවශ්යයි.
තවදුරටත් කියවන්න
ඔබේ පළමු channel එක මිනිත්තු දෙකකින් සම්බන්ධ කරන්න.
වේදිකා සමාලෝචන සඳහා බලා සිටීමට අවශ්ය නැත. WhatsApp, Instagram, TikTok හෝ වෙනත් channel එකක් සම්බන්ධ කර, පසුව ඔබේ AI හට පළ කිරීමට, ප්රතිචාර දැක්වීමට හෝ වාර්තා කිරීමට පවසා එය වැඩ කරන ආකාරය බලන්න.
- දින 3ක් නොමිලේ
- ඕනෑම වේලාවක අවලංගු කරන්න
- නිල API පමණි
- 24/7 නිරීක්ෂණය කෙරේ
සත්යාපනය කළේ