@bonsaif/bonsaif-wa
Version:
Utileria para poder consumir servicios de WhatsApp CloudApi
360 lines (289 loc) • 10.9 kB
JavaScript
const fetch = require ('node-fetch');
const FormData = require('form-data');
const fs = require('fs');
const logger = require('./Logger');
const mime = require('mime');
class WAMetaServiceGupshup{
tokenAcceso = '';
app_id = '';
apiKey = '';
debug = false;
VERSION_DEFAULT = "";
constructor (options){
this.tokenAcceso = options.tokenAcceso;
this.apiKey = options.apiKey;
this.app_id = options.app_id;
this.version = options.version || this.VERSION_DEFAULT;
this.debug = options.debug || this.debug;
//logger.DEBUG = this.debug;
logger.DEBUG = this.debug;
}
//Obtener todos los templates
getTemplates(){
const tag = `ServiceGetTemplates`;
logger.log(tag);
const url_message_templates = `https://partner.gupshup.io/partner/app/${this.app_id}/templates`;
let obj = {
object: {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + this.tokenAcceso,
}
}
}
logger.log(`${tag} url ${url_message_templates}`);
return fetch(url_message_templates,obj.object);
}
//Obtener template por ID
getTemplate(objTemplate){
const tag = `ServiceGetTemplate`;
logger.log(tag);
let id_template = objTemplate.id_template || '';
const url_message_templates = `https://api.gupshup.io/wa/app/${this.app_id}/template/${id_template}`;
let obj = {
object: {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'apiKey': this.apiKey,
}
}
}
logger.log(`${tag} url ${url_message_templates}`);
return fetch(url_message_templates,obj.object);
}
//Insertar template
insertTemplate(template){
const tag = `ServiceInsertTemplate`;
logger.log(tag);
let urlencoded = new URLSearchParams(template);
let url_message_templates = "";
url_message_templates = `https://partner.gupshup.io/partner/app/${this.app_id}/templates`;
let obj = {
object: {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Bearer ' + this.tokenAcceso,
},
body : urlencoded
}
}
return fetch(url_message_templates,obj.object)
.then(res => res.json())
.then(data =>{
logger.log(data)
return data;
}).catch(error => {
logger.log(tag + 'error al procesar api', error);
});
}
updateTemplate(template,templateID){
const tag = `ServiceUpdateTemplate`;
logger.log(tag);
let urlencoded = new URLSearchParams(template);
let url_message_templates = "";
url_message_templates = `https://partner.gupshup.io/partner/app/${this.app_id}/templates/${templateID}`;
let obj = {
object: {
method: 'PUT',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Bearer ' + this.tokenAcceso,
},
body : urlencoded
}
}
return fetch(url_message_templates,obj.object)
.then(res => res.json())
.then(data =>{
logger.log(data)
return data;
}).catch(error => {
logger.log(tag + 'error al procesar api', error);
});
}
deleteTemplate(name){
const tag = "ServiceDeleteTemplate";
const url_message_templates = `https://partner.gupshup.io/partner/app/${this.app_id}/template/${name}`;
let obj = {
object: {
method: 'DELETE',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + this.tokenAcceso,
}
}
}
return fetch(url_message_templates, obj.object)
.then(res => res.json())
.then(data =>{
logger.log(data)
return data;
}).catch(error => {
logger.log(tag + 'error al procesar api', error);
});
}
getAccountDetails(){
const tag = `getAccountDetails`;
logger.log(tag);
const url = `https://partner.gupshup.io/partner/app/${this.app_id}/waba/info`;
let requestOptions = {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + this.tokenAcceso,
}
}
return fetch(url, requestOptions)
.then(response => response.json())
.then(result => {
if (result.status == 'error') { return [] }
const data = result;
return data;
})
.catch(error => console.log('error', error));
}
async sendMessageMeta(body){
const tag = `ServiceSendMessageMeta`;
logger.log(tag);
const respMeta = new Array();
const resp = new Array();
const url_send_message = `https://api.gupshup.io/wa/api/v1/msg`;
if(typeof body === 'object' && Array.isArray(body)){
for(let index = 0; index < body.length; index ++){
let bodyMessage = new URLSearchParams(body[index]);
let obj = {
object: {
method: 'POST',
redirect: 'follow',
body: bodyMessage,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
'apiKey': this.apiKey
}
}
}
respMeta[index] = await fetch(url_send_message, obj.object)
.then(res => res.json())
.then(data =>{
return data;
}).catch(error => {
logger.log(tag + 'error al enviar mensaje', error);
});
resp[index] = [{body: body[index], resp: respMeta[index]}]
}
return resp;
}else{
logger.log(tag + ' Metodo de entrada no es un Array');
}
}
sendMessageTemplate(bodyMessage){
const tag = `sendMessageTemplate`;
logger.log(tag);
let urlencoded = new URLSearchParams(bodyMessage);
const url_send_message = `https://partner.gupshup.io/partner/app/${this.app_id}/template/msg`;
let obj = {
method: 'POST',
redirect: 'follow',
body: urlencoded,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
'Cache-Control': 'max-age=3600',//Para mantenerlo en cache por 3600 segundos para alguna peticion posterior que utlice imagenes/documentos/videos
'Authorization': 'Bearer ' + this.tokenAcceso
}
}
return fetch(url_send_message, obj);
}
async uploadMedia(mediaTemplate){
const tag = `uploadMedia`;
const path = mediaTemplate.path || '';
if(path == ''){
return {Error: 'No se encontro path'}
}
let mimeType = ""
const formData = new FormData();
try{
mimeType = mime.getType(path);
formData.append('file_type', mimeType);
formData.append('file', fs.readFileSync(path));
}catch(e){
return {Error: e}
}
const url = `https://partner.gupshup.io/partner/app/${this.app_id}/upload/media`;
const requestOptions = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Authorization': 'Bearer ' + this.tokenAcceso
},
body: formData
};
return fetch(url, requestOptions)
.then(res => res.json())
.then(data => {
logger.log(`${tag} data: `, data);
return data;
})
.catch(error => {
logger.log(tag + ' error al procesar api', error);
});
}
unsubscribeWebhook(){
const tag = `unsubscribeWebhook`;
const url = `https://partner.gupshup.io/partner/app/${this.app_id}/subscription`;
const requestOptions = {
method: 'DELETE',
redirect: 'follow',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Bearer ' + this.tokenAcceso
}
}
return fetch(url, requestOptions)
.then(res => res.json())
.then(data => {
logger.log(`${tag} data: `, data);
return data;
})
.catch(error => {
logger.log(tag + ' error al procesar api', error);
});
}
subscribeWebhook(obj){
const tag = `unsubscribeWebhook`;
let urlencoded = new URLSearchParams(obj);
const url = `https://partner.gupshup.io/partner/app/${this.app_id}/subscription`;
const requestOptions = {
method: 'POST',
redirect: 'follow',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Bearer ' + this.tokenAcceso
},
body: urlencoded
}
return fetch(url, requestOptions)
.then(res => res.json())
.then(data => {
logger.log(`${tag} data: `, data);
return data;
})
.catch(error => {
logger.log(tag + ' error al procesar api', error);
});
}
}
module.exports = {WAMetaServiceGupshup};