Search code examples
node.jsfacebookwebhookswhatsappwhatsapp-cloud-api

Can't return response via webhook with Whatsapp Business Cloud API


I am trying to return a response generated from an API call via whatsapp through the use of the Whatsapp business cloud API and a webhook. I can log the message and it is correct however when I return it by using the webhook it does not then get sent in Whatsapp. Here is my code:

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);
      res.status(200).json({
        message: responseData.answer,
      });
    })
    .catch(error => {
      console.error(error);
      res.status(500).json({
        message: "An error occurred while chatting.",
      });
    });
    }
   
  } 
});

As you can see I am console logging the responseData and it is showing me a good response. But as mentioned when I return it it does not then get sent to the whatsapp phone number that it received the initial post request from.

I am trying to achieve this whole process by using Meta For Developers and their docs for the Whatsapp business Cloud API but can't figure it out.


Solution

  • It looks like you're receiving the webhook from WhatsApp, making a call to your own API, and then returning the answer as a JSON response to the original webhook request. However, this doesn't send a message back through WhatsApp to the user; the webhook request is simply acknowledging that you've successfully received a message.

    To send a message back to the user, you'll typically have to make a POST request to the WhatsApp API with the necessary parameters, such as the recipient phone number and message body. You should do this within your code where you're handling the webhook POST request.

    <pre>
        app.post("/webhook", (req, res) => {
          // Parse the request body from the POST
          let body = req.body;
        
          // Log the incoming webhook message
          console.log(JSON.stringify(req.body, null, 2));
        
          // ... (existing code to extract phone_number_id, from, and msg_body)
        
          // Make a request to your API
          axios({
            method: "POST",
            url: API_URL,
            // ... (existing code)
          })
            .then(apiResponse => {
              // ... (existing code)
            })
            .then(responseData => {
              // Log the answer received from your API
              console.log(responseData);
        
              // Prepare to send the message back to the user via WhatsApp API
              axios({
                method: "POST",
                url: "YOUR_WHATSAPP_API_ENDPOINT_HERE", // Replace with the correct endpoint URL
                headers: {
                  "Content-Type": "application/json",
                  Authorization: `Bearer YOUR_WHATSAPP_ACCESS_TOKEN_HERE`, // Replace with your token
                },
                data: {
                  to: from, // The phone number of the user who sent the message
                  type: "text",
                  text: {
                    body: responseData.answer, // The answer to send back
                  },
                },
              })
              .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 => {
              // ... (existing code)
            });
        });
    
    </pre>