Posts under category Facebook WhatsApp Business API

I have a working WhatsApp Business API Project however I am facing a weird problem the Webhook URL that I provided in the Facebook Developers app is getting triggered automatically even without a message being sent.

Here is how is the flow of my Application:

1- The user sends the Message on WhatsApp Number 2- A Firebase Function is triggered which generates the reply 3- The user gets the reply back

This is working fine, however, if the user sends the message, it sends back the reply.

However, I see that the user is still able to get the reply back even without sending the message on the WhatsApp Business API Number.

During the development, I made a mistake when I deployed the code which had an error and maybe that is why it is in a loop to send back the same message.

Right now I am solving this problem by deleting the Facebook Developers App and recreating it again and changing the App Id, and Token again since I don't see any option to stop this.

I am sending the audio file from a WhatsApp voice message (WhatsApp business cloud API) to google speech to text recognition. The very weird thing is that it works for voice messages sent from a windows whatsapp client. So having the official WhatsApp windows WhatsApp program send a voice message does work. But it does not work when sending the voice message from an android whatsapp app. So there seems to be different encoding for the voice audio file. Both have Opus Audio codec and both have sample rate of 48000 Hz. Both files can be played with VLC, but the android file is much smaller Any help or ideas on that?

Not sure if that info helps: The working audio file from windows whatsapp desktop has bits per sample 32. The not working one from android has no information about bits per sample. Also the not working file is much smaller.

I'm trying to set up a webhook in my Google Cloud Function that can receive incoming messages from the WhatsApp Business API and forward them to platform called Front. However, when configuring the webhook on Meta for Whatsapp, I get the error The callback URL or verify token couldn't be validated. Please verify the provided information or try again later.

Here's the relevant code from my index.js file:

const axios = require('axios'); const FRONT_API_TOKEN = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzY29wZXMiOlsicHJvdmlzaW9uaW5nIiwicHJpdmF0ZToqIiwic2hhcmVkOioiXSwiaWF0IjoxNjc5NTE0MDU1LCJpc3MiOiJmcm9udCIsInN1YiI6ImI4MGUzZDExODQyMDUzZTk5OGE0IiwianRpIjoiYmM5NzNlNGQyZTA3YTAzMiJ9.7LBqJ5Kw3O65c4GttZuh4K2Zt7fkGIIq9yI96l06TJ8'; const FRONT_CUSTOM_CHANNEL_WEBHOOK_URL = 'https://api2.frontapp.com/channels/cha_ak6s0/incoming_messages'; const VERIFY_TOKEN = 'whatsappfronttoken'; const handleVerification = (req, res) => {   const queryToken = req.query.verify_token;   console.log('Verification request received:', req.query);   if (queryToken === VERIFY_TOKEN) {     res.send(req.query.challenge);   } else {     console.error('Invalid verify token:', queryToken);     res.sendStatus(403);   } }; exports.whatsappHandler = async (req, res) => {   if (req.query.verify_token) {     handleVerification(req, res);   } else {     const message = req.body;     if (!message.contacts || !message.messages) {       console.warn('Received message with missing contacts or messages property. Skipping message processing.');       res.sendStatus(200);       return;     }     // Extract relevant information from the WhatsApp message     const sender = message.contacts[0].profile.name || message.contacts[0].wa_id;     const text = message.messages[0].text.body;     // Format the message for Front's custom channel webhook URL     const formattedMessage = {       sender: {         name: sender,         handle: sender,       },       subject: 'WhatsApp Message',       body: text,       body_format: 'markdown',     };     // Forward the message to Front's custom channel webhook URL     try {       await axios.post(FRONT_CUSTOM_CHANNEL_WEBHOOK_URL, formattedMessage, {         headers: {           'Authorization': `Bearer ${FRONT_API_TOKEN}`,         },       });       res.sendStatus(200);     } catch (error) {       console.error(error);       res.sendStatus(500);     }   } }; 

What could be causing this issue, and how can I resolve it?

Any assistance or guidance would be greatly appreciated. Thank you!

I've confirmed that my WhatsApp Business API credentials and webhook URL are set up correctly. I've also verified that my Google Cloud Function is deployed and accessible.

I've checked the logs for my Google Cloud Function and when trying to verify the webhook, I see an error Received message with missing contacts or messages property. Skipping message processing. To bypass this, I tried to return a 200 status as I thought this could be caused by the fact that I was just verifying the webhook and not actually receiving an actual message from Meta.

I'm facing an error when creating a media template with sample image file. I'm following the developer facebook documentation: "https://developers.facebook.com/docs/whatsapp/business-management-api/message-templates/#message--media----interactive-templates" and the section is "Example Media Template Request".

