La Facebook Messenger API consente agli sviluppatori di costruire esperienze conversazionali che raggiungono oltre 1,3 miliardi di utenti attivi mensili. Che tu stia creando un bot per l'assistenza clienti, un assistente per l'e-commerce o una campagna di marketing interattiva, la messenger platform api fornisce gli strumenti necessari per coinvolgere gli utenti in conversazioni significative.
Questa guida ti accompagna attraverso tutto, dalla configurazione iniziale alle funzionalità avanzate come i template di messaggi, le risposte rapide e il protocollo di passaggio agli operatori umani. Troverai esempi funzionanti in TypeScript in tutto il documento, pronti per essere adattati ai tuoi progetti.
Introduzione alla Messenger Platform
La Messenger Platform è il framework di Meta per costruire bot e integrazioni che comunicano con gli utenti attraverso Facebook Messenger. A differenza delle interfacce web tradizionali, la facebook chat api crea un'esperienza conversazionale in cui gli utenti interagiscono attraverso messaggi, pulsanti e contenuti multimediali ricchi.

Le principali funzionalità della messenger bot api includono:
| Funzionalità | Descrizione | Caso d'Uso |
|---|---|---|
| Messaggi di Testo | Invio e ricezione base di messaggi | Richieste clienti, notifiche |
| Template di Messaggi | Layout strutturati con immagini e pulsanti | Cataloghi prodotti, ricevute |
| Risposte Rapide | Pulsanti di risposta suggeriti | Conversazioni guidate, sondaggi |
| Menu Persistente | Opzioni di navigazione sempre disponibili | Navigazione del bot, azioni comuni |
| Messaggi Multimediali | Immagini, video, audio e file | Immagini prodotti, tutorial |
| Protocollo di Passaggio | Trasferimento tra bot e operatori umani | Escalation per supporto complesso |
La piattaforma opera su un'architettura basata su webhook. Il tuo server riceve i messaggi in arrivo tramite webhooks, li elabora e risponde utilizzando la Send API. Questo modello asincrono ti permette di costruire esperienze reattive senza mantenere connessioni aperte.
Configurazione della Tua Meta App
Prima di poter utilizzare la facebook messenger api, devi creare e configurare una Meta App. Questo processo stabilisce l'identità della tua applicazione e garantisce l'accesso alla Messenger Platform.
Passo 1: Creare una Meta App
Naviga al portale Meta for Developers e crea una nuova app. Seleziona "Business" come tipo di app, che fornisce accesso alle funzionalità di Messenger.
// Environment variables you'll need after setup
interface MessengerConfig {
FACEBOOK_APP_ID: string;
FACEBOOK_APP_SECRET: string;
FACEBOOK_PAGE_ID: string;
FACEBOOK_PAGE_ACCESS_TOKEN: string;
MESSENGER_VERIFY_TOKEN: string;
}
// Validate your configuration at startup
function validateConfig(): MessengerConfig {
const required = [
'FACEBOOK_APP_ID',
'FACEBOOK_APP_SECRET',
'FACEBOOK_PAGE_ID',
'FACEBOOK_PAGE_ACCESS_TOKEN',
'MESSENGER_VERIFY_TOKEN'
];
const missing = required.filter(key => !process.env[key]);
if (missing.length > 0) {
throw new Error(`Missing required environment variables: ${missing.join(', ')}`);
}
return {
FACEBOOK_APP_ID: process.env.FACEBOOK_APP_ID!,
FACEBOOK_APP_SECRET: process.env.FACEBOOK_APP_SECRET!,
FACEBOOK_PAGE_ID: process.env.FACEBOOK_PAGE_ID!,
FACEBOOK_PAGE_ACCESS_TOKEN: process.env.FACEBOOK_PAGE_ACCESS_TOKEN!,
MESSENGER_VERIFY_TOKEN: process.env.MESSENGER_VERIFY_TOKEN!
};
}
Passo 2: Aggiungere il Prodotto Messenger
Nella dashboard della tua app, clicca su "Add Product" e seleziona Messenger. Questo abilita le funzionalità della Messenger Platform per la tua app.
Passo 3: Collegare una Pagina Facebook
Il tuo bot ha bisogno di una Pagina Facebook per inviare e ricevere messaggi. Nelle impostazioni di Messenger, clicca su "Add or Remove Pages" e seleziona la pagina che vuoi collegare. Genera un Page Access Token, che userai per autenticare le richieste API.
Nota: I Page Access Token possono essere a breve o lunga durata. Per le applicazioni in produzione, scambia il tuo token con una versione a lunga durata che dura circa 60 giorni.
interface TokenExchangeResponse {
access_token: string;
token_type: string;
expires_in?: number;
}
async function exchangeForLongLivedToken(
shortLivedToken: string,
appId: string,
appSecret: string
): Promise {
const baseUrl = 'https://graph.facebook.com/v18.0';
const params = new URLSearchParams({
grant_type: 'fb_exchange_token',
client_id: appId,
client_secret: appSecret,
fb_exchange_token: shortLivedToken,
});
const response = await fetch(`${baseUrl}/oauth/access_token?${params.toString()}`);
if (!response.ok) {
const error = await response.text();
throw new Error(`Token exchange failed: ${error}`);
}
const data = await response.json();
if (!data.access_token) {
throw new Error('No access token returned from token exchange');
}
const expiresInDays = data.expires_in
? Math.floor(data.expires_in / 86400)
: 'unknown';
console.log(`Token exchanged successfully (expires in ${expiresInDays} days)`);
return {
access_token: data.access_token,
token_type: data.token_type || 'bearer',
expires_in: data.expires_in,
};
}
Passo 4: Configurare i Permessi dell'App
Richiedi i permessi necessari per il tuo bot. Come minimo, avrai bisogno di:
pages_messaging: Inviare e ricevere messaggipages_manage_metadata: Sottoscriversi ai webhookspages_read_engagement: Accedere ai dati delle conversazioni
Configurazione e Verifica dei Webhook
I webhooks sono la spina dorsale della messenger platform api. Permettono a Facebook di notificare il tuo server quando si verificano eventi, come messaggi in arrivo o conferme di consegna.
Configurazione del Tuo Endpoint Webhook
Crea un endpoint che gestisca sia le richieste GET (per la verifica) che le richieste POST (per ricevere gli eventi).
import express, { Request, Response } from 'express';
import crypto from 'crypto';
const app = express();
// Parse raw body for signature verification
app.use(express.json({
verify: (req: any, res, buf) => {
req.rawBody = buf;
}
}));
// Webhook verification endpoint
app.get('/webhook', (req: Request, res: Response) => {
const mode = req.query['hub.mode'];
const token = req.query['hub.verify_token'];
const challenge = req.query['hub.challenge'];
const verifyToken = process.env.MESSENGER_VERIFY_TOKEN;
if (mode === 'subscribe' && token === verifyToken) {
console.log('Webhook verified successfully');
res.status(200).send(challenge);
} else {
console.error('Webhook verification failed');
res.sendStatus(403);
}
});
// Webhook event receiver
app.post('/webhook', (req: Request, res: Response) => {
// Verify request signature
const signature = req.headers['x-hub-signature-256'] as string;
if (!verifySignature(req, signature)) {
console.error('Invalid signature');
return res.sendStatus(401);
}
const body = req.body;
if (body.object !== 'page') {
return res.sendStatus(404);
}
// Process each entry
body.entry?.forEach((entry: any) => {
entry.messaging?.forEach((event: any) => {
handleMessagingEvent(event);
});
});
// Always respond with 200 OK quickly
res.sendStatus(200);
});
function verifySignature(req: any, signature: string): boolean {
if (!signature) return false;
const appSecret = process.env.FACEBOOK_APP_SECRET!;
const expectedSignature = 'sha256=' + crypto
.createHmac('sha256', appSecret)
.update(req.rawBody)
.digest('hex');
return crypto.timingSafeEqual(
Buffer.from(signature),
Buffer.from(expectedSignature)
);
}
async function handleMessagingEvent(event: any): Promise {
const senderId = event.sender.id;
if (event.message) {
await handleMessage(senderId, event.message);
} else if (event.postback) {
await handlePostback(senderId, event.postback);
} else if (event.read) {
console.log(`Message read by ${senderId}`);
} else if (event.delivery) {
console.log(`Message delivered to ${senderId}`);
}
}
Sottoscrizione agli Eventi Webhook
Dopo aver configurato il tuo endpoint, sottoscriviti agli eventi che vuoi ricevere. Nella Dashboard della Meta App, configura l'URL del tuo webhook e seleziona i campi di sottoscrizione rilevanti:
messages: Messaggi in arrivomessaging_postbacks: Click sui pulsanti e selezioni dal menumessaging_optins: Opt-in degli utentimessage_deliveries: Conferme di consegnamessage_reads: Conferme di lettura
Ricezione dei Messaggi
Quando gli utenti inviano messaggi al tuo bot, la facebook chat api li consegna al tuo webhook. I messaggi possono contenere testo, allegati o entrambi.
interface MessengerMessage {
mid: string;
text?: string;
attachments?: Array<{
type: 'image' | 'video' | 'audio' | 'file' | 'location' | 'fallback';
payload: {
url?: string;
coordinates?: {
lat: number;
long: number;
};
};
}>;
quick_reply?: {
payload: string;
};
reply_to?: {
mid: string;
};
}
async function handleMessage(
senderId: string,
message: MessengerMessage
): Promise {
console.log(`Received message from ${senderId}:`, message);
// Handle quick reply responses
if (message.quick_reply) {
await handleQuickReply(senderId, message.quick_reply.payload);
return;
}
// Handle attachments
if (message.attachments && message.attachments.length > 0) {
for (const attachment of message.attachments) {
await handleAttachment(senderId, attachment);
}
return;
}
// Handle text messages
if (message.text) {
await processTextMessage(senderId, message.text);
}
}
async function handleAttachment(
senderId: string,
attachment: MessengerMessage['attachments'][0]
): Promise {
switch (attachment.type) {
case 'image':
await sendTextMessage(senderId, `Thanks for the image! I received: ${attachment.payload.url}`);
break;
case 'location':
const { lat, long } = attachment.payload.coordinates!;
await sendTextMessage(senderId, `Got your location: ${lat}, ${long}`);
break;
default:
await sendTextMessage(senderId, `Received your ${attachment.type}`);
}
}
async function processTextMessage(
senderId: string,
text: string
): Promise {
const lowerText = text.toLowerCase();
if (lowerText.includes('help')) {
await sendHelpMessage(senderId);
} else if (lowerText.includes('products')) {
await sendProductCatalog(senderId);
} else {
await sendTextMessage(senderId, `You said: "${text}". How can I help you today?`);
}
}
Invio di Messaggi di Testo
La Send API è il tuo strumento principale per rispondere agli utenti attraverso la messenger bot api. I messaggi di testo sono la forma più semplice di risposta.
const GRAPH_API_URL = 'https://graph.facebook.com/v18.0';
interface SendMessageResponse {
recipient_id: string;
message_id: string;
}
interface SendMessageError {
message: string;
type: string;
code: number;
error_subcode?: number;
fbtrace_id: string;
}
async function sendTextMessage(
recipientId: string,
text: string
): Promise {
const pageAccessToken = process.env.FACEBOOK_PAGE_ACCESS_TOKEN!;
const response = await fetch(
`${GRAPH_API_URL}/me/messages?access_token=${pageAccessToken}`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
recipient: { id: recipientId },
message: { text },
messaging_type: 'RESPONSE'
}),
}
);
const data = await response.json();
if (!response.ok) {
const error = data.error as SendMessageError;
throw new Error(`Send failed: ${error.message} (code: ${error.code})`);
}
return data as SendMessageResponse;
}
// Send typing indicator for better UX
async function sendTypingIndicator(
recipientId: string,
isTyping: boolean
): Promise {
const pageAccessToken = process.env.FACEBOOK_PAGE_ACCESS_TOKEN!;
await fetch(
`${GRAPH_API_URL}/me/messages?access_token=${pageAccessToken}`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
recipient: { id: recipientId },
sender_action: isTyping ? 'typing_on' : 'typing_off'
}),
}
);
}
// Helper function to send messages with typing indicator
async function sendMessageWithTyping(
recipientId: string,
text: string,
typingDuration: number = 1000
): Promise {
await sendTypingIndicator(recipientId, true);
await new Promise(resolve => setTimeout(resolve, typingDuration));
return sendTextMessage(recipientId, text);
}
Template di Messaggi (Generic, Button, Receipt)
I template di messaggi creano esperienze ricche e interattive che vanno oltre il semplice testo. La facebook messenger api supporta diversi tipi di template, ognuno progettato per casi d'uso specifici.
Generic Template
Il Generic Template visualizza un carosello di elementi, perfetto per elenchi di prodotti o feed di contenuti.
interface GenericTemplateElement {
title: string;
subtitle?: string;
image_url?: string;
default_action?: {
type: 'web_url';
url: string;
webview_height_ratio?: 'compact' | 'tall' | 'full';
};
buttons?: Array;
}
type TemplateButton =
| { type: 'web_url'; url: string; title: string }
| { type: 'postback'; title: string; payload: string }
| { type: 'phone_number'; title: string; payload: string }
| { type: 'account_link'; url: string }
| { type: 'ac