diff --git a/index.js b/index.js index 19d020f11f..f60f8d10f0 100644 --- a/index.js +++ b/index.js @@ -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; diff --git a/views/pages/index.ejs b/views/pages/index.ejs index ea7498435d..95a9bfc746 100644 --- a/views/pages/index.ejs +++ b/views/pages/index.ejs @@ -13,7 +13,7 @@ -

Getting Started on Heroku with Node.js

+

Hello from Balaraju 🚀

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.

Getting Started on Heroku with Node.js Getting Started on Heroku Fir with Node.js