I'm trying the following code.

My component code is :

[{"type":"header","format":"IMAGE","example":{"header_handle":["https://edailyshopping.com/images/download.jpg"]}},{"type":"body","text":"Wishing you all Ramadan Mubarak."}] 

API URL: https://graph.facebook.com/v16.0/{whatsapp-business-account-ID}/message_template

response is getting success.

**The problem is template is created but the sample media file is not uploaded. **

Can anyone any idea about it why the sample image is not uploaded?

I am using Whatsapp cloud API. I have configured the webhook with a valid URL. It is working properly. But the issue is that once I receive a message from the business and if I send back a message immediately, the callback URL not getting invoked instantly. It waits for three minutes to invoke the endpoint. And if I wait for 3 minutes after a response and then send a message then it invokes instantly. Not able to find the reason. Nothing in the documentation also. I want to make it faster. For all the messages, the webhook should be triggered instantly.

https://developers.facebook.com/docs/whatsapp/cloud-api/get-started This is the documentation I followed.

Any help would be highly appreciable. Thanks in advance.

I tried sending back 200 OK for all the requests as per the documentation

My server code looks like this:

const fs = require('fs'); const token = process.env.ACCESS_TOKEN; // Imports dependencies and set up http server const request = require("request"),   express = require("express"),   body_parser = require("body-parser"),   axios = require("axios").default,   app = express().use(body_parser.json()); // creates express http server // Sets server port and logs message on success var https = require('https'); var credentials = {     key: fs.readFileSync(process.env.key),     cert: fs.readFileSync(process.env.cert),     ca: fs.readFileSync(process.env.ca, 'utf-8') } var httpsServer = https.createServer(credentials, app); httpsServer.listen(process.env.PORT, async () => {   console.log("Whatsapp server listening to port: "+process.env.PORT);   // await mysqlConnector.initializeMySql(app);   // await redis.initializeRedis(); }); 

And my webhook post method looks like this:

app.post("/inbound", async (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 (       body.entry &&       body.entry[0].changes &&       body.entry[0].changes[0] &&       body.entry[0].changes[0].value.messages &&       body.entry[0].changes[0].value. Messages[0]     ) {       res.sendStatus(200);        //if the business needs to send a text message       //async function call to send a text message (It is a promise function that makes API call to the /message endpoint of WhatsApp business API)        // if the business needs to send an interactive message       //async function call to send interactive message(promise function)     //if the business needs to send a template     //async function call to send message template(Promise function) } } } 

And the function that send the text message:

 sendMessage: async function (message, incomingMessageFrom, outgoingMessageFrom, accessToken) {     return new Promise(async function (resolve, reject) {       try {         axios({           method: "POST",           url: "https://graph.facebook.com/v16.0/" +             outgoingMessageFrom +             "/messages?access_token=" +             accessToken,           data: {             messaging_product: "whatsapp",             "to": incomingMessageFrom,             "type": "text",             "text": {               "body": String(message)             }           },           headers: { "Content-Type": "application/json" }         }).then(response => {           resolve(response.data)         });       } catch (error) {         //log Error         resolve("error: " + JSON.stringify(error.message));       }     })   } 

And the function that sends the template:

 sendMessageTemplate: async function (templateName, params, incomingMessageFrom, outgoingMessageFrom, accessToken) {     await this.bindParams(params, templateName);     return new Promise(async function (resolve, reject) {       try {         //call bind params         let data = {           "messaging_product": "whatsapp",           "to": incomingMessageFrom,           "type": "template",           "template": templates[templateName]         }         let url = "https://graph.facebook.com/v12.0/" +         outgoingMessageFrom +         "/messages?access_token=" +         accessToken;         axios({           method: "POST", // Required, HTTP method, a string, e.g. POST, GET           url:url,           data: data,           headers: { "Content-Type": "application/json" },         }).then(response => {           resolve(response.data)         }).catch(err =>{           appLogger.logMessage("error","Failed to call template api due to: "+JSON.stringify(err.message),className,"sendMessageTemplate","ADMIN","Server",moduleName);         });         appLogger.logMessage("debug","The request data send is: "+JSON.stringify(data),className,"sendMessageTemplate","ADMIN","SERVER",moduleName);         appLogger.logMessage("debug","The request url send is: "+url,className,"sendMessageTemplate","ADMIN","SERVER",moduleName);       } catch (error) {         appLogger.logMessage("error","error occured while sending message template: "+JSON.stringify(error.message),"sendMessageTemplate","ADMIN","SERVER",moduleName);         //logError         resolve("error: " + JSON.stringify(error.message));       }     })   }