diff --git a/src/api/controllers/instance.controller.ts b/src/api/controllers/instance.controller.ts index 556caed9..3a4499f2 100644 --- a/src/api/controllers/instance.controller.ts +++ b/src/api/controllers/instance.controller.ts @@ -392,7 +392,7 @@ export class InstanceController { throw new BadRequestException('number is required'); } const urlServer = this.configService.get('SERVER').URL; - webhookWaBusiness = `${urlServer}/webhook/whatsapp/${encodeURIComponent(instance.instanceName)}`; + webhookWaBusiness = `${urlServer}/webhook/meta`; accessTokenWaBusiness = this.configService.get('WA_BUSINESS').TOKEN_WEBHOOK; } diff --git a/src/api/controllers/webhook.controller.ts b/src/api/controllers/webhook.controller.ts index 8eb0174e..4eea4497 100644 --- a/src/api/controllers/webhook.controller.ts +++ b/src/api/controllers/webhook.controller.ts @@ -56,7 +56,12 @@ export class WebhookController { return this.webhookService.find(instance); } - public async receiveWebhook(instance: InstanceDto, data: any) { - return await this.waMonitor.waInstances[instance.instanceName].connectToWhatsapp(data); + public async receiveWebhook(data: any) { + console.log('webhook/meta', data); + this.webhookService.receiveWebhook(data); + + return { + message: 'Webhook received', + }; } } diff --git a/src/api/routes/index.router.ts b/src/api/routes/index.router.ts index 59007b58..afffb8e3 100644 --- a/src/api/routes/index.router.ts +++ b/src/api/routes/index.router.ts @@ -1,7 +1,7 @@ import { Router } from 'express'; import fs from 'fs'; -import { configService } from '../../config/env.config'; +import { configService, WaBusiness } from '../../config/env.config'; import { authGuard } from '../guards/auth.guard'; import { instanceExistsGuard, instanceLoggedGuard } from '../guards/instance.guard'; import { ChatwootRouter } from '../integrations/chatwoot/routes/chatwoot.router'; @@ -9,6 +9,7 @@ import { RabbitmqRouter } from '../integrations/rabbitmq/routes/rabbitmq.router' import { SqsRouter } from '../integrations/sqs/routes/sqs.router'; import { TypebotRouter } from '../integrations/typebot/routes/typebot.router'; import { WebsocketRouter } from '../integrations/websocket/routes/websocket.router'; +import { webhookController } from '../server.module'; import { ChatRouter } from './chat.router'; import { GroupRouter } from './group.router'; import { InstanceRouter } from './instance.router'; @@ -59,6 +60,17 @@ router .use('/sqs', new SqsRouter(...guards).router) .use('/typebot', new TypebotRouter(...guards).router) .use('/proxy', new ProxyRouter(...guards).router) - .use('/label', new LabelRouter(...guards).router); + .use('/label', new LabelRouter(...guards).router) + .get('/webhook/meta', async (req, res) => { + if (req.query['hub.verify_token'] === configService.get('WA_BUSINESS').TOKEN_WEBHOOK) + res.send(req.query['hub.challenge']); + else res.send('Error, wrong validation token'); + }) + .post('/webhook/meta', async (req, res) => { + const { body } = req; + const response = await webhookController.receiveWebhook(body); + + return res.status(200).json(response); + }); export { HttpStatus, router }; diff --git a/src/api/routes/webhook.router.ts b/src/api/routes/webhook.router.ts index db930620..a442d43f 100644 --- a/src/api/routes/webhook.router.ts +++ b/src/api/routes/webhook.router.ts @@ -1,6 +1,6 @@ import { RequestHandler, Router } from 'express'; -import { ConfigService, WaBusiness } from '../../config/env.config'; +import { ConfigService } from '../../config/env.config'; import { instanceSchema, webhookSchema } from '../../validate/validate.schema'; import { RouterBroker } from '../abstract/abstract.router'; import { InstanceDto } from '../dto/instance.dto'; @@ -31,21 +31,6 @@ export class WebhookRouter extends RouterBroker { }); res.status(HttpStatus.OK).json(response); - }) - .post(this.routerPath('whatsapp'), async (req, res) => { - const response = await this.dataValidate({ - request: req, - schema: instanceSchema, - ClassRef: InstanceDto, - execute: (instance, data) => webhookController.receiveWebhook(instance, data), - }); - - res.status(HttpStatus.OK).json(response); - }) - .get(this.routerPath('whatsapp'), async (req, res) => { - if (req.query['hub.verify_token'] === this.configService.get('WA_BUSINESS').TOKEN_WEBHOOK) - res.send(req.query['hub.challenge']); - else res.send('Error, wrong validation token'); }); } diff --git a/src/api/server.module.ts b/src/api/server.module.ts index 75b2ee53..505d2f83 100644 --- a/src/api/server.module.ts +++ b/src/api/server.module.ts @@ -61,7 +61,7 @@ const authService = new AuthService(prismaRepository); const typebotService = new TypebotService(waMonitor, configService, prismaRepository); export const typebotController = new TypebotController(typebotService); -const webhookService = new WebhookService(waMonitor); +const webhookService = new WebhookService(waMonitor, prismaRepository); export const webhookController = new WebhookController(webhookService, waMonitor); const websocketService = new WebsocketService(waMonitor); diff --git a/src/api/services/monitor.service.ts b/src/api/services/monitor.service.ts index 16e05c61..1df76fe5 100644 --- a/src/api/services/monitor.service.ts +++ b/src/api/services/monitor.service.ts @@ -187,7 +187,7 @@ export class WAMonitoringService { data: { id: data.instanceId, name: data.instanceName, - connectionStatus: 'close', + connectionStatus: data.integration && data.integration === Integration.WHATSAPP_BUSINESS ? 'open' : 'close', number: data.number, integration: data.integration || Integration.WHATSAPP_BAILEYS, token: data.hash, diff --git a/src/api/services/webhook.service.ts b/src/api/services/webhook.service.ts index 2a087baf..70307e54 100644 --- a/src/api/services/webhook.service.ts +++ b/src/api/services/webhook.service.ts @@ -3,10 +3,11 @@ import { Webhook } from '@prisma/client'; import { Logger } from '../../config/logger.config'; import { InstanceDto } from '../dto/instance.dto'; import { WebhookDto } from '../dto/webhook.dto'; +import { PrismaRepository } from '../repository/repository.service'; import { WAMonitoringService } from './monitor.service'; export class WebhookService { - constructor(private readonly waMonitor: WAMonitoringService) {} + constructor(private readonly waMonitor: WAMonitoringService, public readonly prismaRepository: PrismaRepository) {} private readonly logger = new Logger(WebhookService.name); @@ -29,4 +30,32 @@ export class WebhookService { return null; } } + + public async receiveWebhook(data: any) { + if (data.object === 'whatsapp_business_account') { + data.entry?.forEach(async (entry: any) => { + const numberId = entry.changes[0].value.metadata.phone_number_id; + + if (!numberId) { + this.logger.error('WebhookService -> receiveWebhook -> numberId not found'); + return; + } + + const instance = await this.prismaRepository.instance.findFirst({ + where: { number: numberId }, + }); + + if (!instance) { + this.logger.error('WebhookService -> receiveWebhook -> instance not found'); + return; + } + + await this.waMonitor.waInstances[instance.name].connectToWhatsapp(data); + + return; + }); + } + + return; + } }