const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.json());
// Optional: Basic authentication middleware
const basicAuth = (req, res, next) => {
const expected =
'Basic ' +
Buffer.from(
`${process.env.WEBHOOK_USER}:${process.env.WEBHOOK_PASS}`
).toString('base64');
if (expected && req.headers.authorization !== expected) {
return res.status(401).json({ message: 'Unauthorized' });
}
next();
};
// Look up the push token for the recipient in your store.
const fetchPushToken = async (uid) => {
// TODO: Implement fetch logic.
return 'device-push-token';
};
// Send to APNs/FCM/other provider with the payload you received.
const sendPushNotification = async (token, title, body, notificationDetails) => {
// TODO: Implement delivery.
};
const triggerPushNotification = async (to, notificationDetails) => {
const { uid } = to || {};
const { type, title, body, callAction, sessionId, callType } =
notificationDetails || {};
if (!uid) {
throw new Error('Missing recipient UID');
}
if (type === 'call') {
console.log('Push notification for calling event', {
callAction,
sessionId,
callType,
});
}
if (type === 'chat') {
console.log('Push notification for messaging event');
}
const token = await fetchPushToken(uid);
await sendPushNotification(token, title, body, notificationDetails);
};
app.post('/webhook', basicAuth, (req, res) => {
const { trigger, data, appId, webhook } = req.body || {};
const { to, notificationDetails } = data || {};
if (
trigger !== 'push-notification-payload-generated' ||
webhook !== 'custom' ||
!to ||
!notificationDetails
) {
return res.status(400).json({ message: 'Invalid trigger or webhook type' });
}
console.log('Received webhook', { appId, trigger, webhook, to: to.uid });
triggerPushNotification(to, notificationDetails).catch((error) => {
console.error(
'Error while triggering push 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}`);
});