adonisjs-whatsapp
Version:
Connect your WhatsApp Cloud API with AdonisJS
75 lines (74 loc) • 2.8 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const axios_1 = __importDefault(require("axios"));
class WhatsAppClient {
constructor(config) {
this.config = config;
this.headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + this.config.accessToken,
};
this.mandatory = {
messaging_product: 'whatsapp',
recipient_type: 'individual',
};
}
async send(data, parse = true) {
const { timeout, phoneNumberId, graphUrl, graphVersion } = this.config;
const response = await (0, axios_1.default)({
validateStatus: (status) => status <= 999,
method: 'POST',
url: `${graphUrl}/${graphVersion}/${phoneNumberId}/messages`,
timeout,
headers: this.headers,
data: { ...this.mandatory, ...data },
responseType: 'json',
});
if ('error' in response.data) {
throw new Error(response.data.error?.error_data?.details || response.data.error?.message);
}
return parse ? WhatsAppClient.parse(response.data) : response.data;
}
async media(media) {
const { timeout, graphUrl, graphVersion } = this.config;
const response = await (0, axios_1.default)({
validateStatus: (status) => status <= 999,
method: 'GET',
url: `${graphUrl}/${graphVersion}/${media}`,
timeout,
headers: this.headers,
responseType: 'json',
});
if ('error' in response.data) {
throw new Error(response.data.error?.error_data?.details || response.data.error?.message);
}
return response.data;
}
async upload(form) {
const { timeout, phoneNumberId, graphUrl, graphVersion } = this.config;
const response = await (0, axios_1.default)({
validateStatus: (status) => status <= 999,
method: 'POST',
url: `${graphUrl}/${graphVersion}/${phoneNumberId}/media`,
timeout,
headers: { ...form.getHeaders(), ...this.headers },
data: form,
responseType: 'json',
});
if ('error' in response.data) {
throw new Error(response.data.error?.error_data?.details || response.data.error?.message);
}
return response.data;
}
static parse(data) {
return {
input: Number(data.contacts[0].input),
phone: data.contacts[0].wa_id,
wamid: data.messages[0].id,
};
}
}
exports.default = WhatsAppClient;