feat: Associate WhatsApp Cloud API numbers by token in the database

gertec
adriano 2024-06-10 16:00:48 -03:00
parent 1d78de9dc9
commit e1e10d8226
10 changed files with 94 additions and 29 deletions

View File

@ -1,5 +1,4 @@
import { Request, Response } from "express"; import { Request, Response } from "express";
import whatsappOfficialAPI from "../helpers/WhatsappOfficialAPI";
import SetTicketMessagesAsRead from "../helpers/SetTicketMessagesAsRead"; import SetTicketMessagesAsRead from "../helpers/SetTicketMessagesAsRead";
import { getIO } from "../libs/socket"; import { getIO } from "../libs/socket";
@ -22,6 +21,7 @@ import Whatsapp from "../models/Whatsapp";
import checkLastClientMsg24hs from "../helpers/CheckLastClientMsg24hs"; import checkLastClientMsg24hs from "../helpers/CheckLastClientMsg24hs";
import AppError from "../errors/AppError"; import AppError from "../errors/AppError";
import { get } from "../helpers/RedisClient"; import { get } from "../helpers/RedisClient";
import createApiClientWhatsOfficial from "../helpers/WhatsappOfficialAPI";
type IndexQuery = { type IndexQuery = {
pageNumber: string; pageNumber: string;
@ -123,7 +123,12 @@ export const store = async (req: Request, res: Response): Promise<Response> => {
} }
} else { } else {
try { try {
const { wabaId }: any = await Whatsapp.findByPk(whatsappId); const { wabaId, whatsappOfficialToken }: any =
await Whatsapp.findByPk(whatsappId);
const whatsappOfficialAPI = createApiClientWhatsOfficial(
whatsappOfficialToken
);
const { data } = await whatsappOfficialAPI.get( const { data } = await whatsappOfficialAPI.get(
`/${process.env.VERSION}/${wabaId}/message_templates?language=pt_BR` `/${process.env.VERSION}/${wabaId}/message_templates?language=pt_BR`

View File

@ -36,7 +36,6 @@ import ShowUserService from "../services/UserServices/ShowUserService";
import fs from "fs"; import fs from "fs";
import receiveWhatsAppMediaOfficialAPI from "../helpers/ReceiveWhatsAppMediaOfficialAPI"; import receiveWhatsAppMediaOfficialAPI from "../helpers/ReceiveWhatsAppMediaOfficialAPI";
import whatsappOfficialAPI from "../helpers/WhatsappOfficialAPI";
import whatsappOfficialNumberInfo from "../helpers/WhatsappOfficialNumberInfo"; import whatsappOfficialNumberInfo from "../helpers/WhatsappOfficialNumberInfo";
import { getSettingValue } from "../helpers/WhaticketSettings"; import { getSettingValue } from "../helpers/WhaticketSettings";
import ListWhatsAppsNumber from "../services/WhatsappService/ListWhatsAppsNumber"; import ListWhatsAppsNumber from "../services/WhatsappService/ListWhatsAppsNumber";
@ -288,7 +287,8 @@ export const weebhook = async (
let filename = await receiveWhatsAppMediaOfficialAPI( let filename = await receiveWhatsAppMediaOfficialAPI(
mediaId, mediaId,
whatsapp.phoneNumberId whatsapp.phoneNumberId,
whatsapp.whatsappOfficialToken
); );
if (!filename) throw new AppError("There was an error"); if (!filename) throw new AppError("There was an error");

View File

@ -0,0 +1,14 @@
import { QueryInterface, DataTypes } from "sequelize";
module.exports = {
up: (queryInterface: QueryInterface) => {
return queryInterface.addColumn("Whatsapps", "whatsappOfficialToken", {
type: DataTypes.STRING,
allowNull: true
});
},
down: (queryInterface: QueryInterface) => {
return queryInterface.removeColumn("Whatsapps", "whatsappOfficialToken");
}
};

View File

@ -10,7 +10,6 @@ import {
import { writeFile } from "fs"; import { writeFile } from "fs";
import whatsappOfficialAPI from "./WhatsappOfficialAPI";
import path, { join } from "path"; import path, { join } from "path";
import { promisify } from "util"; import { promisify } from "util";
@ -18,14 +17,20 @@ import mime from "mime";
import fs from "fs"; import fs from "fs";
import { response } from "express"; import { response } from "express";
import createApiClientWhatsOfficial from "./WhatsappOfficialAPI";
const writeFileAsync = promisify(writeFile); const writeFileAsync = promisify(writeFile);
async function receiveWhatsAppMediaOfficialAPI( async function receiveWhatsAppMediaOfficialAPI(
mediaId: string, mediaId: string,
phoneNumberId: string phoneNumberId: string,
whatsappOfficialToken: string
) { ) {
try { try {
const whatsappOfficialAPI = createApiClientWhatsOfficial(
whatsappOfficialToken
);
const { data } = await whatsappOfficialAPI.get( const { data } = await whatsappOfficialAPI.get(
`/${process.env.VERSION}/${mediaId}?phone_number_id=${phoneNumberId}` `/${process.env.VERSION}/${mediaId}?phone_number_id=${phoneNumberId}`
); );
@ -33,7 +38,7 @@ async function receiveWhatsAppMediaOfficialAPI(
if (data && data?.url) { if (data && data?.url) {
const config: any = { const config: any = {
headers: { headers: {
Authorization: `Bearer ${process.env.TOKEN}` Authorization: `Bearer ${whatsappOfficialToken}`
}, },
responseType: "arraybuffer" responseType: "arraybuffer"
}; };

View File

@ -5,8 +5,6 @@ import Ticket from "../models/Ticket";
import Whatsapp from "../models/Whatsapp"; import Whatsapp from "../models/Whatsapp";
import endPointQuery from "./old_EndPointQuery"; import endPointQuery from "./old_EndPointQuery";
import whatsappOfficialAPI from "./WhatsappOfficialAPI";
export async function setMessageAsRead(ticket: Ticket) { export async function setMessageAsRead(ticket: Ticket) {
if (ticket?.phoneNumberId) { if (ticket?.phoneNumberId) {
return; return;

View File

@ -3,14 +3,28 @@ import https from "https"
import http from "http" import http from "http"
const api = axios.create({ // const api = axios.create({
// baseURL: process.env.URL_WHATSAPP_API,
// headers: {
// Accept: "application/json",
// Authorization: `Bearer ${process.env.TOKEN}`
// },
// httpAgent: new http.Agent({ keepAlive: true }),
// httpsAgent: new https.Agent({ keepAlive: true })
// });
// export default api;
const createApiClientWhatsOfficial = (token: string) => {
return axios.create({
baseURL: process.env.URL_WHATSAPP_API, baseURL: process.env.URL_WHATSAPP_API,
headers: { headers: {
Accept: "application/json", Accept: "application/json",
Authorization: `Bearer ${process.env.TOKEN}` Authorization: `Bearer ${token}`
}, },
httpAgent: new http.Agent({ keepAlive: true }), httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }) httpsAgent: new https.Agent({ keepAlive: true })
}); });
};
export default api; export default createApiClientWhatsOfficial;

View File

@ -1,7 +1,15 @@
import whatsappOfficialAPI from "./WhatsappOfficialAPI"; import Whatsapp from "../models/Whatsapp";
import createApiClientWhatsOfficial from "./WhatsappOfficialAPI";
async function whatsappOfficialNumberInfo(wabaId: string) { async function whatsappOfficialNumberInfo(wabaId: string) {
try { try {
const { whatsappOfficialToken }: any = await Whatsapp.findOne({
where: { wabaId }
});
const whatsappOfficialAPI = createApiClientWhatsOfficial(
whatsappOfficialToken
);
const { data } = await whatsappOfficialAPI.get( const { data } = await whatsappOfficialAPI.get(
`/${process.env.VERSION}/${wabaId}/phone_numbers` `/${process.env.VERSION}/${wabaId}/phone_numbers`
); );

View File

@ -1,3 +1,4 @@
import { where } from "sequelize";
import { getIO } from "../libs/socket"; import { getIO } from "../libs/socket";
import Contact from "../models/Contact"; import Contact from "../models/Contact";
import Ticket from "../models/Ticket"; import Ticket from "../models/Ticket";
@ -5,8 +6,9 @@ import {
isValidMsg, isValidMsg,
verifyMessage verifyMessage
} from "../services/WbotServices/wbotMessageListener"; } from "../services/WbotServices/wbotMessageListener";
import { get } from "./RedisClient";
import whatsappOfficialAPI from "./WhatsappOfficialAPI"; import createApiClientWhatsOfficial from "./WhatsappOfficialAPI";
import Whatsapp from "../models/Whatsapp";
async function sendWhatsAppMessageOfficialAPI( async function sendWhatsAppMessageOfficialAPI(
ticket: Ticket, ticket: Ticket,
@ -52,7 +54,14 @@ async function sendWhatsAppMessageOfficialAPI(
return; return;
} }
const { whatsappOfficialToken }: any = await Whatsapp.findOne({
where: { phoneNumberId }
});
console.log("SEND MESSAGE: ", JSON.stringify(data, null, 2)); console.log("SEND MESSAGE: ", JSON.stringify(data, null, 2));
const whatsappOfficialAPI = createApiClientWhatsOfficial(
whatsappOfficialToken
);
whatsappOfficialAPI whatsappOfficialAPI
.post(`/${process.env.VERSION}/${phoneNumberId}/messages`, data) .post(`/${process.env.VERSION}/${phoneNumberId}/messages`, data)

View File

@ -12,13 +12,14 @@ import {
import ffmpeg from "fluent-ffmpeg"; import ffmpeg from "fluent-ffmpeg";
import fs from "fs"; import fs from "fs";
import whatsappOfficialAPI from "./WhatsappOfficialAPI";
import path from "path"; import path from "path";
import { convertAudioToOgg } from "../helpers/ConvertAudio"; import { convertAudioToOgg } from "../helpers/ConvertAudio";
import { bytesToMB } from "./BytesToMB"; import { bytesToMB } from "./BytesToMB";
import isThisHour from "date-fns/esm/isThisHour/index"; import isThisHour from "date-fns/esm/isThisHour/index";
import AppError from "../errors/AppError"; import AppError from "../errors/AppError";
import createApiClientWhatsOfficial from "./WhatsappOfficialAPI";
import Whatsapp from "../models/Whatsapp";
async function sendWhatsMediaOfficialAPI( async function sendWhatsMediaOfficialAPI(
ticket: Ticket, ticket: Ticket,
@ -79,6 +80,14 @@ async function sendWhatsMediaOfficialAPI(
return; return;
} }
const { whatsappOfficialToken }: any = await Whatsapp.findOne({
where: { phoneNumberId }
});
const whatsappOfficialAPI = createApiClientWhatsOfficial(
whatsappOfficialToken
);
whatsappOfficialAPI whatsappOfficialAPI
.post(`/${process.env.VERSION}/${phoneNumberId}/messages`, data) .post(`/${process.env.VERSION}/${phoneNumberId}/messages`, data)
.then(response => { .then(response => {

View File

@ -87,6 +87,9 @@ class Whatsapp extends Model<Whatsapp> {
@UpdatedAt @UpdatedAt
updatedAt: Date; updatedAt: Date;
@Column
whatsappOfficialToken: string;
@HasMany(() => Ticket) @HasMany(() => Ticket)
tickets: Ticket[]; tickets: Ticket[];