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

用一个 API 从 Node.js 发布到 Instagram、TikTok 和 Facebook

借助 easyCoexistence,Node.js 或 TypeScript 后端可通过各网络的官方 API,向 Instagram、Facebook、TikTok、YouTube 和 LinkedIn 发布内容。账户只需通过托管链接登录一次;之后每个任务调用一次 fetch,即可在 TikTok、YouTube 和 LinkedIn 上获取新的访问令牌,签名事件则会把评论和私信送达您的路由。基于 TypeScript MCP SDK 构建的 Agent 可把相同的账户当作工具使用。

15 a day

TikTok 发布端点对每个账户接受的视频发布,频率不超过每分钟 6 次。

10 min to 30 days

设置 published false 并使用 scheduled_publish_time 时,Facebook 主页帖子可提前预定的时长。

x-restli-id

状态码为 201 时,承载新 LinkedIn 帖子 URN 的响应头。

5 minutes

评论被创建、删除或可见性被修改后,TikTok 多久触发一次 comment.update 事件。

1 hour

Partner API 连接链接在会话过期前保持有效的时长。

Node.js 后端如何连接账户并获取它们的访问令牌?

您的后端会打开一个连接会话,账户所有者在浏览器中完成操作。向 /connect-sessions 发送 POST 请求,以 ec_live_ 密钥作为 Bearer 访问令牌,并附上 tiktok 或 linkedin 等 channel、redirect_url,以及客户的 external_ref,即可返回 easycoexistence.com 上的 URL。所有者在此登录网络方自己的授权页面,随后带着 status=connected 和 channel_id 返回您的 redirect_url;已取消的尝试可在链接过期前,即创建后一小时内,从同一链接重试。

每个任务随后以 GET /channels/{id}?credentials=1 开始。响应中包含一个当前有效的访问令牌(不适用于 Instagram 与 Facebook,其令牌从不提供),以及各网络所需的字段:Instagram 与 Facebook 上的 graph_api_base 和 account_id_on_meta,TikTok 上的 api_base 和 business_id,YouTube 上的 channel_id,LinkedIn 上的 author_urn 和 required_headers。已签名的 channel.connected、channel.disconnected、channel.removed 和 channel.suspended 事件会发送至您在控制台中设置的事件 URL,让您的应用知道账户何时发生变化。

A connect link and per-job credentials with fetch
const EC = "https://easycoexistence.com/api/v1";
const KEY = { Authorization: `Bearer ${process.env.EC_API_KEY}` }; // ec_live_...

type Network = "instagram" | "facebook" | "tiktok" | "youtube" | "linkedin";

// A hosted sign-in link for one of your customers on one network
export async function connectLink(customerId: string, channel: Network): Promise<string> {
  const r = await fetch(`${EC}/connect-sessions`, {
    method: "POST",
    headers: { ...KEY, "Content-Type": "application/json" },
    body: JSON.stringify({
      channel,
      redirect_url: "https://app.example.com/connected",
      external_ref: customerId,
    }),
  });
  const session = (await r.json()) as { url: string; error?: { message: string } };
  if (!r.ok) throw new Error(session.error?.message);
  return session.url; // they come back with ?session=...&status=connected&channel_id=...
}

// At the start of every job: the API base and a token that is valid now
export async function credentials(channelId: string) {
  const r = await fetch(`${EC}/channels/${channelId}?credentials=1`, { headers: KEY });
  const body: any = await r.json(); // the credential fields differ by network
  if (!r.ok) throw new Error(body.error.message);
  if (!body.credentials.access_token) throw new Error(body.credentials.note);
  return body.credentials;
}

如何使用 Node.js 发布到 Instagram 和 Facebook?

Instagram 通过容器发布。对于 Reel 视频,使用 media_type REELS、video_url 与 caption 创建容器,轮询其 status_code 直到显示 FINISHED,然后以容器 ID 作为 creation_id 调用 media_publish。Meta 建议约每分钟轮询一次,五分钟后放弃;ERROR 或 EXPIRED 表示该容器无法发布,未发布满 24 小时的容器会自动过期。

