File size: 9,961 Bytes
b43e552 de6a95b b43e552 6dd9bad b43e552 cc442ef b25d16e b43e552 6dd9bad b43e552 6dd9bad b43e552 6dd9bad b43e552 0f2f80a 170eb5d 0f2f80a 6dd9bad e289c5c b43e552 e289c5c 4339e77 b43e552 4339e77 b43e552 4339e77 b43e552 4339e77 6dd9bad 4339e77 6dd9bad 4339e77 6dd9bad b43e552 6dd9bad b43e552 6dd9bad 4339e77 6dd9bad b43e552 6dd9bad b43e552 cc442ef b43e552 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 | import axios from 'axios';
import { logger } from '../logger';
export interface WhatsAppMessage {
to: string;
text?: string;
templateName?: string;
templateLanguage?: string;
}
export class WhatsAppService {
private baseUrl = process.env.WHATSAPP_GRAPH_URL || `https://graph.facebook.com/${process.env.META_GRAPH_API_VERSION || 'v22.0'}`;
/**
* Sends a direct text message or template via WhatsApp Cloud API
*/
async sendMessage(config: { accessToken: string; phoneNumberId: string }, message: WhatsAppMessage) {
try {
const url = `${this.baseUrl}/${config.phoneNumberId}/messages`;
let payload: any;
if (message.templateName) {
payload = {
messaging_product: 'whatsapp',
recipient_type: 'individual',
to: message.to,
type: 'template',
template: {
name: message.templateName,
language: {
code: message.templateLanguage || 'fr'
}
}
};
} else {
payload = {
messaging_product: 'whatsapp',
recipient_type: 'individual',
to: message.to,
type: 'text',
text: { body: message.text || '' }
};
}
const response = await axios.post(url, payload, {
headers: {
'Authorization': `Bearer ${config.accessToken}`,
'Content-Type': 'application/json'
}
});
return {
id: response.data.messages?.[0]?.id,
status: 'SENT'
};
} catch (err: any) {
logger.error({
error: err.response?.data || err.message,
to: message.to,
template: message.templateName
}, '[WHATSAPP_SERVICE] Failed to send message');
throw err;
}
}
/**
* Bulk send utility
*/
async sendBulk(config: { accessToken: string; phoneNumberId: string }, messages: WhatsAppMessage[]) {
const results = { sent: 0, failed: 0 };
// We use sequential or limited concurrency to avoid Meta rate limits
for (const msg of messages) {
try {
await this.sendMessage(config, msg);
results.sent++;
} catch (err) {
results.failed++;
}
}
return results;
}
/**
* Fetches message templates from Meta Graph API
*/
async fetchMetaTemplates(config: { accessToken: string; wabaId: string }) {
try {
const url = `${this.baseUrl}/${config.wabaId}/message_templates`;
const response = await axios.get(url, {
headers: { 'Authorization': `Bearer ${config.accessToken}` },
params: { limit: 100 }
});
return response.data.data;
} catch (err: any) {
logger.error({
error: err.response?.data || err.message,
wabaId: config.wabaId
}, '[WHATSAPP_SERVICE] Failed to fetch templates');
throw err;
}
}
/**
* Submits a new message template to Meta for approval
*/
async createMetaTemplate(config: { accessToken: string; wabaId: string }, template: any) {
try {
const url = `${this.baseUrl}/${config.wabaId}/message_templates`;
const response = await axios.post(url, template, {
headers: {
'Authorization': `Bearer ${config.accessToken}`,
'Content-Type': 'application/json'
}
});
return response.data;
} catch (err: any) {
logger.error({
error: err.response?.data || err.message,
wabaId: config.wabaId
}, '[WHATSAPP_SERVICE] Failed to create template');
throw err;
}
}
/**
* Initiates WhatsApp Business phone number registration.
* Meta sends an OTP to the phone number to verify ownership.
*/
async registerPhoneNumber(config: { accessToken: string }, phoneNumberId: string, pin: string = '000000') {
try {
const url = `${this.baseUrl}/${phoneNumberId}/register`;
const response = await axios.post(url, {
messaging_product: 'whatsapp',
pin,
}, {
headers: {
'Authorization': `Bearer ${config.accessToken}`,
'Content-Type': 'application/json',
}
});
return response.data;
} catch (err: any) {
logger.error({ error: err.response?.data || err.message, phoneNumberId }, '[WHATSAPP_SERVICE] registerPhoneNumber failed');
throw err;
}
}
/**
* Verifies the OTP code Meta sent during phone number registration.
*/
async verifyPhoneNumber(config: { accessToken: string }, phoneNumberId: string, code: string) {
try {
const url = `${this.baseUrl}/${phoneNumberId}/verify_code`;
const response = await axios.post(url, { code }, {
headers: {
'Authorization': `Bearer ${config.accessToken}`,
'Content-Type': 'application/json',
}
});
return response.data;
} catch (err: any) {
logger.error({ error: err.response?.data || err.message, phoneNumberId }, '[WHATSAPP_SERVICE] verifyPhoneNumber failed');
throw err;
}
}
/**
* Resolves a Meta Media ID into a permanent or temporary URL.
* This abstracts the two-step download process.
*/
async resolveMediaUrl(config: { accessToken: string }, mediaId: string): Promise<string> {
try {
const url = `${this.baseUrl}/${mediaId}`;
const response = await axios.get(url, {
headers: { 'Authorization': `Bearer ${config.accessToken}` }
});
return response.data.url;
} catch (err: any) {
logger.error({
error: err.response?.data || err.message,
mediaId
}, '[WHATSAPP_SERVICE] Failed to resolve media URL');
throw err;
}
}
/**
* Orchestrates the AI response loop and notifications for an incoming message
*/
async handleIncomingMessage(phone: string, text: string, audioUrl?: string, imageUrl?: string, _videoId?: string, organizationId?: string) {
if (!organizationId) {
logger.warn({ phone }, '[WHATSAPP_SERVICE] Cannot handle message without organizationId');
return;
}
try {
const { EntityResolver } = await import('./EntityResolver');
const { aiService } = await import('./ai');
const { pushService } = await import('./push');
const { decryptSecrets } = await import('./organization');
const { prisma } = await import('./prisma');
// 1. Resolve Entities (Standardized logic)
const { user, contact, organization } = await EntityResolver.resolve(phone, organizationId);
// 2. Decrypt config if present
const config = organization ? decryptSecrets(organization) : null;
const accessToken = config?.systemUserToken;
// 3. Auto-resolve Media IDs if they are IDs instead of URLs
let resolvedAudio = audioUrl;
let resolvedImage = imageUrl;
if (accessToken) {
if (audioUrl && !audioUrl.startsWith('http')) {
resolvedAudio = await this.resolveMediaUrl({ accessToken }, audioUrl).catch(() => audioUrl);
}
if (imageUrl && !imageUrl.startsWith('http')) {
resolvedImage = await this.resolveMediaUrl({ accessToken }, imageUrl).catch(() => imageUrl);
}
}
// 4. Log Message (Non-blocking)
if (user || contact) {
prisma.message.create({
data: {
content: text || '[Media]',
mediaUrl: resolvedAudio || resolvedImage,
direction: 'INBOUND',
userId: user?.id,
contactId: contact?.id,
organizationId
}
}).catch(err => logger.warn({ err }, '[WHATSAPP_SERVICE] Failed to log message'));
}
// 5. Process via AI Closing Engine
const { response } = await aiService.handleCrmConversation(phone, organizationId, text || '[Médias Reçus]');
// 6. Trigger Push Notification to the team
await pushService.notifyOrganization(
organizationId,
"Nouveau message WhatsApp",
`Le client ${phone} a répondu : "${(text || '').substring(0, 50)}..."`
).catch(e => logger.warn({ e }, "[PUSH] Failed to notify"));
// 7. Send automated response if possible
const phoneNumberId = organization?.phoneNumbers?.[0]?.id;
if (organization && phoneNumberId && accessToken) {
await this.sendMessage({
accessToken: accessToken,
phoneNumberId
}, { to: phone, text: response });
}
} catch (err) {
logger.error({ err, phone }, '[WHATSAPP_SERVICE] handleIncomingMessage failed');
}
}
}
export const whatsappService = new WhatsAppService();
|