Pubblica su Instagram, TikTok e Facebook da Node.js con un'unica API
Con easyCoexistence, un backend Node.js o TypeScript pubblica su Instagram, Facebook, TikTok, YouTube e LinkedIn tramite le API ufficiali di ciascun social. Gli account si collegano una sola volta tramite un link ospitato; una singola fetch restituisce poi un token sempre valido per ogni attività su TikTok, YouTube e LinkedIn, e gli eventi firmati portano commenti e DM alla tua route. Gli agenti costruiti con l'SDK MCP per TypeScript ricevono gli stessi account come strumenti.
Video che l'endpoint di pubblicazione di TikTok accetta per account, con non più di sei al minuto.
Con published false e un scheduled_publish_time, fino a quanto in anticipo si può programmare un post su una Pagina Facebook.
L'header di risposta che riporta l'URN di un nuovo post LinkedIn, inviato con stato 201.
Quanto presto TikTok invia un evento comment.update dopo che un commento viene creato, eliminato o cambia visibilità.
Per quanto tempo resta aperto un link di connessione della Partner API prima che la sessione scada.
Come collega account e ottiene i token un backend Node.js?
Il tuo backend apre una sessione di connessione e il titolare dell'account la completa nel browser. Una POST a /connect-sessions, con la tua chiave ec_live_ come bearer token, un canale come tiktok o linkedin, un redirect_url e un external_ref per il tuo cliente, restituisce un url su easycoexistence.com. Lì il titolare accede tramite la schermata di consenso del social stesso e torna al tuo redirect_url con status=connected e un channel_id; un tentativo annullato può essere ripetuto dallo stesso link fino alla scadenza, un'ora dopo la creazione.
Ogni lavoro inizia poi con GET /channels/{id}?credentials=1. La risposta contiene un token valido in questo momento (non su Instagram e Facebook, i cui token non vengono mai consegnati) e i campi che ogni social richiede: graph_api_base e account_id_on_meta su Instagram e Facebook, api_base e business_id su TikTok, channel_id su YouTube, author_urn e required_headers su LinkedIn. Gli eventi firmati channel.connected, channel.disconnected, channel.removed e channel.suspended, inviati all'URL degli eventi impostato nella dashboard, avvisano la tua app quando un account cambia.
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;
}Come pubblicare su Instagram e Facebook da Node.js?
Instagram pubblica tramite un container. Per un Reel, crealo con media_type REELS, il video_url e la didascalia, interroga il suo status_code finché non vale FINISHED, poi chiama media_publish con l'id del container come creation_id. Meta consiglia di interrogare circa una volta al minuto e di rinunciare dopo cinque minuti; ERROR o EXPIRED significa che il container non sarà pubblicato, e uno rimasto non pubblicato per 24 ore scade da solo.
Una Pagina Facebook riceve una foto con una sola chiamata a /{page-id}/photos, con l'url dell'immagine e la didascalia, mentre testo e link vanno a /{page-id}/feed. Entrambe accettano published false con un scheduled_publish_time, e Meta stessa pubblica il post all'orario stabilito, tra 10 minuti e 30 giorni in anticipo. Il token viaggia in un header bearer, la versione della Graph API è già contenuta in graph_api_base, e i media devono trovarsi su un URL pubblico che Meta scarica.
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
});
}Come pubblicare su LinkedIn e caricare su YouTube da Node.js?
LinkedIn richiede due header oltre al bearer token in ogni chiamata: LinkedIn-Version, con il valore YYYYMM che easyCoexistence restituisce in required_headers, e X-Restli-Protocol-Version impostato a 2.0.0. Un post è una POST a /rest/posts con l'URN dell'autore, il testo come commentary, visibilità PUBLIC, il feed principale come distribuzione e lifecycleState PUBLISHED. LinkedIn risponde 201 e inserisce l'URN del nuovo post nell'header x-restli-id, e qualunque URN posto in un percorso URL deve essere codificato in URL.
YouTube richiede due richieste. Una POST all'endpoint di caricamento con uploadType=resumable e part=snippet,status invia i metadati e restituisce l'indirizzo della sessione nell'header Location; una PUT dei byte del file a quell'indirizzo restituisce la risorsa video con il suo id. Caricando come privato con una data publishAt, la pubblicazione è affidata allo scheduler di YouTube, quindi nulla di tuo deve girare a quell'ora.
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;
}Come ricevere commenti e DM in una route Node.js?
Ogni canale inoltra all'URL che indichi con PUT /channels/{id}/webhook, e quella chiamata restituisce il signing_secret del canale una sola volta. Ogni consegna è una POST con platform, account_id, external_id ed entry, con un header X-EC-Signature nella forma t=<unix>,v1=<hex>, dove v1 è l'HMAC-SHA256 di t, di un punto e del body grezzo. Leggi il body come testo prima di fare il parsing, rifiuta un t più vecchio di cinque minuti e confronta con timingSafeEqual.
Per Instagram e Facebook, entry è l'entry del webhook di Meta così come lo ha inviato Meta: changes per commenti e menzioni, messaging per i DM. Per TikTok contiene l'evento comment.update, che TikTok invia entro cinque minuti da un commento, con comment_id e video_id come stringhe, così JavaScript non arrotonda quei numeri a 64 bit. C'è un solo tentativo per evento e nessuna copia salvata, quindi rispondi subito con 204 ed elabora dalla coda.
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 });
}Come rispondere a commenti e DM da Node.js?
Con una nuova chiamata alle credenziali e gli id dell'evento. Su Instagram e Facebook, una risposta a un DM va a /{account-id}/messages, usando account_id_on_meta, con l'id del mittente come recipient e entro 24 ore dall'ultimo messaggio; una Pagina aggiunge messaging_type RESPONSE, e Instagram accetta al massimo 1.000 byte di testo. Un commento riceve una risposta pubblica, a /{comment-id}/replies su Instagram o /{comment-id}/comments su Facebook, oppure una sola risposta privata entro 7 giorni.
Le conversazioni su TikTok restano pubbliche, perché su TikTok non ci sono DM. business/comment/reply/create/, con l'header Access-Token, business_id, video_id e comment_id, pubblica una risposta di fino a 1.200 caratteri. Leggi il campo code della risposta, dove 0 significa successo, invece dello stato HTTP. Agisci solo su comment_action insert con comment_type comment, perché anche le tue risposte arrivano come eventi.
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 },
});
}
}
}Come pubblicare su TikTok e dare a un agente TypeScript questi strumenti?
Entrambe le cose passano dal server MCP di easyCoexistence su https://easycoexistence.com/api/mcp, che accetta solo OAuth 2.1: registrazione dinamica del client, codice di autorizzazione con PKCE, token di accesso validi un'ora e token di aggiornamento. Con @modelcontextprotocol/client, l'SDK ufficiale per TypeScript su Node 20 e versioni successive, un OAuthClientProvider conserva il client, i token e il verificatore PKCE; il primo connect manda l'utente ad accedere e lancia UnauthorizedError, e finishAuth con la query della callback lo completa.
La pubblicazione su TikTok sta qui perché TikTok scarica i media solo da prefissi URL verificati per l'app sviluppatore dietro il token. publish_tiktok_post prende il tuo link HTTPS e fornisce a TikTok un indirizzo firmato sulla route media verificata di easyCoexistence, e get_tiktok_publish_status segue il post. Lo stesso client consegna all'agente tutti gli strumenti per i social dell'account; chiama prima list_social_accounts, il cui account_id è l'id di canale della Partner API.
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_statusErrori comuni
- Calcolare l'HMAC su JSON analizzato e serializzato di nuovo. La firma copre il body grezzo byte per byte, quindi chiama prima req.text() e fai il parsing dopo, altrimenti ogni consegna fallisce il controllo.
- Trasformare gli id TikTok in numeri. Gli id di commento e video sono a 64 bit e Number() li arrotonda, quindi conserva le stringhe che porta l'evento quando rispondi o cerchi un commento.
- Tenere solo il channel_id dal redirect. Un accesso a Facebook o LinkedIn può aggiungere più Pagine in una volta, quindi elencale con GET /channels?external_ref= e salvane ciascuna.
- Rispondere a un DM di Messenger o Instagram da un batch notturno. Oltre le 24 ore dall'ultimo messaggio della persona l'invio fallisce, quindi rispondi dal gestore dell'evento mentre la finestra è aperta.
easyCoexistence offre a backend Node.js e agenti IA l'accesso ai clienti su WhatsApp, Instagram, Facebook, TikTok, YouTube, LinkedIn e altri canali, ciascuno tramite la sua API ufficiale. Collega gli account con la Partner API, ottieni token sempre aggiornati ed eventi firmati, e lascia che gli agenti TypeScript agiscano tramite il server MCP, con ogni connessione monitorata 24/7. Da US$ 9 a US$ 0,75 per connessione al mese, con un prezzo che scende man mano che aggiungi connessioni, e i primi 3 giorni di prova gratuita.
Domande frequenti
Serve un SDK per chiamare queste API da Node?
No. La Partner API e le API dei social sono HTTPS semplice, quindi il fetch globale di Node 18 e versioni successive è sufficiente. @modelcontextprotocol/client serve solo per gli strumenti MCP, tra cui la pubblicazione su TikTok.
Perché la pubblicazione su TikTok passa dal server MCP?
TikTok scarica video e foto solo da un dominio o da un prefisso URL verificato per l'app sviluppatore, e quell'app è di easyCoexistence. publish_tiktok_post serve il tuo file HTTPS da quell'indirizzo verificato, quindi il tuo dominio non richiede alcuna verifica.
Un solo accesso può collegare più Pagine Facebook o LinkedIn?
Sì. Ogni Pagina, e su LinkedIn il profilo personale del membro, diventa un proprio canale e una propria connessione. Il redirect contiene il primo channel_id, e GET /channels?external_ref= le elenca tutte.
Quanto costa easyCoexistence per Node.js?
Da US$ 9 a US$ 0,75 per connessione al mese, con un prezzo che scende man mano che aggiungi connessioni, uguale su ogni social. La Partner API e il connettore MCP sono inclusi, senza licenze per utente, e i primi 3 giorni sono gratuiti.
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