Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@ CORS_METHODS=GET,POST,PUT,DELETE
CORS_CREDENTIALS=true

# Determine the logs to be displayed
LOG_LEVEL=ERROR,WARN,DEBUG,INFO,LOG,VERBOSE,DARK,WEBHOOKS,WEBSOCKET
# WEBHOOKMETA logs the full incoming Meta payload, including message content and contact data.
LOG_LEVEL=ERROR,WARN,DEBUG,INFO,LOG,VERBOSE,DARK,WEBHOOKS,WEBSOCKET,WEBHOOKMETA
LOG_COLOR=true
# Log Baileys - "fatal" | "error" | "warn" | "info" | "debug" | "trace"
LOG_BAILEYS=error
Expand Down
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@ lerna-debug.log*
# Project related
/instances/*
!/instances/.gitkeep
/test/
/test/*
!/test/meta-message-status.test.cjs
/src/env.yml
/store
*.env
Expand Down
2 changes: 1 addition & 1 deletion prisma/mysql-schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ model Instance {
integration String? @db.VarChar(100)
number String? @db.VarChar(100)
businessId String? @db.VarChar(100)
token String? @db.VarChar(255)
token String? @db.Text
clientName String? @db.VarChar(100)
disconnectionReasonCode Int? @db.Int
disconnectionObject Json? @db.Json
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "Instance" ALTER COLUMN "token" SET DATA TYPE TEXT;
2 changes: 1 addition & 1 deletion prisma/postgresql-migrations/migration_lock.toml
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (e.g., Git)
provider = "postgresql"
provider = "postgresql"
2 changes: 1 addition & 1 deletion prisma/postgresql-schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ model Instance {
integration String? @db.VarChar(100)
number String? @db.VarChar(100)
businessId String? @db.VarChar(100)
token String? @db.VarChar(255)
token String? @db.Text
clientName String? @db.VarChar(100)
disconnectionReasonCode Int? @db.Integer
disconnectionObject Json? @db.JsonB
Expand Down
132 changes: 98 additions & 34 deletions src/api/integrations/channel/meta/meta.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,54 +15,118 @@ export class MetaController extends ChannelController implements ChannelControll
integrationEnabled: boolean;

public async receiveWebhook(data: any) {
if (data.object === 'whatsapp_business_account') {
if (data.entry[0]?.changes[0]?.field === 'message_template_status_update') {
const template = await this.prismaRepository.template.findFirst({
where: { templateId: `${data.entry[0].changes[0].value.message_template_id}` },
});
if (data.object !== 'whatsapp_business_account') {
return {
status: 'success',
};
}

if (!template) {
console.log('template not found');
return;
}
const entries = data.entry ?? [];

const { webhookUrl } = template;
for (const entry of entries) {
const changes = entry.changes ?? [];

await axios.post(webhookUrl, data.entry[0].changes[0].value, {
headers: {
'Content-Type': 'application/json',
},
});
return;
}
for (const change of changes) {
if (change?.field === 'message_template_status_update') {
const templateId = change?.value?.message_template_id;

if (!templateId) {
this.logger.error('WebhookService -> receiveWebhookMeta -> templateId not found');
continue;
}

const template = await this.prismaRepository.template.findFirst({
where: {
templateId: String(templateId),
},
});

if (!template) {
this.logger.error(`WebhookService -> receiveWebhookMeta -> template not found: ${templateId}`);
continue;
}

if (!template.webhookUrl) {
this.logger.error(`WebhookService -> receiveWebhookMeta -> template webhookUrl not found: ${templateId}`);
continue;
}

try {
await axios.post(template.webhookUrl, change.value, {
headers: {
'Content-Type': 'application/json',
},
});
} catch (error) {
this.logger.error(
`WebhookService -> receiveWebhookMeta -> error sending template webhook: ${
error instanceof Error ? error.message : String(error)
}`,
);
}

continue;
}

data.entry?.forEach(async (entry: any) => {
const numberId = entry.changes[0].value.metadata.phone_number_id;
const numberId = change?.value?.metadata?.phone_number_id;

if (!numberId) {
this.logger.error('WebhookService -> receiveWebhookMeta -> numberId not found');
return {
status: 'success',
};
continue;
}

const instance = await this.prismaRepository.instance.findFirst({
where: { number: numberId },
const instances = await this.prismaRepository.instance.findMany({
where: {
number: String(numberId),
},
});

if (!instance) {
this.logger.error('WebhookService -> receiveWebhookMeta -> instance not found');
return {
status: 'success',
};
if (!instances.length) {
this.logger.error(`WebhookService -> receiveWebhookMeta -> instances not found for numberId: ${numberId}`);
continue;
}

await this.waMonitor.waInstances[instance.name].connectToWhatsapp(data);

return {
status: 'success',
const webhookData = {
...data,
entry: [
{
...entry,
changes: [change],
},
],
};
});

const results = await Promise.allSettled(
instances.map(async (instance) => {
const waInstance = this.waMonitor.waInstances[instance.name];

if (!waInstance) {
throw new Error(`Instance not loaded: ${instance.name}`);
}

await waInstance.connectToWhatsapp(webhookData);

return instance.name;
}),
);

results.forEach((result, index) => {
const instanceName = instances[index].name;

if (result.status === 'rejected') {
this.logger.error(
`WebhookService -> receiveWebhookMeta -> error processing webhook for instance ${instanceName}: ${
result.reason instanceof Error ? result.reason.message : String(result.reason)
}`,
);
return;
}

this.logger.log(
`WebhookService -> receiveWebhookMeta -> webhook processed successfully for instance ${instanceName}`,
);
});
}
}

return {
Expand Down
8 changes: 7 additions & 1 deletion src/api/integrations/channel/meta/meta.router.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import { RouterBroker } from '@api/abstract/abstract.router';
import { metaController } from '@api/server.module';
import { ConfigService, WaBusiness } from '@config/env.config';
import { ConfigService, Log, WaBusiness } from '@config/env.config';
import { Logger } from '@config/logger.config';
import { Router } from 'express';

export class MetaRouter extends RouterBroker {
private readonly logger = new Logger('MetaRouter');

constructor(readonly configService: ConfigService) {
super();
this.router
Expand All @@ -14,6 +17,9 @@ export class MetaRouter extends RouterBroker {
})
.post(this.routerPath('webhook/meta', false), async (req, res) => {
const { body } = req;
if (this.configService.get<Log>('LOG').LEVEL.includes('WEBHOOKMETA')) {
this.logger.webhookMeta(JSON.stringify(body));
}
const response = await metaController.receiveWebhook(body);

return res.status(200).json(response);
Expand Down
Loading