async function handler(request, env) {
const webhook = await request.json();
// Only process message received events
if (request.headers.get('X-Webhook-Event') !== 'whatsapp.message.received') {
return new Response('OK');
}
// Extract customer info
const { message, conversation } = webhook;
const customerPhone = message.phone_number;
// Track customer session in KV
const sessionKey = `session:${customerPhone}`;
const session = await env.KV.get(sessionKey, { type: 'json' }) || {
firstContact: new Date().toISOString(),
messageCount: 0
};
session.lastMessage = message.content;
session.lastContact = new Date().toISOString();
session.messageCount++;
// Store session with 24-hour expiration
await env.KV.put(sessionKey, JSON.stringify(session), {
expirationTtl: 86400 // 24 hours
});
// Create or update CRM contact with session data
await fetch('https://api.hubspot.com/contacts/v1/contact', {
method: 'POST',
headers: {
'Authorization': `Bearer ${env.HUBSPOT_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
properties: [
{ property: 'phone', value: customerPhone },
{ property: 'last_whatsapp_message', value: message.content },
{ property: 'whatsapp_conversation_id', value: conversation.id },
{ property: 'total_messages', value: session.messageCount },
{ property: 'first_contact_date', value: session.firstContact }
]
})
});
return new Response('OK');
}