Posts tagged with node.js

I was doing coding in node js but in that it there is requirement of setup like that

APP_ID=<<YOUR-WHATSAPP-BUSINESS-APP_ID>> APP_SECRET=<<YOUR-WHATSAPP-BUSINESS-APP_SECRET>> RECIPIENT_WAID=<<YOUR-RECIPIENT-TEST-PHONE-NUMBER>> VERSION=v13.0 PHONE_NUMBER_ID=<<YOUR-WHATSAPP-BUSINESS-PHONE-NUMBER-ID>> ACCESS_TOKEN=<<YOUR-SYSTEM-USER-ACCESS-TOKEN>>   

I got all credential accept app_secret. I am unable to find that if anyone know how can I get app_secret please let me know.

Thanks in advance.

I searched on dashboard but couldn't find that.

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 a problem with my nodejs code and the connection to the official whatsapp business api.

The bot connects the webhook correctly, the messages arrive to the server correctly but the code I have implemented to make it respond is not being effective, I checked the code from top to bottom but I can't find the fault.

I leave you the codes so you have more context:

whatsappController.js:

const fs = require("fs"); const myConsole = new console.Console(fs.createWriteStream("./logs.txt")); const whatsappService = require("../services/whatsappService") const VerifyToken = (req, res) => {     try {         var accessToken = "456E7GR****************************";         var token = req.query["hub.verify_token"];         var challenge = req.query["hub.challenge"];         if(challenge != null && token != null && token == accessToken){             res.send(challenge);         }         else{             res.status(400).send();         }     } catch(e) {         res.status(400).send();     } } const ReceivedMessage = (req, res) => {     try {         var entry = (req.body["entry"])[0];         var changes = (entry["changes"])[0];         var value = changes["value"];         var messageObject = value["messages"];         if(typeof messageObject != "undefined"){             var messages = messageObject[0];             var text = GetTextUser(messages);             var number = messages["from"];             myConsole.log("Message: " + text + " from: " + number);             whatsappService.SendMessageWhatsApp("The user say: " + text, number);                          myConsole.log(messages);             myConsole.log(messageObject);         }         res.send("EVENT_RECEIVED");     }catch(e) {         myConsole.log(e);         res.send("EVENT_RECEIVED");     } } function GetTextUser(messages){     var text = "";     var typeMessage = messages["type"];     if(typeMessage == "text"){         text = (messages["text"])["body"];     }     else if(typeMessage == "interactive"){         var interactiveObject = messages["interactive"];         var typeInteractive = interactiveObject["type"];         if(typeInteractive == "button_reply"){             text = (interactiveObject["button_reply"])["title"];         }         else if(typeInteractive == "list_reply"){             text = (interactiveObject["list_reply"])["title"];         }else{             myConsole.log("sin mensaje");         }     }else{         myConsole.log("sin mensaje");     }     return text; } module.exports = {     VerifyToken,     ReceivedMessage } 

The second file is whatsappService which I make the connection with the api using the token and I also send the format of the message I want to send when I receive a hello for example...

const https = require("https"); function SendMessageWhatsApp(textResponse, number){     const data = JSON.stringify({         "messaging_product": "whatsapp",             "recipient_type": "individual",         "to": number,         "type": "text",         "text": {             "preview_url": false,             "body": textResponse         }     });     const options = {         host:"graph.facebook.com",         path:"/v15.0/1119744*************/messages",         method:"POST",         body:data,         headers: {             "Content-Type":"application/json",             Authorization:"Bearer EAAWNbICfuWEBAK5ObPbD******************************************************"         }     };     const req = https.request(options, res => {         res.on("data", d=> {             process.stdout.write(d);         });     });     req.on("error", error => {         console.error(error);     });     req.write(data);     req.end(); } module.exports = {     SendMessageWhatsApp }; 

Then I declare the routes for the get (to check token) and post (to receive and reply to messages) methods:

const expres = require("express"); const router = expres.Router(); const whatsappController = require("../controllers/whatsappControllers"); router .get("/", whatsappController.VerifyToken) .post("/", whatsappController.ReceivedMessage) module.exports = router; 

Last but not least the index file for the code to run correctly:

const express = require("express"); const apiRoute = require("./routes/routes"); const app = express(); const PORT = process.env.PORT || 3000 app.use(express.json()); app.use("/whatsapp", apiRoute); app.listen(PORT, () => (console.log("El puerto es: " + PORT))); 

I should clarify that I did the tests with Postman and they were all successful, it responds and receives messages correctly, finally I did the tests by uploading the bot to the Azure service and it works without problem until it has to answer/replicate the user's message.

The bot is not responding to the user when he talks to it but everything arrives correctly to the server and it processes it with a 200 response. I attach the evidence that there is no problem in the reception.

Finally I must say that in the meta platform I have everything configured as specified by the same platform, I have already configured the api to answer the messages through the webhooks and everything is correct, I just can't get the bot to answer correctly.

The bot is hosted in the Azure service.

I am trying to implement Google ads enhanced conversions. I have the option of doing it using the gtag, google tag manager or using the Ads api. However, On the Ads api I don't see any documentation related to Node Js. I am not able to figure out how I can make use of the Ads api to implement enhanced conversions with Node Js.

This is the official documentation for enhanced conversion using Ads api and i don't see anything related to Node Js

https://developers.google.com/google-ads/api/docs/conversions/enhance-conversions

Can someone please clarify which is the correct WhatsApp Business Account ID to use to access the WhatsApp cloud API?

I have properly set up my webhook and can receive messages. However when I try to send a message using the WhatsApp Business Account ID (marked as number 1 in the attached image) provided here, I get the following error:

error: {     message:       "Unsupported post request. Object with ID '< my app id>' does not exist, cannot be loaded due to missing permissions, or does not support this operation. Please read the Graph API documentation at https://developers.facebook.com/docs/graph-api",     type: "GraphMethodException",     code: 100,     error_subcode: 33,     fbtrace_id: "AQXqjuSJKTWBnyJdUK_W-jj", },  

However when I switch to the second WhatsApp Business Account ID in the curl command (marked as number 2 in the attached image), it works.

What confuses me is that the incoming message has the first WhatsApp Business Account ID (marked number 1 in the attached image) like so:

message: {   object: "whatsapp_business_account",   entry: [     {       id: "xxxxxxxxxxxxxxx",  // This matches the first       changes: [           ...       ],     },   ], }; 

I am using the current api v14.0. Is there some setting I need to change?