0

I am creating a whatsapp business api app that replies to whatsapp messages with a messages I have received from my API. However, it is triggerring multiple times after the initial messages has been sent.

app.post("/webhook", (req, res) => {
  // Parse the request body from the POST
  let body = req.body;

  // Check the Incoming webhook message
  console.log(JSON.stringify(req.body, null, 2));

  // info on WhatsApp text message payload: https://developers.facebook.com/docs/whatsapp/cloud-api/webhooks/payload-examples#text-messages
  if (req.body.object) {
    if (
      req.body.entry &&
      req.body.entry[0].changes &&
      req.body.entry[0].changes[0] &&
      req.body.entry[0].changes[0].value.messages &&
      req.body.entry[0].changes[0].value.messages[0]
    ) {
      let phone_number_id =
        req.body.entry[0].changes[0].value.metadata.phone_number_id;
      let from = req.body.entry[0].changes[0].value.messages[0].from; // extract the phone number from the webhook payload
      let msg_body = req.body.entry[0].changes[0].value.messages[0].text.body; // extract the message text from the webhook payload
     axios({
    method: "POST",
    url: API_URL,
    data: {
      id: phone_number_id,
      question: msg_body,
      email: "N/A",
      conversation: [],
      save: true,
      resolved: "N/A",
      ads: 0,
    },
    headers: {
      "Content-Type": "application/json",
      "x-api-key": process.env.API_KEY,
    },
  })
    .then(apiResponse => {
      if (apiResponse.status !== 200) {
        throw new Error(`Request failed with status ${apiResponse.status}`);
      }
      return apiResponse.data;
    })
    .then(responseData => {
      console.log(responseData);
       axios({
            method: "POST",
            url: END_POINT_URL
            headers: {
              "Content-Type": "application/json",
              Authorization: TOKEN,             data: {
              to: from, 
              type: "text",
              text: {
                preview_url: false,
                body: responseData.answer, 
              },
              messaging_product: "whatsapp",
              recipient_type: "individual"
            },
          })
          .then(() => {
            // Confirm the message has been sent
            res.status(200).end();
          })
          .catch((error) => {
            console.error("Error sending WhatsApp message: ", error);
            res.status(500).end();
          });
    })
    .catch(error => {
      console.error(error);
      res.status(500).json({
        message: "An error occurred while chatting.",
      });
    });
    }
   
  } 
});

I have tried debugging but to no avail, sometimes the messages are sent at super random periods too

  • Make sure, it will trigger 3 separate status notifications for one message (sent, delivered, read) or error. – turivishal Sep 01 '23 at 06:09

0 Answers0