(https://i.sstatic.net/gVF6HTIz.png) (https://i.sstatic.net/GPabyiiQ.png)
I am trying to integrate the Whatsapp API Webhook on a Node.JS server on cPanel. I have copied the code from the docs and it works perfectly on Glitch. The server starts fine but when I try to add the webhook on the facebook app page, there is no request received on the Node.JS server. These are the packages I have in package.json:
-
"@google-cloud/local-auth": "^2.1.0",
-
"axios": "^1.7.2",
-
"dotenv": "^16.4.5",
-
"express": "^4.19.2",
-
"google-auth-library": "^9.10.0",
-
"googleapis": "^105.0.0",
-
"googleapis-common": "^7.2.0"
This is the code for my server.js:
import express from "express";
import axios from "axios";
import dotenv from 'dotenv';
dotenv.config();
console.log("WEBHOOK_VERIFY_TOKEN:", process.env.WEBHOOK_VERIFY_TOKEN);
console.log("GRAPH_API_TOKEN:", process.env.GRAPH_API_TOKEN);
console.log("PORT:", process.env.PORT);
const app = express();
app.use(express.json());
const { WEBHOOK_VERIFY_TOKEN, GRAPH_API_TOKEN, PORT = 3000 } = process.env;
app.post("/webhook", async (req, res) => {
console.log("Incoming webhook message:", JSON.stringify(req.body, null, 2));
const message = req.body.entry?.[0]?.changes[0]?.value?.messages?.[0];
if (message?.type === "text") {
const business_phone_number_id =
req.body.entry?.[0].changes?.[0].value?.metadata?.phone_number_id;
try {
await axios({
method: "POST",
url: `https://graph.facebook.com/v20.0/${business_phone_number_id}/messages`,
headers: {
Authorization: `Bearer ${GRAPH_API_TOKEN}`,
},
data: {
messaging_product: "whatsapp",
to: message.from,
text: { body: "Echo: " + message.text.body },
context: { message_id: message.id },
},
});
await axios({
method: "POST",
url: `https://graph.facebook.com/v20.0/${business_phone_number_id}/messages`,
headers: {
Authorization: `Bearer ${GRAPH_API_TOKEN}`,
},
data: {
messaging_product: "whatsapp",
status: "read",
message_id: message.id,
},
});
} catch (error) {
console.error("Error sending reply:", error);
}
}
res.sendStatus(200);
});
app.get("/webhook", (req, res) => {
console.log("Webhook verification request:", req.query);
const mode = req.query["hub.mode"];
const token = req.query["hub.verify_token"];
const challenge = req.query["hub.challenge"];
if (mode === "subscribe" && token === process.env.WEBHOOK_VERIFY_TOKEN) {
res.status(200).send(challenge);
console.log("Webhook verified successfully!");
} else {
console.log("Webhook verification failed. Mode:", mode, "Token:", token);
res.sendStatus(403);
}
});
app.get("/", (req, res) => {
res.send(`<pre>Nothing to see here. Checkout README.md to start.</pre>`);
});
app.listen(PORT, () => {
console.log(`Server is listening on port: ${PORT}`);
});