Facebook 主页通过一次调用 /{page-id}/photos 发布照片,附上图片 URL 和 caption;文字和链接则发送至 /{page-id}/feed。两者都接受 published false 与 scheduled_publish_time,Meta 会在指定时间自行发布,可提前 10 分钟至 30 天之间的时间。访问令牌以 Bearer 标头传递,Graph API 版本已包含在 graph_api_base 中,媒体文件必须位于 Meta 能够下载的公开 URL 上。

Publish a Reel and schedule a Page photo
type Meta = { graph_api_base: string; access_token: string };

async function graph(c: Meta, path: string, body?: object) {
  const r = await fetch(`${c.graph_api_base}/${path}`, {
    method: body ? "POST" : "GET",
    headers: { Authorization: `Bearer ${c.access_token}`, "Content-Type": "application/json" },
    body: body && JSON.stringify(body),
  });
  const data: any = await r.json();
  if (!r.ok) throw new Error(data.error?.message ?? `Graph API ${r.status}`);
  return data;
}

export async function postReel(channelId: string, videoUrl: string, caption: string) {
  const c = await credentials(channelId);
  const ig = c.account_id_on_meta;
  const { id } = await graph(c, `${ig}/media`, { media_type: "REELS", video_url: videoUrl, caption });
  for (let check = 0; check < 5; check++) {
    await new Promise((wake) => setTimeout(wake, 60_000)); // about once a minute, as Meta advises
    const { status_code } = await graph(c, `${id}?fields=status_code`);
    if (status_code === "FINISHED") return graph(c, `${ig}/media_publish`, { creation_id: id });
    if (status_code === "ERROR" || status_code === "EXPIRED") throw new Error(`Reel container ${status_code}`);
  }
  throw new Error("The Reel is still processing after five minutes");
}

export async function schedulePagePhoto(channelId: string, url: string, caption: string, at: Date) {
  const c = await credentials(channelId);
  return graph(c, `${c.account_id_on_meta}/photos`, {
    url,
    caption,
    published: false,
    scheduled_publish_time: Math.floor(at.getTime() / 1000), // 10 minutes to 30 days ahead
  });
}

如何使用 Node.js 发布到 LinkedIn 并上传到 YouTube?

LinkedIn 每次调用除 Bearer 访问令牌外,还需两个标头:LinkedIn-Version,值为 easyCoexistence 在 required_headers 中返回的 YYYYMM;以及设为 2.0.0 的 X-Restli-Protocol-Version。发帖需向 /rest/posts 发送 POST 请求,包含作者 URN、commentary 中的文本、PUBLIC 可见性、以主信息流作为 distribution,以及 lifecycleState PUBLISHED。LinkedIn 返回 201,并将新帖子的 URN 放在 x-restli-id 标头中;放入 URL 路径的任何 URN 都必须进行 URL 编码。

YouTube 需要两次请求。向上传端点发送 POST,附带 uploadType=resumable 和 part=snippet,status 以发送元数据,并在 Location 标头中获得会话地址;然后将文件字节以 PUT 发送至该地址,即可返回带有 id 的视频资源。若以 private 状态上传并设置 publishAt 日期,发布工作将交由 YouTube 自己的调度器完成,您的程序无需在那个时刻运行。

Publish on LinkedIn and schedule a YouTube upload
import { readFile } from "node:fs/promises";

