Posts tagged with whatsapp

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));       }     })   } 

I have created a media template in what's app business API. But I cannot send the template message where the media file is attached in the header.

My media template object.

{     "name": "business_five",     "components": [         {             "type": "HEADER",             "format": "IMAGE",             "example": {                 "header_handle": [                     "https://scontent.whatsapp.net/v/t61.29466-34/323170987_1239753446972881_6537482729362490175_n.jpg?ccb=1-7&_nc_sid=57045b&_nc_ohc=24dzgQb3Xc8AX9Nllk_&_nc_ht=scontent.whatsapp.net&edm=AH51TzQEAAAA&oh=01_AdRx0hLfUqy4nKvgGz1cf23Em9ElezWo1o4UPrfwPGeVgg&oe=64336E79"                 ]             }         },         {             "type": "BODY",             "text": "Dear All,\nWishing you ramadan mubarak."         }     ],     "language": "en_US",     "status": "APPROVED",     "category": "MARKETING",     "id": "1235769690704590" } 

When I'm sending this template message to others using the API https://graph.facebook.com/{{version}}/{{phone_number_id}}/messages
it's showing the error :

(#132012) Parameter format does not match format in the created template

Can anyone help me with how can I send a media template message? My post field was

$message = [     "messaging_product" => "whatsapp",     "to" => "8801704158504",     "type" => "template",     "template" => [         "name" => $template->name,         "language" => [             "code" => $template->language         ],         "components" => [             [                 "type" => "header",                 "parameters" => [                     'type' => 'image',                     'image' => [                         'link' => 'https://imgur.com/a/wu3BP6R'                     ]                 ]             ]         ]     ] ]; 

I'm trying to implement whatsapp business API but I'm getting forbidden error I think its because i dont have enough permission. I have also implemented this code on Postman its works fine there but its not working in app i dont know why?

var client = new HttpClient();         var request = new HttpRequestMessage(HttpMethod.Post, "https://graph.facebook.com/v15.0/110474688636083/messages");         request.Headers.Add("Authorization", "Bearer EAAM2wERIcIsBAFSGQD3yCSYRd5II5u7hU1859z8VcpNFlZBjJrqJUR2QrgZADHlHYSCG0zWvpYqVkFlzea9TsN1wnu8ZBZBSiEaXQu5OZAQC63ufVKZAQDHZB25CIq3TBQ9rxr2DdZB1oZBgJtia4eAEBbzqfjwJpXm9M5SZCGhDh7JbK0s1ldz2Od099jHfKrFvnQDZD");         var content = new StringContent("{\n    \"messaging_product\": \"whatsapp\",\n    \"to\": \""+WHATSAPPNO+"\",\n    \"type\": \"template\",\n    \"template\": {\n        \"name\": \"hello_world\",\n        \"language\": {\n            \"code\": \"en_US\"\n        }\n    }\n}", null, "application/json");         request.Content = content;         var response = await client.SendAsync(request);         response.EnsureSuccessStatusCode();         Console.WriteLine(await response.Content.ReadAsStringAsync()); 

thank you for your time

Whatsapp (business) cloud API expires your chat session after 24 hours of inactivity. I developed a mini-app to use the API to send server alarms about the state of my machines, but when the (user-initiated) session is aging more than 24 hours the cloud API disables my notifications, it just silently drops all the messages (that I am sending via API) without any error code. Of course an alarm system can't be so unreliable so I need to keep the session with business test account (which sends all the messages) active before the API expires it.

How can I do it? I can't send messages on behalf of myself using the API, so how can you make the conversation active all the time programmatically so it never becomes inactive?

Or if there are any other methods to send Whatsapp messages programmatically all the time without manually initiating conversation with business account I would like to hear your suggestions.