Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 71 additions & 29 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,36 +1,78 @@
const express = require('express')
const path = require('path')
const express = require('express');
const path = require('path');

const port = process.env.PORT || 5006
const app = express();
const port = process.env.PORT || 5006;

const app = express()
// Middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.use(express.static(path.join(__dirname, 'public')))
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'ejs')
// Static & views
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// Home route
app.get('/', (req, res) => {
console.log(`Rendering 'pages/index' for route '/'`)
res.render('pages/index')
})
res.send('WhatsApp Webhook is running ✅');
});

const server = app.listen(port, () => {
console.log(`Listening on ${port}`)
})

// The number of seconds an idle Keep-Alive connection is kept open. This should be greater than the Heroku Router's
// Keep-Alive idle timeout of 90 seconds:
// - to ensure that the closing of idle connections is always initiated by the router and not the Node.js server
// - to prevent a race condition if the router sends a request to the app just as Node.js is closing the connection
// https://devcenter.heroku.com/articles/http-routing#keepalives
// https://nodejs.org/api/http.html#serverkeepalivetimeout
server.keepAliveTimeout = 95 * 1000

process.on('SIGTERM', async () => {
console.log('SIGTERM signal received: gracefully shutting down')
if (server) {
server.close(() => {
console.log('HTTP server closed')
})
// 🔐 Webhook verification (Meta Step)
app.get('/webhook', (req, res) => {
const VERIFY_TOKEN = 'my_verify_token'; // must match Meta token

const mode = req.query['hub.mode'];
const token = req.query['hub.verify_token'];
const challenge = req.query['hub.challenge'];

if (mode === 'subscribe' && token === VERIFY_TOKEN) {
console.log('Webhook verified');
res.status(200).send(challenge);
} else {
res.sendStatus(403);
}
})
});

// 📩 Receive WhatsApp messages
app.post('/webhook', async (req, res) => {
console.log('Incoming webhook:', JSON.stringify(req.body, null, 2));

const entry = req.body.entry?.[0];
const changes = entry?.changes?.[0];
const value = changes?.value;
const messages = value?.messages;

if (messages && messages.length > 0) {
const from = messages[0].from;
const text = messages[0].text?.body;

console.log(`Message from ${from}: ${text}`);

// Auto-reply
await fetch(
`https://graph.facebook.com/v19.0/${process.env.PHONE_NUMBER_ID}/messages`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${process.env.WHATSAPP_TOKEN}`
},
body: JSON.stringify({
messaging_product: 'whatsapp',
to: from,
text: { body: '👋 Hello! Your message has been received successfully.' }
})
}
);
}

res.sendStatus(200);
});

// Start server
const server = app.listen(port, () => {
console.log(`Server running on port ${port}`);
});

server.keepAliveTimeout = 95 * 1000;
2 changes: 1 addition & 1 deletion views/pages/index.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
<a href="/" class="lang-logo">
<img src="/lang-logo.png">
</a>
<h1>Getting Started on Heroku with Node.js</h1>
<h1>Hello from Balaraju 🚀</h1>
<p>This is a sample Node application deployed to Heroku. It's a reasonably simple app - but a good foundation for understanding how to get the most out of the Heroku platform.</p>
<a type="button" class="btn btn-lg btn-default" href="https://devcenter.heroku.com/articles/getting-started-with-nodejs"><span class="glyphicon glyphicon-flash"></span> Getting Started on Heroku with Node.js</a>
<a type="button" class="btn btn-lg btn-default" href="https://devcenter.heroku.com/articles/getting-started-with-nodejs-fir"><span class="glyphicon glyphicon-flash"></span> Getting Started on Heroku Fir with Node.js</a>
Expand Down