const express = require("express");
const crypto = require("crypto");
const GOWA = "http://localhost:3000";
const AUTH = "Basic " + Buffer.from("admin:changeme").toString("base64");
const SECRET = "change-me";
const app = express();
app.post("/wa-hook", express.raw({ type: "application/json" }), async (req, res) => {
const sig = crypto.createHmac("sha256", SECRET).update(req.body).digest("hex");
const received = req.get("X-Hub-Signature-256") || "";
const expected = `sha256=${sig}`;
if (!/^sha256=[0-9a-f]{64}$/.test(received) ||
received.length !== expected.length ||
!crypto.timingSafeEqual(Buffer.from(received), Buffer.from(expected))) {
return res.sendStatus(401);
}
const evt = JSON.parse(req.body);
res.sendStatus(200);
if (evt.event !== "message" || evt.payload.is_from_me) return;
if (!evt.session_id) return;
if (!/^hi\b/i.test(evt.payload.body || "")) return;
const response = await fetch(`${GOWA}/send/message`, {
method: "POST",
headers: {
Authorization: AUTH,
"Content-Type": "application/json",
"X-Device-Id": evt.session_id, // reply from the slot that received it
},
body: JSON.stringify({
phone: evt.payload.chat_id,
message: "Hello! How can we help?",
reply_message_id: evt.payload.id,
}),
});
if (!response.ok) console.error("GOWA reply failed", response.status);
});
app.listen(8080);