-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsend-order.js
More file actions
98 lines (84 loc) · 3.58 KB
/
Copy pathsend-order.js
File metadata and controls
98 lines (84 loc) · 3.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// /api/send-order.js
// Serverless function (Vercel Node.js runtime). Receives the checkout payload
// from the frontend and forwards a formatted order ticket to a Telegram chat
// via the Bot API — no official WhatsApp Business API needed.
//
// Required environment variables (set these in your hosting dashboard,
// NEVER in frontend code):
// TELEGRAM_BOT_TOKEN - token from @BotFather
// TELEGRAM_CHAT_ID - the chat/group that should receive order tickets
export default async function handler(req, res) {
if (req.method !== 'POST') {
res.setHeader('Allow', 'POST');
return res.status(405).json({ success: false, error: 'Method not allowed' });
}
const { orderId, name, phone, address, payment, items, itemTotal, deliveryFee, grandTotal } = req.body || {};
// Never trust the client — re-validate the shape of the order server-side.
if (
!orderId || !name || !phone || !address ||
!Array.isArray(items) || items.length === 0 ||
typeof grandTotal !== 'number'
) {
return res.status(400).json({ success: false, error: 'Missing or invalid order details' });
}
const BOT_TOKEN = process.env.TELEGRAM_BOT_TOKEN;
const CHAT_ID = process.env.TELEGRAM_CHAT_ID;
if (!BOT_TOKEN || !CHAT_ID) {
console.error('Telegram bot not configured: missing TELEGRAM_BOT_TOKEN / TELEGRAM_CHAT_ID');
return res.status(500).json({ success: false, error: 'Notification service not configured' });
}
const text = formatOrderMessage({ orderId, name, phone, address, payment, items, itemTotal, deliveryFee, grandTotal });
try {
const tgRes = await fetch(`https://api.telegram.org/bot${BOT_TOKEN}/sendMessage`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
chat_id: CHAT_ID,
text,
parse_mode: 'HTML',
disable_web_page_preview: true,
}),
});
const tgData = await tgRes.json();
if (!tgData.ok) {
console.error('Telegram API rejected the message:', tgData);
return res.status(502).json({ success: false, error: tgData.description || 'Telegram API error' });
}
return res.status(200).json({ success: true });
} catch (err) {
console.error('Telegram request failed:', err);
return res.status(500).json({ success: false, error: 'Could not reach Telegram' });
}
}
// Telegram's HTML parse mode only understands a handful of tags (b, i, u, s,
// a, code, pre, etc). Anything else in user-typed text — & < > — must be
// escaped or Telegram will reject the whole message.
function escapeHtml(str) {
return String(str)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>');
}
function formatOrderMessage({ orderId, name, phone, address, payment, items, itemTotal, deliveryFee, grandTotal }) {
const itemLines = items
.map((i) => `• ${escapeHtml(i.name)} × ${i.qty} — ₹${i.qty * i.price}`)
.join('\n');
const paymentLabel = payment === 'upi' ? 'Pay Now via UPI' : 'Pay on Delivery (Cash / UPI QR at door)';
const deliveryLine = deliveryFee === 0 ? 'FREE' : `₹${deliveryFee}`;
return [
`🍕 <b>NEW ORDER — ${escapeHtml(orderId)}</b>`,
'━━━━━━━━━━━━━━━━━━',
`<b>Name:</b> ${escapeHtml(name)}`,
`<b>WhatsApp:</b> <code>${escapeHtml(phone)}</code>`,
`<b>Address:</b> ${escapeHtml(address)}`,
'',
'<b>Items</b>',
itemLines,
'',
`<b>Item Total:</b> ₹${itemTotal}`,
`<b>Delivery Fee:</b> ${deliveryLine}`,
`<b>Grand Total:</b> ₹${grandTotal}`,
'',
`<b>Payment:</b> ${escapeHtml(paymentLabel)}`,
].join('\n');
}