लॉग इनमोफत ट्रायल सुरू करा
easyCoexistence अधिकृत एपीआय

TikTok एपीआय: Python आणि Node.js मध्ये कार्यरत उदाहरणे

Python किंवा Node.js वरून TikTok चा API for Business साध्या HTTPS विनंत्यांनी चालतो: प्रत्येक कॉल https://business-api.tiktok.com/open_api/v1.3 वर पाठवा, खात्याचा टोकन Access-Token हेडरमध्ये द्या आणि त्याचा open_id business_id म्हणून द्या. TikTok बहुतेक कॉलना HTTP 200 आणि code फील्डसह उत्तर देते, यश मिळाल्यास 0. म्हणून code तपासा आणि 40100 आल्यास 5 मिनिटे थांबा.

easyCoexistence Claude, ChatGPT किंवा तुमच्या स्वतःच्या कोडला त्याच TikTok कामे टूल म्हणून देते, publish_tiktok_post आणि reply_to_comment पासून get_social_insights पर्यंत, आणि get_social_credentials किंवा Partner API द्वारे तुमच्या स्क्रिप्ट्सना सध्याचे टोकन देते.

HTTP 200

बहुतेक TikTok उत्तरांची स्थिती, त्रुटींसह; बॉडीमधील code 0 हाच कॉल यशस्वी झाल्याचे दर्शवतो.

40100

मर्यादा ओलांडलेल्या कॉलसाठी कोड: प्रति मिनिट मर्यादेनंतर TikTok 5 मिनिटांचा विराम मागते, आणि प्रति दिवस मर्यादेनंतर 00:00 UTC पर्यंत.

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

प्रत्येक वेबहुकच्या Tiktok-Signature हेडरमधील स्वाक्षरी timestamp, एक डॉट आणि बॉडी यावर मोजलेली असते, आणि ॲप सीक्रेट ही की वापरते.

प्रत्येक 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 सह पाठवते आणि data फक्त code 0 असतानाच देते.

Python मध्ये TikTok च्या त्रुटी-रचना कशी हाताळायची?

एक लहान क्लायंट लिहा जो प्रत्येक मेथड अपेक्षित ठिकाणी business_id ठेवतो, code 0 असल्यास data परत करतो आणि अन्यथा TikTokError उभी करतो. मर्यादा ओलांडलेला कॉल TikTok च्या 5 मिनिटांच्या विरामानंतर पुन्हा करतो, कारण 40100 म्हणजे TikTok ने कॉल नाकारला, आणि 5xx फक्त GET साठी पुन्हा करतो, कारण सर्व्हर त्रुटीने संपलेले प्रकाशन तरीही TikTok पर्यंत पोहोचले असू शकते. यासाठी requests लागते, आणि पुढची Python उदाहरणे हाच क्लायंट वापरतात:

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

import requests

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


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


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

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

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


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

Node.js मध्ये हे कसे हाताळायचे?

त्याच क्लायंटचा वापर, Node.js 18 आणि नंतरच्या आवृत्त्यांमधील बिल्ट-इन fetch वर, काहीही इन्स्टॉल न करता. तो GET साठी यादी पॅरामीटर JSON म्हणून एन्कोड करतो, POST साठी business_id बॉडीत ठेवतो, आणि त्रुटीवर TikTok चा code कायम ठेवतो, त्यामुळे कॉल करणारे 40102 किंवा 40105 (टोकनची समस्या) आणि 40001 (गहाळ परवानगी) यात फरक करू शकतात:

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

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

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

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

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

व्हिडिओ यूआरएलद्वारे प्रकाशित कसा करायचा आणि त्याची स्थिती कशी तपासायची?

video_url आणि post_info सह POST /business/video/publish/ करा, मग share_id ला publish_id म्हणून वापरून /business/publish/status/ ला पोल करा. लूप FAILED वर TikTok च्या कारणासह थांबतो, आणि PUBLISH_COMPLETE वर post_ids येईपर्यंत थांबत राहतो, जे TikTok म्हणते आणखी तीन मिनिटांपर्यंत लागू शकतात. video_url तुमच्या ॲपसाठी पडताळलेल्या डोमेन किंवा यूआरएल प्रीफिक्सवर असणे आवश्यक आहे:

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/ सह तुम्हाला हवी असलेली fields द्या, त्यात item_id असावा, नवीनपासून सुरुवात करून प्रति पानावर 20 पोस्टपर्यंत. परत मिळालेला cursor (मिलिसेकंदांमधील UTC टाइमस्टॅम्प) पाठवा, जोपर्यंत has_more true आहे, आणि लहान पानांची अपेक्षा ठेवा: TikTok च्या ट्रस्ट आणि सेफ्टी नियमांमुळे यादी संपण्यापूर्वी max_count पेक्षा कमी परत येऊ शकतात.

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


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

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

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

कमेंट्स कसे वाचायचे आणि त्यांना उत्तर कसे द्यायचे?

GET /business/comment/list/ सह video_id म्हणून पोस्टचा item_id दिल्यास प्रति पानावर 30 कमेंट्सपर्यंत मिळतात, आणि POST /business/comment/reply/create/ एकाला सार्वजनिकपणे 1,200 अक्षरांपर्यंतच्या मजकुरासह उत्तर देते. उदाहरण अशा सर्वोच्च-स्तरीय सार्वजनिक कमेंट्सना उत्तर देते ज्यांना अजून उत्तरे नाहीत, खात्याच्या स्वतःच्या कमेंट्स वगळते, आणि शब्दरचना तुम्ही लिहिलेल्या फंक्शनवर सोडते, कारण जवळपास सारख्या कमेंट्स जवळ जवळ पोस्ट झाल्यास TikTok त्यांना स्पॅम म्हणून लपवू शकतो:

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


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


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

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

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

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

