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
318 changes: 282 additions & 36 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,36 +1,282 @@
const express = require('express')
const path = require('path')

const port = process.env.PORT || 5006

const app = express()

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

app.get('/', (req, res) => {
console.log(`Rendering 'pages/index' for route '/'`)
res.render('pages/index')
})

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')
})
}
})
const express = require("express");
const axios = require("axios");
const bodyParser = require("body-parser");

const app = express();
app.use(bodyParser.json());

const PORT = process.env.PORT || 10000;

/* ========== CONFIG ========== */

const TOKEN = process.env.WHATSAPP_TOKEN;
const PHONE_ID = process.env.PHONE_NUMBER_ID;
const SHEET_URL = process.env.SHEET_WEBHOOK;
const OWNER_UPI = "8121893882-2@ybl";

/* ========== SESSION STORE ========== */

const sessions = {};

function newSession(phone) {
return {
orderId: "ORD-" + Date.now(),
phone,
step: "MENU",
};
}

/* ========== PRODUCTS ========== */

const PRODUCTS = {
"1": { name: "Buffalo Milk", price: 100 },
"2": { name: "Cow Milk", price: 120 },
"3": { name: "Paneer", price: 600 },
"4": { name: "Ghee", price: 1000 },
"5": { name: "Daily Milk Subscription" },
"6": { name: "Talk to Owner" },
};

/* ========== SEND MESSAGE ========== */

async function sendMessage(to, text) {
await axios.post(
`https://graph.facebook.com/v18.0/${PHONE_ID}/messages`,
{
messaging_product: "whatsapp",
to,
text: { body: text },
},
{
headers: {
Authorization: `Bearer ${TOKEN}`,
"Content-Type": "application/json",
},
}
);
}

/* ========== SAVE TO SHEET ========== */

async function saveToSheet(data) {
await axios.post(SHEET_URL, data);
}

/* ========== MENU TEXT ========== */

function menuText() {
return `🥛 *Welcome to Bala Milk Store*

Please choose an option:
1️⃣ Buffalo Milk – ₹100/L
2️⃣ Cow Milk – ₹120/L
3️⃣ Paneer – ₹600/Kg
4️⃣ Ghee – ₹1000/Kg
5️⃣ Daily Milk Subscription
6️⃣ Talk to Owner

Reply with option number.`;
}

/* ========== WEBHOOK ========== */

