const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.json());
const basicAuth = (req, res, next) => {
const authHeader = req.headers['authorization'];
if (!authHeader || !authHeader.startsWith('Basic ')) {
return res.status(401).json({ message: 'Unauthorized' });
}
next();
};
const triggerSMSNotification = async (to = {}, data = {}) => {
let { name, uid, phno } = to;
let { groupDetails, senderDetails, smsContent } = data;
if (!uid) throw new Error('Missing data.to.uid');
if (!smsContent) throw new Error('Missing data.smsContent');
if (groupDetails) console.log('Received webhook for group SMS notification');
if (senderDetails) console.log('Received webhook for one-on-one SMS notification');
if (phno == null) {
phno = await fetchPhoneNumberFor(uid);
}
if (!phno) throw new Error(`Phone number not available for uid=${uid}`);
return await sendSMS(phno, smsContent);
};
app.post('/webhook', basicAuth, (req, res) => {
const { trigger, data, appId, region, webhook } = req.body || {};
const { to } = data || {};
if (trigger !== 'sms-notification-payload-generated' || webhook !== 'custom') {
return res.status(400).json({ message: 'Invalid trigger or webhook type' });
}
console.log('Received Webhook:', JSON.stringify(req.body, null, 2));
triggerSMSNotification(to, data)
.then((result) => {
console.log('Successfully triggered SMS notification for', appId, to?.uid, result);
})
.catch((error) => {
console.error('Something went wrong while triggering SMS notification for', appId, to?.uid, error.message);
});
res.status(200).json({ message: 'Webhook received successfully' });
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});