import type { Channel, ChannelEvent, MessageStatus, SendResult } from './types'; export interface MetaChannelConfig { /** phone_number_id — non secret, sert d'identifiant externe de ChannelAccount. */ phoneNumberId: string; /** Bearer token WhatsApp Cloud API — secret, décrypté au runtime. */ accessToken: string; /** Token de vérification du webhook (hub.verify_token). */ verifyToken?: string; /** Version Graph API (défaut v22.0). */ graphApiVersion?: string; /** WABA ID (pour info/traçabilité). */ wabaId?: string; } const DEFAULT_GRAPH_VERSION = 'v22.0'; function normalizeStatus(s: string): MessageStatus { switch (s) { case 'delivered': return 'delivered'; case 'read': return 'read'; case 'failed': return 'failed'; case 'sent': default: return 'sent'; } } /** * Adaptateur WhatsApp Meta (Cloud API). Confine TOUT le JSON Meta ici : * core ne voit que des `ChannelEvent` / `InboundMessage` / `SendResult`. */ export class WhatsAppMetaChannel implements Channel { readonly channelType = 'whatsapp' as const; constructor( private config: MetaChannelConfig, private fetchImpl: typeof fetch = fetch ) {} verifyWebhook(query: Record): { verified: boolean; challenge?: string } { const mode = query['hub.mode']; const token = query['hub.verify_token']; const challenge = query['hub.challenge']; if (mode === 'subscribe' && this.config.verifyToken && token === this.config.verifyToken) { return { verified: true, challenge }; } return { verified: false }; } parseWebhook(payload: unknown): ChannelEvent[] { const events: ChannelEvent[] = []; const obj = payload as any; if (!obj || obj.object !== 'whatsapp_business_account') return events; for (const entry of obj.entry ?? []) { for (const change of entry.changes ?? []) { if (change.field !== 'messages') continue; const value = change.value ?? {}; const phoneNumberId: string = value.metadata?.phone_number_id; // Messages entrants (texte uniquement pour Phase 2) for (const msg of value.messages ?? []) { if (msg.type !== 'text') continue; events.push({ type: 'message_received', inbound: { channelType: 'whatsapp', channelAccountExternalId: phoneNumberId, externalUserId: msg.from, externalMessageId: msg.id, text: msg.text?.body ?? '', timestamp: new Date(Number(msg.timestamp) * 1000), }, }); } // Statuts des messages sortants (sent/delivered/read/failed) for (const st of value.statuses ?? []) { events.push({ type: 'message_status', channelType: 'whatsapp', channelAccountExternalId: phoneNumberId, externalMessageId: st.id, status: normalizeStatus(st.status), timestamp: new Date(Number(st.timestamp) * 1000), error: st.errors?.[0]?.message, }); } } } return events; } async sendMessage(to: string, text: string): Promise { const version = this.config.graphApiVersion ?? DEFAULT_GRAPH_VERSION; const url = `https://graph.facebook.com/${version}/${this.config.phoneNumberId}/messages`; let res: Response; try { res = await this.fetchImpl(url, { method: 'POST', headers: { Authorization: `Bearer ${this.config.accessToken}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ messaging_product: 'whatsapp', to, type: 'text', text: { body: text }, }), }); } catch (e) { return { status: 'failed', error: e instanceof Error ? e.message : String(e) }; } const body = await res.json().catch(() => ({})); if (!res.ok) { return { status: 'failed', error: body?.error?.message ?? `Graph API HTTP ${res.status}` }; } const wamid: string | undefined = body?.messages?.[0]?.id; if (!wamid) return { status: 'failed', error: 'no wamid in Graph API response' }; return { status: 'sent', externalMessageId: wamid }; } }