app.post("/webhook", async (req, res) => {
const msg = req.body.entry?.[0]?.changes?.[0]?.value?.messages?.[0];
if (!msg) return res.sendStatus(200);

const from = msg.from;
const text = msg.text?.body?.trim();
const location = msg.location;
const image = msg.image;

if (!sessions[from]) {
sessions[from] = newSession(from);
await sendMessage(from, menuText());
return res.sendStatus(200);
}

const s = sessions[from];

/* ===== MENU ===== */
if (s.step === "MENU") {
if (!PRODUCTS[text]) {
await sendMessage(from, "❌ Invalid option.\n\n" + menuText());
return res.sendStatus(200);
}

if (text === "6") {
await sendMessage(from, "📞 Please call: 8121893882");
delete sessions[from];
return res.sendStatus(200);
}

s.product = PRODUCTS[text].name;
s.unitPrice = PRODUCTS[text].price;
s.step = "QTY";

await sendMessage(
from,
`🧾 *${s.product}*

Choose quantity:
1️⃣ 500ml – ₹${s.unitPrice * 0.5}
2️⃣ 1 L – ₹${s.unitPrice}
3️⃣ 2 L – ₹${s.unitPrice * 2}`
);
return res.sendStatus(200);
}

/* ===== QUANTITY ===== */
if (s.step === "QTY") {
if (!["1", "2", "3"].includes(text)) {
await sendMessage(from, "❌ Choose 1 / 2 / 3");
return res.sendStatus(200);
}

const map = {
"1": { qty: "500ml", mul: 0.5 },
"2": { qty: "1L", mul: 1 },
"3": { qty: "2L", mul: 2 },
};

s.quantity = map[text].qty;
s.price = s.unitPrice * map[text].mul;
s.step = "ADDRESS";

await sendMessage(
from,
`📍 *Delivery Address*

1️⃣ Send live location
2️⃣ Type address manually`
);
return res.sendStatus(200);
}

/* ===== ADDRESS ===== */
if (s.step === "ADDRESS") {
if (location) {
s.address = `Live Location: ${location.latitude}, ${location.longitude}`;
} else {
s.address = text;
}

s.step = "SLOT";
await sendMessage(from, "🚚 Choose delivery slot:\n1️⃣ Morning\n2️⃣ Evening");
return res.sendStatus(200);
}

/* ===== SLOT ===== */
if (s.step === "SLOT") {
if (!["1", "2"].includes(text)) {
await sendMessage(from, "❌ Choose 1 or 2");
return res.sendStatus(200);
}

s.slot = text === "1" ? "Morning" : "Evening";
s.step = "TIME";
await sendMessage(from, "⏰ Enter delivery time (example: 6:30 AM)");
return res.sendStatus(200);
}

/* ===== TIME ===== */
if (s.step === "TIME") {
s.time = text;
s.step = "PAYMENT_CHOICE";

await sendMessage(
from,
`💰 Choose payment method:
1️⃣ UPI
2️⃣ Cash on Delivery`
);
return res.sendStatus(200);
}

/* ===== PAYMENT CHOICE ===== */
if (s.step === "PAYMENT_CHOICE") {
if (text === "1") {
s.paymentMethod = "UPI";
s.step = "UPI_SCREENSHOT";
await sendMessage(
from,
`📲 Pay using UPI:

${OWNER_UPI}

After payment, please send screenshot.`
);
return res.sendStatus(200);
}

if (text === "2") {
s.paymentMethod = "Cash on Delivery";
await finalizeOrder(from, s);
return res.sendStatus(200);
}

await sendMessage(from, "❌ Choose 1 or 2");
return res.sendStatus(200);
}

/* ===== UPI SCREENSHOT ===== */
if (s.step === "UPI_SCREENSHOT") {
if (!image) {
await sendMessage(from, "❌ Please send payment screenshot.");
return res.sendStatus(200);
}

s.screenshot = image.id;
await finalizeOrder(from, s);
return res.sendStatus(200);
}

res.sendStatus(200);
});

/* ========== FINALIZE ORDER ========== */

async function finalizeOrder(from, s) {
await saveToSheet({
orderId: s.orderId,
date: new Date().toLocaleString(),
phone: s.phone,
product: s.product,
quantity: s.quantity,
price: s.price,
address: s.address,
delivery: `${s.slot} ${s.time}`,
payment: s.paymentMethod,
screenshot: s.screenshot || "",
});

await sendMessage(
from,
`✅ *Order Confirmed!*

🧾 Order ID: ${s.orderId}
🥛 ${s.product}
📦 ${s.quantity}
💰 ₹${s.price}
🚚 ${s.slot} ${s.time}

🙏 Thank you for choosing *Bala Milk Store*`
);

delete sessions[from];
}

/* ========== VERIFY ========== */

app.get("/webhook", (req, res) => {
if (req.query["hub.verify_token"] === process.env.VERIFY_TOKEN) {
return res.send(req.query["hub.challenge"]);
}
res.sendStatus(403);
});

/* ========== START ========== */

app.listen(PORT, () => {
console.log("Server running on port", PORT);
});
34 changes: 10 additions & 24 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,30 +1,16 @@
{
"name": "nodejs-getting-started",
"private": true,
"description": "A sample Node.js app using Express",
"engines": {
"node": "20.x || 22.x || 24.x"
},
"name": "bala-whatsapp-bot",
"version": "1.0.0",
"description": "WhatsApp Cloud API bot for Bala Milk Store",
"main": "index.js",
"scripts": {
"start": "node index.js",
"test": "jest"
},
"dependencies": {
"ejs": "^3.1.10",
"express": "^5.2.1"
"start": "node index.js"
},
"devDependencies": {
"jest": "^30.2.0"
},
"repository": {
"type": "git",
"url": "https://github.com/heroku/nodejs-getting-started"
"engines": {
"node": ">=18"
},
"keywords": [
"node",
"heroku",
"express"
],
"license": "MIT"
"dependencies": {
"axios": "^1.6.2",
"express": "^4.18.2"
}
}
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