How use with EXPRESS #178
-
I COULD'T UNDERSTAND HOW THIS WILL WORK WITH EXPRESS SERVER OR ANYSERVER |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
No need to shout 🤣 Here's a small snippet of a express server using the library: import express from 'express';
import WhatsAppAPI from 'whatsapp-api-js';
const app = express();
const Whatsapp = new WhatsAppAPI({
token: "Your Token goes here",
appSecret: "Your App Secret goes here",
webhookVerifyToken: "Your webhook key goes here"
});
// This entry handles the server auth against Meta's website
app.get("/", async (req, res) => {
try {
res.send(await Whatsapp.get(req.query));
} catch (e) {
res.sendStatus(e);
}
});
// This entry handles server updates, such as messages and statuses
app.post("/", async (req, res) => {
let code;
try {
code = await Whatsapp.post(JSON.parse(req.body), req.body, req.headers["x-hub-signature-256"]);
} catch (e) {
// In case the JSON.parse fails ¯\_(ツ)_/¯
code = Number.isInteger(e) ? e : 500;
}
res.sendStatus(code);
});
// If you recieve a message, log it to the terminal
Whatsapp.on.message = ({ phoneID, from, message, name }) => {
console.log(`User ${name} (${from}) sent to bot ${phoneID} a(n) ${message.type}`);
};
app.listen(80); This "short" snippet handles both authentication against Meta's servers and WhatsApp updates. If the notification is a message, it will be logged to the terminal. And that's it! The library doesn't play well with Express, which can't handle failed promises, hence the need for so many try catchs in both methods. Among the updates I'm planning to write, I will add middlewares for the most popular server frameworks, including Express, so the code can be reduced to 2 lines. If you need more help, feel free to check out EXAMPLES, which includes snippets for all the messages types and how to send them. |
Beta Was this translation helpful? Give feedback.
No need to shout 🤣
Here's a small snippet of a express server using the library: