router_message_sendTemplate.js

const axios = require("axios");
const konfig = require("../../config.js");
const { KeiLog } = require('../../lib/Logger');

/**
 * Sets up an Express route for sending text template messages via WhatsApp.
 *
 * This function adds a GET route to the provided Express application. When accessed,
 * it constructs a WhatsApp message template with optional text parameters and sends it
 * using the WhatsApp Business API. The API response is then returned to the client.
 * This endpoint is specifically for sending text-based templates.
 *
 *@module sendtemplate
 * @param {Object} app - The Express application instance.
 */
module.exports = async function (app) {
  app.get("/sendtemplate", async (req, res) => {
    let msg = req.query.parameter;
    let template = req.query.template;
    let nmbr = req.query.number;

    let components = [];
    if (msg) {
      const params = msg.split(',');
      components.push({
        type: 'body',
        parameters: params.map(p => ({
          type: 'text',
          text: p.trim()
        }))
      });
    }

    let header = {
      "messaging_product": "whatsapp",
      "recipient_type": "individual",
      "to": nmbr,
      "type": "template",
      "template": {
        "name": template,
        "language": {
          "code": "en_US"
        }
      }
    };

    if (components.length > 0) {
      header["template"]["components"] = components;
    }

    const config = {
      method: 'post',
      maxBodyLength: Infinity,
      url: `https://graph.facebook.com/v14.0/${konfig.phone_id}/messages`,
      headers: { 
        'Content-Type': 'application/json', 
        'Authorization': "Bearer "+ konfig.token
      },
      data : header
    };

    try {
      const response = await axios(config);
      res.status(200).json({
        status : true,
        messages :response.data.messages[0].id
       });
       KeiLog("INFO", `Berhasil mengirim template ke ${nmbr}  dengan template ${template} `);
    } catch (error) {
      //console.log(error);
      KeiLog("ERROR", `Gagal mengirim template ke ${nmbr}  dengan template ${template} ${error}`);
       res.status(200).send({
        status : false,
        messages : error.response.data.error.message ?? error.message 
       });
    }
  });
};