diff --git a/whatsapp-gateway/baileys-client.js b/whatsapp-gateway/baileys-client.js index 05ba2de..e60190d 100644 --- a/whatsapp-gateway/baileys-client.js +++ b/whatsapp-gateway/baileys-client.js @@ -437,6 +437,24 @@ async function sendMessage(session_key, phone, message, mediaUrl = null, audioBa return sentMsg; } +async function checkContact(session_key, phone) { + const sock = sessions.get(session_key); + if (!sock) { + throw new Error(`Session ${session_key} is not active or connected`); + } + const jid = phone.includes('@') ? phone : `${phone}@s.whatsapp.net`; + try { + const result = await sock.onWhatsApp(jid); + if (result && result.length > 0) { + return result[0]; + } + return { exists: false, jid }; + } catch (err) { + console.error(`[Baileys] Error checking contact ${jid}:`, err.message); + throw err; + } +} + function getActiveSessions() { return Array.from(sessions.keys()); } @@ -445,6 +463,7 @@ module.exports = { startSession, disconnectSession, sendMessage, - getActiveSessions + getActiveSessions, + checkContact }; diff --git a/whatsapp-gateway/server.js b/whatsapp-gateway/server.js index b2e7934..09f75c4 100644 --- a/whatsapp-gateway/server.js +++ b/whatsapp-gateway/server.js @@ -20,7 +20,7 @@ for (const p of envPaths) { const express = require('express'); const cors = require('cors'); -const { startSession, disconnectSession, sendMessage, getActiveSessions } = require('./baileys-client'); +const { startSession, disconnectSession, sendMessage, getActiveSessions, checkContact } = require('./baileys-client'); const app = express(); app.use(cors()); @@ -82,6 +82,23 @@ app.get('/api/sessions/active', (req, res) => { res.json({ status: 'success', active_sessions: getActiveSessions() }); }); +// Check if contact is on WhatsApp +app.post('/api/contacts/check', async (req, res) => { + const { session_key, phone } = req.body; + + if (!session_key || !phone) { + return res.status(400).json({ error: 'Missing session_key or phone' }); + } + + try { + const result = await checkContact(session_key, phone); + res.json({ status: 'success', data: result }); + } catch (err) { + console.error(`Error checking contact ${phone} via ${session_key}:`, err); + res.status(500).json({ error: err.message || 'Failed to check contact' }); + } +}); + // Send outbound message app.post('/api/messages/send', async (req, res) => { const { session_key, phone, message, media_url, audio, mimetype, image } = req.body;