export async function postOnLinkedIn(channelId: string, text: string) {
  const c = await credentials(channelId);
  const r = await fetch(`${c.api_base}/posts`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${c.access_token}`,
      "LinkedIn-Version": c.required_headers["LinkedIn-Version"],
      "X-Restli-Protocol-Version": "2.0.0",
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      author: c.author_urn, // urn:li:organization:... or urn:li:person:...
      commentary: text,
      visibility: "PUBLIC",
      distribution: { feedDistribution: "MAIN_FEED", targetEntities: [], thirdPartyDistributionChannels: [] },
      lifecycleState: "PUBLISHED",
      isReshareDisabledByAuthor: false,
    }),
  });
  if (r.status !== 201) throw new Error(`LinkedIn ${r.status}: ${await r.text()}`);
  return r.headers.get("x-restli-id"); // the new post's URN
}

export async function scheduleOnYouTube(channelId: string, file: string, title: string, publishAt: string) {
  const c = await credentials(channelId);
  const auth = { Authorization: `Bearer ${c.access_token}` };
  const start = await fetch(
    "https://www.googleapis.com/upload/youtube/v3/videos?uploadType=resumable&part=snippet,status",
    {
      method: "POST",
      headers: { ...auth, "Content-Type": "application/json; charset=UTF-8", "X-Upload-Content-Type": "video/mp4" },
      body: JSON.stringify({
        snippet: { title },
        status: { privacyStatus: "private", publishAt, selfDeclaredMadeForKids: false },
      }),
    },
  );
  const session = start.headers.get("location");
  if (!start.ok || !session) throw new Error(`YouTube ${start.status}: ${await start.text()}`);
  const done = await fetch(session, {
    method: "PUT",
    headers: { ...auth, "Content-Type": "video/mp4" },
    body: await readFile(file),
  });
  const video = (await done.json()) as { id: string };
  return video.id;
}

如何在 Node.js 路由中接收评论和私信?

每个渠道的消息会转发至您通过 PUT /channels/{id}/webhook 设置的 URL,该调用会一次性返回渠道的 signing_secret。每次投递都是 POST 请求,包含 platform、account_id、external_id 和 entry,并带有 X-EC-Signature 标头,格式为 t=<unix>,v1=<hex>,其中 v1 是对 t、一个点号和原始正文计算的 HMAC-SHA256。解析前先将正文读取为文本,拒绝早于 5 分钟的 t,并使用 timingSafeEqual 进行比较。

对于 Instagram 和 Facebook,entry 为 Meta 原样发送的 Webhook entry:评论和提及位于 changes,私信位于 messaging。对于 TikTok,entry 包含 comment.update 事件,TikTok 会在评论产生后 5 分钟内触发该事件,其中 comment_id 和 video_id 以字符串形式提供,以免 JavaScript 对这些 64 位数字进行舍入。每个事件只投递一次,且不保存副本,因此请立即响应 204,并从队列中处理。

Turn on forwarding and verify X-EC-Signature in a route handler
import { createHmac, timingSafeEqual } from "node:crypto";

const secrets = new Map<string, string>(); // channel id -> signing_secret, kept in your database

export async function forwardEvents(channelId: string, url: string) {
  const r = await fetch(`${EC}/channels/${channelId}/webhook`, {
    method: "PUT",
    headers: { ...KEY, "Content-Type": "application/json" },
    body: JSON.stringify({ url }),
  });
  const body = (await r.json()) as { signing_secret: string; error?: { message: string } };
  if (!r.ok) throw new Error(body.error?.message);
  secrets.set(channelId, body.signing_secret); // returned only this once
}

function verify(raw: string, header: string | null, secret: string): boolean {
  const parts = Object.fromEntries((header ?? "").split(",").map((kv) => kv.split("=", 2)));
  const t: string = parts.t ?? "";
  const v1: string = parts.v1 ?? "";
  if (!/^[0-9]+$/.test(t) || Math.abs(Date.now() / 1000 - Number(t)) > 300) return false;
  const mac = createHmac("sha256", secret).update(`${t}.${raw}`).digest("hex");
  return mac.length === v1.length && timingSafeEqual(Buffer.from(mac), Buffer.from(v1));
}

// POST /hooks/social as a web-standard handler (Next.js, Hono, Bun and others)
export async function POST(req: Request) {
  const raw = await req.text(); // the signature covers these exact bytes
  const event = JSON.parse(raw); // { platform, account_id, external_id, entry }
  const secret = secrets.get(event.account_id);
  if (!secret || !verify(raw, req.headers.get("x-ec-signature"), secret)) {
    return new Response("invalid signature", { status: 401 });
  }
  await enqueue(event); // one attempt per event and no retries: acknowledge first
  return new Response(null, { status: 204 });
}

如何在 Node.js 中回复评论和私信?

使用新的 credentials 请求,并结合事件中的 ID。在 Instagram 和 Facebook 上,私信回复发送至 /{account-id}/messages,使用 account_id_on_meta,收件人为发送者的 ID,且须在对方最后一条消息后 24 小时内发送;主页需附加 messaging_type RESPONSE,Instagram 允许的文本最多 1,000 字节。公开评论回复发送至 Instagram 的 /{comment-id}/replies 或 Facebook 的 /{comment-id}/comments;私下回复只能发送一次,且须在 7 天内发送。

TikTok 上的对话始终公开,因为 TikTok 没有私信功能。business/comment/reply/create/ 请求须带上 Access-Token 标头、business_id、video_id 和 comment_id,可发布最多 1,200 个字符的回复。请读取响应中的 code 字段,其中 0 表示成功,而非 HTTP 状态码。只处理 comment_action 为 insert 且 comment_type 为 comment 的事件,因为您自己的回复也会以事件形式送达。

Reply to a TikTok comment and a Messenger DM
export async function reply(event: any, text: string) {
  const c = await credentials(event.account_id);
  if (event.platform === "tiktok") {
    const e = event.entry.content; // the comment.update event, ids as strings
    if (e.comment_action !== "insert" || e.comment_type !== "comment") return; // your replies arrive as "reply"
    const r = await fetch(`${c.api_base}/business/comment/reply/create/`, {
      method: "POST",
      headers: { "Access-Token": c.access_token, "Content-Type": "application/json" },
      body: JSON.stringify({ business_id: c.business_id, video_id: e.video_id, comment_id: e.comment_id, text }),
    });
    const out = (await r.json()) as { code: number; message: string };
    if (out.code !== 0) throw new Error(out.message); // 0 is success, whatever the HTTP status
  } else if (event.platform === "facebook") {
    for (const m of event.entry.messaging ?? []) {
      if (!m.message || m.message.is_echo) continue; // only what people sent the Page
      await graph(c, `${c.account_id_on_meta}/messages`, {
        recipient: { id: m.sender.id },
        messaging_type: "RESPONSE", // within 24 hours of their last message
        message: { text },
      });
    }
  }
}

如何发布到 TikTok,并为 TypeScript Agent 提供这些工具?

两者都通过 easyCoexistence 的 MCP 服务器 https://easycoexistence.com/api/mcp 进行,该服务器仅接受 OAuth 2.1:动态客户端注册、带 PKCE 的授权码,访问令牌有效期为一小时,并配有刷新令牌。使用面向 Node 20 及更高版本的官方 TypeScript SDK @modelcontextprotocol/client,OAuthClientProvider 负责保存客户端、令牌和 PKCE verifier;首次连接会将用户引导至登录页面并抛出 UnauthorizedError,随后以回调的 query 调用 finishAuth 即可完成授权。

TikTok 发布功能在此提供,因为 TikTok 只会从为该令牌对应的开发者应用验证过的 URL 前缀下载媒体。publish_tiktok_post 接收您的 HTTPS 链接,并向 TikTok 提供 easyCoexistence 已验证媒体路由上的签名地址;get_tiktok_publish_status 用于跟踪该帖子。同一客户端会为 Agent 提供该账户所属各网络的全部工具;请先调用 list_social_accounts,其 account_id 即为 Partner API 的渠道 ID。

Sign in over OAuth and publish to TikTok with the MCP client
import { createInterface } from "node:readline/promises";
import { Client, StreamableHTTPClientTransport, UnauthorizedError, type OAuthClientProvider } from "@modelcontextprotocol/client";

const MCP = new URL("https://easycoexistence.com/api/mcp");
const saved: Record<string, any> = {}; // persist this, so the browser sign-in happens once

const provider: OAuthClientProvider = {
  redirectUrl: "http://localhost:8090/callback",
  clientMetadata: { client_name: "My social agent", redirect_uris: ["http://localhost:8090/callback"] },
  state: () => (saved.state = crypto.randomUUID()),
  clientInformation: () => saved.client,
  saveClientInformation: (info) => { saved.client = info; },
  tokens: () => saved.tokens,
  saveTokens: (tokens) => { saved.tokens = tokens; },
  saveCodeVerifier: (verifier) => { saved.verifier = verifier; },
  codeVerifier: () => saved.verifier,
  redirectToAuthorization: (url) => console.log("Sign in to easyCoexistence:", url.href),
};

const client = new Client({ name: "my-social-agent", version: "1.0.0" });
const transport = new StreamableHTTPClientTransport(MCP, { authProvider: provider });
try {
  await client.connect(transport);
} catch (error) {
  if (!(error instanceof UnauthorizedError)) throw error;
  const rl = createInterface({ input: process.stdin, output: process.stdout });
  const back = new URL(await rl.question("Paste the address you were sent back to: ")).searchParams;
  rl.close();
  if (back.get("state") !== saved.state) throw new Error("state mismatch");
  await transport.finishAuth(back);
  await client.connect(new StreamableHTTPClientTransport(MCP, { authProvider: provider }));
}

const result = await client.callTool({
  name: "publish_tiktok_post",
  arguments: {
    account_id: process.env.TIKTOK_CHANNEL_ID, // the Partner API channel id
    video_url: "https://cdn.example.com/launch.mp4",
    caption: "New drop #behindthescenes",
  },
});
console.log(result.content); // a share_id to follow with get_tiktok_publish_status

常见错误

  • 在解析并重新序列化后的 JSON 上计算 HMAC。签名覆盖的是原始正文的每个字节,因此应先调用 req.text() 再解析,否则每次投递都会未通过校验。
  • 将 TikTok ID 转为数字。评论和视频 ID 为 64 位,Number() 会对其进行舍入,因此在回复或查询评论时,请保留事件中携带的字符串。
  • 只保留重定向中的 channel_id。Facebook 或 LinkedIn 登录可能一次添加多个主页,因此请使用 GET /channels?external_ref= 列出它们,并分别存储。
  • 在每晚批处理中回复 Messenger 或 Instagram 私信。超出对方最后一条消息 24 小时后,发送会失败,因此请在时间窗口开放期间,从事件处理程序中回复。
使用 EasyCoexistence 完成这些操作

easyCoexistence 为 Node.js 后端和 AI Agent 提供触达客户的能力,覆盖 WhatsApp、Instagram、Facebook、TikTok、YouTube、LinkedIn 等更多渠道,每个渠道均通过其官方 API 接入。使用 Partner API 连接账户,获取新的访问令牌和签名事件,并让 TypeScript Agent 通过 MCP 服务器执行操作,每个连接均提供 24/7 监控。每个连接每月 US$ 9 至 US$ 0.75,连接越多越便宜,前 3 天免费。

常见问题

调用这些 API 需要 Node.js 的 SDK 吗?

不需要。Partner API 和各网络的 API 都是普通的 HTTPS,因此 Node 18 及更高版本内置的全局 fetch 即可胜任。只有 MCP 工具(包括 TikTok 发布功能)才需要引入 @modelcontextprotocol/client。

为什么 TikTok 发布要经过 MCP 服务器?

TikTok 只从为开发者应用验证过的域名或 URL 前缀下载视频和图片,而该应用属于 easyCoexistence。publish_tiktok_post 会从该已验证地址提供您的 HTTPS 文件,因此您自己的域名无需验证。

一次登录可以连接多个 Facebook 或 LinkedIn 主页吗?

可以。每个主页,以及 LinkedIn 上成员本人的个人资料,都会成为独立的渠道和独立的连接。重定向会携带第一个 channel_id,而 GET /channels?external_ref= 可列出全部渠道。

easyCoexistence 对 Node.js 的收费是多少?

每个连接每月 US$ 9 至 US$ 0.75,连接越多越便宜,各网络收费相同。Partner API 和 MCP 连接器均包含在内,无需按席位付费,前 3 天免费。

继续阅读

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

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

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

验证时间