I’m trying to configure the webhook. I watched a lot of videos using platforms like Heroku or ngrok. But I already have a server, Hostinger Brasil. The problem is that the URL I put in the configuration is not accepted. I don’t know if it’s because of my code or some configuration I didn’t do.
“Port” 80 is the web standard, but I still wanted to specify it. On localhost, testing, it only works on port 8000, 3000.
arquivo .env
WEBHOOK_VERIFY_TOKEN = "123"
GRAPH_API_TOKEN = "EAAQUA14XZBPwBO7M7sqU46sO7eSbVjYQAGJiD9rqOnOhTLIUyPPZBT2SZAbJLzOPUIGZAblwp5TiwWsPe1AgxuGtiZAJlumDrZBXH7ROct5IDZCOmJXji8OWUnfQPFrmmI3LTCkPjJygkmyx2MmtPXKp9KFcAGVRoLErlMKQl2JbFBjAi8KDyDe2rgQ9ouGd37PAozBALTQ1B48jpKYbZBUZD" # token temporary
PORT = 80
arquivo index.js
// ------ IMPORTANDO MODULOS
const express = require("express"); // framework para aplicativos web do Node.js
const body_parser = require("body-parser"); // middleware para analisar corpos de solicitação em middleware antes de seus manipuladores
const axios = require("axios"); // biblioteca HTTP cliente para fazer requisições HTTP
require('dotenv').config(); // módulo para carregar variáveis de ambiente do arquivo .env
// configuracao do Express. Criamos uma instância do aplicativo Express e usamos o body_parser.json() para analisar os corpos das solicitações como JSON
const app = express().use(body_parser.json());
const token = process.env.GRAPH_API_TOKEN; //temporary access token dashboard api wpp
const mytoken = process.env.WEBHOOK_VERIFY_TOKEN;
// inicia o servidor Express na porta 8000 ou na porta definida em process.env.PORT
app.listen(process.env.PORT,()=>{
console.log("webhook is listening...");
})
app.get("/",(req,res) => {
res.status(200).send("hello this is webhook setup");
});
// é definida uma rota GET para a URL /webhook que será usada para verificação e configuração do webhook do Facebook
// para verificar a url de retorno no painel de apps (cloud api)
app.get("/webhook", (req, res) =>{
let mode = req.query["hub.mode"];
let token = req.query["hub.verify_token"];
let challenge = req.query["hub.challenge"];
// check the mode and token sent are correct
if (mode && token) {
if(mode === "subscribe" && token === mytoken){
// respond with 200 OK and challenge token from the request
res.status(200).send(challenge);
console.log("Webhook verified successfully!");
}else {
// respond with '403 Forbidden' if verify tokens do not match
res.sendStatus(403);
}
}
});
// trata as solicitações POST recebidas no endpoint /webhook, onde as mensagens recebidas do WhatsApp serão processadas e respondidas
app.post("/webhook",(req,res) => {
let body_param = req.body;
console.log(JSON.stringify(body_param,null,2)); // obtem a resposta e coloca no console
// https://developers.facebook.com/docs/whatsapp/cloud-api/webhooks/payload-examples
if(body_param.object){
if(body_param.entry && // Verifica se a propriedade entry existe em body_param e se não é null ou undefined
body_param.entry[0].changes && // Verifica se o primeiro elemento do array entry possui a propriedade changes e se não é null ou undefine
body_param.entry[0].changes[0].value.message && // Verifica se o primeiro elemento do array changes possui a propriedade value com uma subpropriedade message e se não é null ou undefined
body_param.entry[0].changes[0].value.message[0] // Verifica se o primeiro elemento do array message existe.
){
let phone_no_id = body_param.entry[0].changes[0].value.metadata.phone_number_id;
let from = body_param.entry[0].changes[0].value.messages[0].from;
let msg_body = body_param.entry[0].changes[0].value.messages[0].text.body;
axios({
method: "POST",
// acha em https://developers.facebook.com/apps/1147904602929404/whatsapp-business/wa-dev-console/?business_id=969071548077814
url: "https://graph.facebook.com/v19.0/"+phone_no_id+"/messages?access_token="+token,
data: {
messaging_product: "whatsapp",
to: from,
text:{
body: "Hi..."
}
},
headers:{
"Content-Type": "application/json"
}
})
res.sendStatus(200);
}else{
res.sendStatus(404);
}
}
});
I’ve also tried putting the URL in the “user” of the webhook, but it wasn’t accepted.
Sorry if it’s a dumb question, I’m new to API. Sorry for my English too :/