खात्याची इनसाइट्स कशी वाचायची?

GET /business/get/ सह fields मधील नावे आणि 60 दिवसांपर्यंतची UTC तारीख श्रेणी. followers_count दोनदा येतो: data च्या वरच्या भागात सध्याची एकूण संख्या, आणि metrics च्या आत प्रत्येक दिवसाची एकूण संख्या, त्या दिवसाच्या video_views, profile_views, likes, comments आणि shares सोबत. उदाहरण कालपर्यंत संपते, कारण दैनिक आकडे 24 ते 48 तास उशिरा येतात:

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


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


daily_insights(tt)

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

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

वेबहुक स्वाक्षरीची पडताळणी कशी करायची?

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 द्वारे त्याच कामे कशी चालवायची?

https://easycoexistence.com/api/mcp वर जोडलेल्या Claude, ChatGPT किंवा दुसऱ्या MCP क्लायंटकडून टूल कॉल म्हणून, प्रत्येक list_social_accounts मधून account_id घेऊन. easyCoexistence तुमचे मीडिया लिंक्स स्वतःच्या पडताळलेल्या यूआरएल प्रीफिक्सद्वारे 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 आणि token_expires_at सह सध्याचा access_token परत करते, किंवा चॅनेलला पुन्हा जोडणे आवश्यक असल्यास note सह 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);

सामान्य चुका

  • कोड न तपासता डेटा वाचणे. उत्तर HTTP 200, code 40002 आणि अजिबात data न घेऊन येऊ शकते, त्यामुळे गहाळ फील्ड बहुतेक वेळा कोडने वगळलेली त्रुटी असते.
  • शेवटचा स्लॅश गाळणे. TikTok चे मार्ग / ने संपतात, आणि त्याच्या रिटर्न कोड परिशिष्टात /tt_user/oauth2/refresh_token हा स्लॅशशिवाय दिलेला मार्ग 404 page not found सह संपणारा कॉल म्हणून दिला आहे.
  • Node.js मध्ये reply_list मधून reply IDs घेणे. 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 सह, वेबहुकसाठी Flask, आणि Node.js 18 किंवा त्यानंतरची आवृत्ती, जिच्या अंगभूत fetch आणि node:crypto मधून बाकी सर्व मिळते.

मी ब्राउझरवरून TikTok API कॉल करू शकतो का?

कॉल तुमच्या सर्व्हरवर ठेवा. TikTok चा टोकन प्रकार Bearer आहे, जो तो बाळगणारा कोणीही वापरू शकतो, आणि टोकन एंडपॉइंट्सना तुमच्या ॲपचा client_secret लागतो.

पुढे वाचा

TikTok API मार्गदर्शक 2026: तुमच्या ॲपपासून पहिल्या पोस्टपर्यंत2026 मधील TikTok एपीआय पायरी-पायरी: कोणते एपीआय, ॲप मंजुरी, स्कोप, टोकन, प्रकाशन, स्टेटस, कमेंट, वेबहुक आणि मर्यादा, क्रमाने.TikTok API मधील 2026 बदल: काय बंद पडले आणि काय करावेTikTok API मधील 2026 बदल, नवीनतम प्रथम: टोकनची मुदत, is_business_account, कमेंट मर्यादा, ॲक्सेस फॉर्म आणि सँडबॉक्स, प्रत्येकाचे उपाय.TikTok एपीआय कनेक्शन का थांबते आणि ते सुरू कसे ठेवावेव्यवसायासाठीचे TikTok एपीआय कनेक्शन का थांबते: 24 तासांचा टोकन, एका वर्षाचा रिफ्रेश टोकन, काढलेली परवानगी, खात्यातील बदल आणि पुन्हा कनेक्ट कसे करावे.एपीआयद्वारे TikTok वर व्हिडिओ कसा पोस्ट करायचाTikTok व्यवसाय एपीआयद्वारे व्हिडिओ पोस्ट करा: पब्लिश एंडपॉइंट, JSON बॉडी, share_id आणि स्टेटस कॉल, curl व Python मध्ये.TikTok वेबहुक पडताळणी: स्वाक्षरी हेडर आणि ती कशी तपासायचीTikTok व्यवसाय एपीआयचा वेबहुक तपासा: Tiktok-Signature हेडर, t, पूर्णविराम आणि कच्च्या बॉडीवर ॲप सीक्रेटसह HMAC-SHA256, Node.js मध्ये.TikTok API दर मर्यादा: प्रति खाते, प्रति ॲप आणि प्रति एंडपॉइंटTikTok API दर मर्यादा: प्रति खाते व एंडपॉइंट 40 कॉल प्रति मिनिट, Accounts API साठी ॲपनुसार 600 किंवा 1,000 प्रति मिनिट, आणि चार ॲप स्तर.

तुमचे पहिले चॅनेल दोन मिनिटांत कनेक्ट करा.

कोणत्याही प्लॅटफॉर्म पुनरावलोकनाची वाट पाहावी लागत नाही. WhatsApp, Instagram, TikTok किंवा दुसरे चॅनेल कनेक्ट करा, मग तुमच्या AI ला पोस्ट करायला, उत्तर द्यायला किंवा रिपोर्ट द्यायला सांगा आणि ते काम करताना पाहा.

  • 3 दिवस मोफत
  • कधीही रद्द करा
  • फक्त अधिकृत एपीआय
  • 24/7 देखरेख

पडताळले: