text
stringlengths
0
59.1k
try {
const body = await c.req.json<WhatsAppWebhookBody>();
// Extract message details
const entry = body.entry?.[0];
if (!entry) {
return c.json({ status: "no_entry" }, 200);
}
const changes = entry.changes?.[0];
if (!changes?.value?.messages) {
return c.json({ status: "no_messages" }, 200);
}
const phoneNumberId = changes.value.metadata.phone_number_id;
const messages = changes.value.messages;
const contacts = changes.value.contacts;
// Process each message
for (const message of messages) {
// Only process text messages
if (message.type !== "text" || !message.text?.body) {
continue;
}
const userPhone = message.from;
const userMessage = message.text.body;
const userName = contacts?.find((c) => c.wa_id === userPhone)?.profile?.name || "Customer";
console.log(`Received message from ${userPhone}: ${userMessage}`);
// Generate response using agent
const response = await agent.generateText(userMessage, {
userId: userPhone, // Use phone number as userId for context
conversationId: `whatsapp_${userPhone}`,
});
// Send response back to WhatsApp
if (response.text) {
const accessToken = process.env.WHATSAPP_ACCESS_TOKEN;
if (!accessToken) {
console.error("WhatsApp access token not configured");
continue;
}
await sendWhatsAppMessage(userPhone, response.text, phoneNumberId, accessToken);
}
}
// WhatsApp expects 200 OK response
return c.json({ status: "processed" }, 200);
} catch (error) {
console.error("Error processing WhatsApp webhook:", error);
// Still return 200 to prevent WhatsApp from retrying
return c.json({ status: "error" }, 200);
}
}
```
</details>
### Function Breakdown
**1. `sendWhatsAppMessage`** wraps the Meta Graph API call, adds the required auth headers, and logs any failures so you know whether WhatsApp actually accepted the reply.
**2. `handleWhatsAppVerification`** checks Meta's `hub.mode` and `hub.verify_token`, returning the expected challenge string when everything matches so the webhook can be registered successfully. This verification step is part of WhatsApp's multi-layer security: verify tokens prove ownership of the callback URL, HTTPS ...
**3. `handleWhatsAppMessage`** reads the webhook payload, forwards text messages into the agent with the right context, and posts responses back while still returning 200 to stop Meta from retrying.
**Key Security Features:** Together these handlers validate the verify token, keep responses at 200 to avoid retry storms, lean on typed payloads for safety, and log unexpected errors without taking the service offline.
#### VoltAgent Server Configuration
Initialize VoltAgent with custom webhook handlers:
```typescript
new VoltAgent({
agents: {
agent,
},
server: honoServer({
configureApp: (app) => {
// WhatsApp webhook verification (GET)
app.get("/webhook/whatsapp", async (c) => {
return handleWhatsAppVerification(c);
});
// WhatsApp webhook message handler (POST)
app.post("/webhook/whatsapp", async (c) => {
return handleWhatsAppMessage(c, agent);
});
// Health check endpoint
app.get("/health", (c) => {
return c.json({
status: "healthy",
service: "whatsapp-ordering-agent",
timestamp: new Date().toISOString(),
});