whatsappCloudClient.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import axios from "axios";
  2. import axiosRetry from "axios-retry";
  3. import { config } from "../config/index.js";
  4. function client() {
  5. const instance = axios.create({
  6. baseURL: `https://graph.facebook.com/${config.whatsapp.apiVersion}`,
  7. timeout: 15_000,
  8. headers: { Authorization: `Bearer ${config.whatsapp.token}` }
  9. });
  10. axiosRetry(instance, {
  11. retries: 2,
  12. retryDelay: axiosRetry.exponentialDelay,
  13. retryCondition: (error) => !error.response && (error.code === "ECONNABORTED" || axiosRetry.isNetworkError(error))
  14. });
  15. return instance;
  16. }
  17. export async function enviarTexto(paraTelefone, texto) {
  18. const { data } = await client().post(`/${config.whatsapp.phoneNumberId}/messages`, {
  19. messaging_product: "whatsapp",
  20. recipient_type: "individual",
  21. to: paraTelefone,
  22. type: "text",
  23. text: { preview_url: false, body: texto }
  24. });
  25. return data;
  26. }
  27. export async function obterUrlMidia(mediaId) {
  28. const { data } = await client().get(`/${mediaId}`);
  29. return data;
  30. }
  31. export async function baixarBytesMidia(url) {
  32. const { data, headers } = await client().get(url, { responseType: "arraybuffer" });
  33. return { buffer: Buffer.from(data), mimetype: headers["content-type"] ?? null };
  34. }
  35. export async function obterInfoNumero() {
  36. const { data } = await client().get(`/${config.whatsapp.phoneNumberId}`, {
  37. params: { fields: "verified_name,display_phone_number,quality_rating" }
  38. });
  39. return data;
  40. }