{"openapi":"3.0.0","info":{"title":"WhatsApp Business Platform - External API","version":"2.0.0","description":"# WhatsApp Business Platform - External API Documentation\n\nThis is the **external API** for developers to integrate WhatsApp messaging into their applications.\n\n## 🔐 Authentication\nUse API token authentication for all endpoints. You can provide the token in two ways:\n- **Bearer Token**: `Authorization: Bearer wat_xxxxx`\n- **Header**: `X-API-Key: wat_xxxxx`\n\n## 🚀 Quick Start\n1. **Get API Token**: Contact your platform administrator to get an API token\n2. **Test Connection**: Use `GET /health` to verify your token works\n3. **Send Messages**: Use `POST /messages/send` to send WhatsApp messages\n4. **Get Conversations**: Use `GET /conversations` to retrieve conversations\n5. **Set up Webhooks**: Configure webhooks to receive real-time notifications\n\n## 📱 Core Features\n- **Message Sending**: Send text, media, and template messages\n- **Conversation Management**: Retrieve and manage conversations\n- **Message Status**: Track message delivery status\n- **Phone Number Management**: List available phone numbers\n- **Webhook Integration**: Receive real-time notifications\n- **Rate Limiting**: Built-in rate limiting with clear headers\n\n## 🔗 Webhook Events\nSubscribe to these events for real-time updates:\n- `message.received`: New message from customer\n- `conversation.created`: New conversation started\n- `message.status`: Message delivery status updates\n- `conversation.updated`: Conversation metadata changes\n\n## 📊 Rate Limiting\n- **Default**: 1000 requests per 15-minute window\n- **Headers**: Check `X-RateLimit-*` headers for current usage\n- **Limits**: Vary by token and endpoint\n\n## 🔗 Related Documentation\n- [Complete API Documentation](/docs) - Internal and External APIs\n- [Webhook Setup Guide](/docs#/webhooks) - Webhook configuration\n- [Rate Limiting Guide](/docs#/rate-limiting) - Rate limit details","contact":{"name":"Developer Support","url":"https://github.com/your-repo","email":"developers@yourapi.com"},"license":{"name":"MIT","url":"https://opensource.org/licenses/MIT"}},"servers":[{"url":"http://localhost:4000/api/v2","description":"Development server"},{"url":"https://your-production-domain.com/api/v2","description":"Production server"}],"components":{"securitySchemes":{"ApiKeyAuth":{"type":"http","scheme":"bearer","bearerFormat":"API-KEY","description":"Enter your API token in the format: Bearer wat_xxxxx"},"ApiKeyHeader":{"type":"apiKey","in":"header","name":"X-API-Key","description":"API token for external applications"}},"schemas":{"ApiResponse":{"type":"object","properties":{"success":{"type":"boolean","description":"Whether the request was successful"},"message":{"type":"string","description":"Response message"},"data":{"type":"object","description":"Response data"},"meta":{"type":"object","description":"Metadata about the response"}}},"Error":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"code":{"type":"string","description":"Error code"},"message":{"type":"string","description":"Error message"}}}}},"RateLimitInfo":{"type":"object","properties":{"limit":{"type":"integer","description":"Maximum requests allowed in the window","example":1000},"remaining":{"type":"integer","description":"Remaining requests in the current window","example":950},"reset":{"type":"string","format":"date-time","description":"When the rate limit window resets","example":"2023-12-01T11:00:00Z"},"window":{"type":"integer","description":"Window size in seconds","example":900}}},"ExternalSendMessageRequest":{"type":"object","required":["phoneNumberId","to","message"],"properties":{"phoneNumberId":{"type":"string","description":"WhatsApp Business Phone Number ID","example":"123456789012345"},"to":{"type":"string","description":"Recipient phone number with country code","example":"+1234567890"},"message":{"type":"string","description":"Text message content","example":"Hello, this is a test message from the API!"},"replyToMessageId":{"type":"string","description":"ID of message to reply to (optional)","example":"msg_123456789"}}},"ExternalSendMessageResponse":{"type":"object","properties":{"success":{"type":"boolean","description":"Whether the message was sent successfully","example":true},"data":{"type":"object","properties":{"messageId":{"type":"string","description":"Internal message ID","example":"msg_123456789"},"whatsappMessageId":{"type":"string","description":"WhatsApp message ID","example":"wamid.HBgLMTY3NDc4NjQyMTQVAgARGBI4OTZFMEY3NjU5QzA5MDcyOQA="},"status":{"type":"string","description":"Message status","example":"sent"},"timestamp":{"type":"string","format":"date-time","description":"Message timestamp","example":"2023-12-01T10:30:00Z"},"conversationId":{"type":"string","description":"Conversation ID","example":"conv_123456789"},"to":{"type":"string","description":"Recipient phone number","example":"+1234567890"},"from":{"type":"string","description":"Sender phone number","example":"+0987654321"},"aiAgentOverride":{"type":"boolean","description":"Whether AI agent was overridden via API parameter","example":true},"conversation":{"type":"object","description":"Conversation details including AI agent and lead qualification data","properties":{"id":{"type":"string","description":"Conversation ID","example":"conv_123456789"},"is_ai_agent_on":{"type":"boolean","description":"Whether AI agent is currently enabled","example":true},"ai_agent_enabled_at":{"type":"string","format":"date-time","description":"When AI agent was enabled","example":"2023-12-01T10:15:00Z","nullable":true},"ai_agent_enabled_by":{"type":"string","description":"Who/what enabled the AI agent","enum":["user","api","auto","default"],"example":"api","nullable":true},"ai_agent_last_toggled_at":{"type":"string","format":"date-time","description":"When AI agent status was last changed","example":"2023-12-01T10:15:00Z","nullable":true},"lead_status":{"type":"string","description":"Lead qualification status","example":"qualified","nullable":true},"lead_score":{"type":"integer","description":"Lead qualification score (0-100)","example":85,"nullable":true},"lead_company":{"type":"string","description":"Lead's company name","example":"Test Company Inc","nullable":true},"lead_notes":{"type":"string","description":"Lead qualification notes","example":"High-value prospect","nullable":true},"lead_name":{"type":"string","description":"Lead's name (may differ from customer name)","example":"John Doe","nullable":true},"lead_source":{"type":"string","description":"Lead source","example":"website","nullable":true},"lead_budget":{"type":"string","description":"Lead's budget range","example":"50000","nullable":true},"lead_timeline":{"type":"string","description":"Lead's purchase timeline","example":"Q1 2024","nullable":true},"lead_industry":{"type":"string","description":"Lead's industry","example":"Technology","nullable":true},"lead_job_title":{"type":"string","description":"Lead's job title","example":"CTO","nullable":true},"lead_location":{"type":"string","description":"Lead's location","example":"San Francisco, CA","nullable":true},"lead_qualification_date":{"type":"string","format":"date-time","description":"When lead was qualified","example":"2023-12-01T10:15:00Z","nullable":true},"lead_last_updated":{"type":"string","format":"date-time","description":"When lead data was last updated","example":"2023-12-01T10:15:00Z","nullable":true},"leadQualification":{"type":"object","description":"Raw lead data from external APIs","nullable":true,"properties":{"raw_data":{"type":"object","description":"Complete raw response from external API","example":{"score":85,"source":"website"}},"processed_data":{"type":"object","description":"Structured data for easy querying","example":{"priority":"high","qualified":true}},"source_api":{"type":"string","description":"Source API that provided the data","example":"test_api"},"stored_at":{"type":"string","format":"date-time","description":"When the data was stored","example":"2023-12-01T10:15:00Z"}}}}}}}}},"ExternalMessageStatus":{"type":"object","properties":{"success":{"type":"boolean","description":"Whether the request was successful","example":true},"data":{"type":"object","properties":{"messageId":{"type":"string","description":"Internal message ID","example":"msg_123456789"},"whatsappMessageId":{"type":"string","description":"WhatsApp message ID","example":"wamid.HBgLMTY3NDc4NjQyMTQVAgARGBI4OTZFMEY3NjU5QzA5MDcyOQA="},"status":{"type":"string","enum":["sent","delivered","read","failed"],"description":"Message status","example":"delivered"},"timestamp":{"type":"string","format":"date-time","description":"Status timestamp","example":"2023-12-01T10:30:00Z"}}}}},"ExternalConversation":{"type":"object","properties":{"id":{"type":"string","description":"Conversation identifier","example":"conv_123456789"},"customerPhone":{"type":"string","description":"Customer phone number","example":"+1234567890"},"customerName":{"type":"string","description":"Customer display name","example":"John Doe"},"lastMessageAt":{"type":"string","format":"date-time","description":"Timestamp of last message","example":"2023-12-01T10:30:00Z"},"lastMessagePreview":{"type":"string","description":"Preview of last message","example":"Hello, how can I help you?"},"unreadCount":{"type":"integer","description":"Number of unread messages","example":3},"phoneNumber":{"type":"string","description":"Business phone number","example":"+0987654321"},"is_ai_agent_on":{"type":"boolean","description":"Whether AI agent is currently enabled for this conversation","example":true},"ai_agent_enabled_at":{"type":"string","format":"date-time","description":"When the AI agent was last enabled for this conversation","example":"2023-12-01T10:15:00Z","nullable":true},"ai_agent_enabled_by":{"type":"string","description":"Who/what enabled the AI agent for this conversation","enum":["user","api","auto","default"],"example":"auto","nullable":true},"ai_agent_last_toggled_at":{"type":"string","format":"date-time","description":"When the AI agent status was last changed","example":"2023-12-01T10:15:00Z","nullable":true}}},"ExternalMessage":{"type":"object","properties":{"id":{"type":"string","description":"Message identifier","example":"msg_123456789"},"conversationId":{"type":"string","description":"Conversation identifier","example":"conv_123456789"},"direction":{"type":"string","enum":["inbound","outbound"],"description":"Message direction","example":"inbound"},"content":{"type":"string","description":"Message content","example":"Hello, how are you?"},"messageType":{"type":"string","enum":["text","image","video","audio","document"],"description":"Message type","example":"text"},"status":{"type":"string","enum":["sent","delivered","read","failed"],"description":"Message status","example":"delivered"},"timestamp":{"type":"string","format":"date-time","description":"Message timestamp","example":"2023-12-01T10:30:00Z"}}},"ExternalPhoneNumber":{"type":"object","properties":{"id":{"type":"string","description":"Internal phone number ID","example":"pn_123456789"},"phoneNumberId":{"type":"string","description":"WhatsApp Business Phone Number ID","example":"123456789012345"},"phoneNumber":{"type":"string","description":"Phone number","example":"+1234567890"},"displayName":{"type":"string","description":"Display name","example":"Business Phone"},"verifiedName":{"type":"string","description":"Verified name","example":"My Business"},"status":{"type":"string","enum":["VERIFIED","UNVERIFIED","PENDING"],"description":"Phone number status","example":"VERIFIED"},"whatsappAccount":{"type":"object","properties":{"id":{"type":"string","description":"WhatsApp account ID","example":"acc_123456789"},"wabaName":{"type":"string","description":"WhatsApp Business Account name","example":"My Business"},"status":{"type":"string","description":"Account status","example":"ACTIVE"}}}}},"ExternalHealthResponse":{"type":"object","properties":{"success":{"type":"boolean","description":"Whether the API is healthy","example":true},"data":{"type":"object","properties":{"status":{"type":"string","enum":["healthy","unhealthy","degraded"],"description":"Health status","example":"healthy"},"timestamp":{"type":"string","format":"date-time","description":"Health check timestamp"}}}}},"AIAgentStatusResponse":{"type":"object","properties":{"success":{"type":"boolean","description":"Whether the request was successful","example":true},"data":{"type":"object","properties":{"conversationId":{"type":"string","description":"Conversation identifier","example":"conv_123456789"},"is_ai_agent_on":{"type":"boolean","description":"Whether AI agent is currently enabled","example":true},"ai_agent_enabled_at":{"type":"string","format":"date-time","description":"When AI agent was enabled","example":"2023-12-01T10:15:00Z","nullable":true},"ai_agent_enabled_by":{"type":"string","description":"Who/what enabled the AI agent","enum":["user","api","auto","default"],"example":"auto","nullable":true},"ai_agent_last_toggled_at":{"type":"string","format":"date-time","description":"When AI agent status was last changed","example":"2023-12-01T10:15:00Z","nullable":true}}}}},"AIAgentToggleRequest":{"type":"object","required":["enabled"],"properties":{"enabled":{"type":"boolean","description":"Whether to enable or disable AI agent","example":true},"reason":{"type":"string","description":"Reason for the toggle (optional)","example":"Manual user toggle","maxLength":500}}},"AIAgentToggleResponse":{"type":"object","properties":{"success":{"type":"boolean","description":"Whether the toggle was successful","example":true},"data":{"type":"object","properties":{"conversationId":{"type":"string","description":"Conversation identifier","example":"conv_123456789"},"previousStatus":{"type":"boolean","description":"AI agent status before toggle","example":false},"newStatus":{"type":"boolean","description":"AI agent status after toggle","example":true},"enabledBy":{"type":"string","description":"Who/what performed the toggle","enum":["user","api","auto","default"],"example":"api"},"toggledAt":{"type":"string","format":"date-time","description":"When the toggle occurred","example":"2023-12-01T10:30:00Z"}}}}},"ExternalSendMessageWithAIAgentRequest":{"type":"object","required":["phoneNumberId","to","message"],"properties":{"phoneNumberId":{"type":"string","description":"WhatsApp Business Phone Number ID","example":"123456789012345"},"to":{"type":"string","description":"Recipient phone number with country code","example":"+1234567890"},"message":{"type":"string","description":"Text message content","example":"Hello, this is a test message from the API!"},"replyToMessageId":{"type":"string","description":"ID of message to reply to (optional)","example":"msg_123456789"},"ai_agent_enabled":{"type":"boolean","description":"Override AI agent auto-enable behavior for this message","example":true}}},"ExternalSendMessageWithAIAgentResponse":{"type":"object","properties":{"success":{"type":"boolean","description":"Whether the message was sent successfully","example":true},"data":{"type":"object","properties":{"messageId":{"type":"string","description":"Internal message ID","example":"msg_123456789"},"whatsappMessageId":{"type":"string","description":"WhatsApp message ID","example":"wamid.HBgLMTY3NDc4NjQyMTQVAgARGBI4OTZFMEY3NjU5QzA5MDcyOQA="},"status":{"type":"string","description":"Message status","example":"sent"},"timestamp":{"type":"string","format":"date-time","description":"Message timestamp","example":"2023-12-01T10:30:00Z"},"conversationId":{"type":"string","description":"Conversation ID","example":"conv_123456789"},"to":{"type":"string","description":"Recipient phone number","example":"+1234567890"},"from":{"type":"string","description":"Sender phone number","example":"+0987654321"},"aiAgentOverride":{"type":"boolean","description":"Whether AI agent was overridden via API parameter","example":true},"conversation":{"type":"object","description":"Conversation details including AI agent and lead qualification data","properties":{"id":{"type":"string","description":"Conversation ID","example":"conv_123456789"},"is_ai_agent_on":{"type":"boolean","description":"Whether AI agent is currently enabled","example":true},"ai_agent_enabled_at":{"type":"string","format":"date-time","description":"When AI agent was enabled","example":"2023-12-01T10:15:00Z","nullable":true},"ai_agent_enabled_by":{"type":"string","description":"Who/what enabled the AI agent","enum":["user","api","auto","default"],"example":"api","nullable":true},"ai_agent_last_toggled_at":{"type":"string","format":"date-time","description":"When AI agent status was last changed","example":"2023-12-01T10:15:00Z","nullable":true},"lead_status":{"type":"string","description":"Lead qualification status","example":"qualified","nullable":true},"lead_score":{"type":"integer","description":"Lead qualification score (0-100)","example":85,"nullable":true},"lead_company":{"type":"string","description":"Lead's company name","example":"Test Company Inc","nullable":true},"lead_notes":{"type":"string","description":"Lead qualification notes","example":"High-value prospect","nullable":true},"lead_name":{"type":"string","description":"Lead's name (may differ from customer name)","example":"John Doe","nullable":true},"lead_source":{"type":"string","description":"Lead source","example":"website","nullable":true},"lead_budget":{"type":"string","description":"Lead's budget range","example":"50000","nullable":true},"lead_timeline":{"type":"string","description":"Lead's purchase timeline","example":"Q1 2024","nullable":true},"lead_industry":{"type":"string","description":"Lead's industry","example":"Technology","nullable":true},"lead_job_title":{"type":"string","description":"Lead's job title","example":"CTO","nullable":true},"lead_location":{"type":"string","description":"Lead's location","example":"San Francisco, CA","nullable":true},"lead_qualification_date":{"type":"string","format":"date-time","description":"When lead was qualified","example":"2023-12-01T10:15:00Z","nullable":true},"lead_last_updated":{"type":"string","format":"date-time","description":"When lead data was last updated","example":"2023-12-01T10:15:00Z","nullable":true},"leadQualification":{"type":"object","description":"Raw lead data from external APIs","nullable":true,"properties":{"raw_data":{"type":"object","description":"Complete raw response from external API","example":{"score":85,"source":"website"}},"processed_data":{"type":"object","description":"Structured data for easy querying","example":{"priority":"high","qualified":true}},"source_api":{"type":"string","description":"Source API that provided the data","example":"test_api"},"stored_at":{"type":"string","format":"date-time","description":"When the data was stored","example":"2023-12-01T10:15:00Z"}}}}}}}}},"ExternalWebhookEvent":{"type":"object","properties":{"event":{"type":"string","description":"Event type","example":"ai_agent.status_changed"},"conversation_id":{"type":"string","description":"Conversation identifier","example":"conv_123456789"},"ai_agent_enabled":{"type":"boolean","description":"New AI agent status","example":true},"enabled_by":{"type":"string","description":"Who/what changed the status","enum":["user","api","auto","default"],"example":"auto"},"previous_status":{"type":"boolean","description":"AI agent status before change","example":false},"new_status":{"type":"boolean","description":"AI agent status after change","example":true},"timestamp":{"type":"string","format":"date-time","description":"When the change occurred","example":"2023-12-01T10:30:00Z"},"user_id":{"type":"string","description":"User identifier","example":"user_123456789"},"whatsapp_account_id":{"type":"string","description":"WhatsApp account identifier","example":"acc_123456789","nullable":true},"version":{"type":"string","description":"API version","example":"2.0.0"},"environment":{"type":"string","description":"Environment name","example":"production"}}}}},"security":[{"ApiKeyAuth":[]},{"ApiKeyHeader":[]}],"paths":{"/api/v2/external/messages/send":{"post":{"summary":"Send a WhatsApp text message","description":"Send a text message to a WhatsApp user using the specified phone number. Supports optional lead qualification data and AI agent control.","tags":["📤 External API - Messages"],"security":[{"ApiKeyAuth":[]},{"ApiKeyHeader":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ExternalSendMessageRequest"},"example":{"phoneNumberId":"123456789012345","to":"+1234567890","message":"Hello, this is a test message from the API!","replyToMessageId":"msg_123456789"}}}},"responses":{"200":{"description":"Message sent successfully","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ExternalSendMessageResponse"}}},"headers":{"X-RateLimit-Limit":{"description":"Rate limit for the endpoint","schema":{"type":"integer","example":1000}},"X-RateLimit-Remaining":{"description":"Remaining requests in the current window","schema":{"type":"integer","example":999}},"X-RateLimit-Reset":{"description":"When the rate limit window resets","schema":{"type":"string","format":"date-time","example":"2023-12-01T11:00:00Z"}}}},"400":{"description":"Invalid request data","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"description":"Invalid or missing API token","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"description":"Rate limit exceeded","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}},"headers":{"X-RateLimit-Limit":{"description":"Rate limit for the endpoint","schema":{"type":"integer","example":1000}},"X-RateLimit-Remaining":{"description":"Remaining requests in the current window","schema":{"type":"integer","example":0}},"X-RateLimit-Reset":{"description":"When the rate limit window resets","schema":{"type":"string","format":"date-time","example":"2023-12-01T11:00:00Z"}}}}}}},"/api/v2/external/messages/{messageId}/status":{"get":{"summary":"Get message delivery status","description":"Retrieve the current delivery status of a sent message","tags":["📤 External API - Messages"],"security":[{"ApiKeyAuth":[]},{"ApiKeyHeader":[]}],"parameters":[{"in":"path","name":"messageId","required":true,"schema":{"type":"string"},"description":"Internal message ID","example":"msg_123456789"}],"responses":{"200":{"description":"Message status retrieved successfully","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ExternalMessageStatus"}}}},"400":{"description":"Invalid message ID","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"description":"Invalid or missing API token","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"404":{"description":"Message not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}}},"/api/v2/external/conversations":{"get":{"summary":"Get conversations","description":"Retrieve a list of conversations for the authenticated user with pagination support","tags":["💬 External API - Conversations"],"security":[{"ApiKeyAuth":[]},{"ApiKeyHeader":[]}],"parameters":[{"in":"query","name":"page","schema":{"type":"integer","default":1},"description":"Page number for pagination"},{"in":"query","name":"limit","schema":{"type":"integer","default":20,"maximum":100},"description":"Number of conversations per page (max 100)"},{"in":"query","name":"phoneNumberId","schema":{"type":"string"},"description":"Filter by specific phone number ID"}],"responses":{"200":{"description":"Conversations retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"type":"array","items":{"$ref":"#/components/schemas/ExternalConversation"}},"meta":{"type":"object","properties":{"page":{"type":"integer","example":1},"limit":{"type":"integer","example":20},"total":{"type":"integer","example":150},"totalPages":{"type":"integer","example":8}}}}}}}},"401":{"description":"Invalid or missing API token","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"description":"Rate limit exceeded","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}}},"/api/v2/external/conversations/{conversationId}/messages":{"get":{"summary":"Get conversation messages","description":"Retrieve messages from a specific conversation with pagination support","tags":["💬 External API - Conversations"],"security":[{"ApiKeyAuth":[]},{"ApiKeyHeader":[]}],"parameters":[{"in":"path","name":"conversationId","required":true,"schema":{"type":"string"},"description":"Conversation ID","example":"conv_123456789"},{"in":"query","name":"page","schema":{"type":"integer","default":1},"description":"Page number for pagination"},{"in":"query","name":"limit","schema":{"type":"integer","default":20,"maximum":100},"description":"Number of messages per page (max 100)"}],"responses":{"200":{"description":"Messages retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"type":"array","items":{"$ref":"#/components/schemas/ExternalMessage"}},"meta":{"type":"object","properties":{"page":{"type":"integer","example":1},"limit":{"type":"integer","example":20},"total":{"type":"integer","example":45},"totalPages":{"type":"integer","example":3}}}}}}}},"401":{"description":"Invalid or missing API token","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"404":{"description":"Conversation not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"description":"Rate limit exceeded","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}}},"/api/v2/external/conversations/{conversationId}/ai-agent":{"get":{"summary":"Get AI Agent status for conversation","description":"Retrieve the current AI agent status for a specific conversation","tags":["🤖 External API - AI Agent"],"security":[{"ApiKeyAuth":[]},{"ApiKeyHeader":[]}],"parameters":[{"in":"path","name":"conversationId","required":true,"schema":{"type":"string"},"description":"Conversation identifier","example":"conv_123456789"}],"responses":{"200":{"description":"AI agent status retrieved successfully","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AIAgentStatusResponse"}}}},"401":{"description":"Invalid or missing API token","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"403":{"description":"Access denied to conversation","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"404":{"description":"Conversation not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"description":"Rate limit exceeded","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}},"patch":{"summary":"Toggle AI Agent for conversation","description":"Enable or disable the AI agent for a specific conversation","tags":["🤖 External API - AI Agent"],"security":[{"ApiKeyAuth":[]},{"ApiKeyHeader":[]}],"parameters":[{"in":"path","name":"conversationId","required":true,"schema":{"type":"string"},"description":"Conversation identifier","example":"conv_123456789"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/AIAgentToggleRequest"},"example":{"enabled":true,"reason":"Manual API toggle for customer support"}}}},"responses":{"200":{"description":"AI agent status toggled successfully","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AIAgentToggleResponse"}}}},"400":{"description":"Invalid request data","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"description":"Invalid or missing API token","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"403":{"description":"Access denied to conversation","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"404":{"description":"Conversation not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"description":"Rate limit exceeded","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}}},"/api/v2/external/media/upload":{"post":{"summary":"Upload media file","description":"Upload an image, document, audio, or video file to WhatsApp for use in messages. Returns a mediaId that can be used with the send-media endpoint.","tags":["📤 External API - Messages"],"security":[{"ApiKeyAuth":[]},{"ApiKeyHeader":[]}],"requestBody":{"required":true,"content":{"multipart/form-data":{"schema":{"type":"object","required":["phoneNumberId","file"],"properties":{"phoneNumberId":{"type":"string","description":"WhatsApp Business Phone Number ID","example":"123456789012345"},"file":{"type":"string","format":"binary","description":"Media file to upload (image, document, audio, video)"}}}}}},"responses":{"200":{"description":"Media uploaded successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"type":"object","properties":{"mediaId":{"type":"string","description":"WhatsApp media ID for use in send-media","example":"media_123456789"},"mimeType":{"type":"string","description":"MIME type of uploaded file","example":"image/jpeg"},"fileSize":{"type":"integer","description":"File size in bytes","example":1024000}}}}}}}},"400":{"description":"Invalid file or missing required fields","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"description":"Invalid or missing API token","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"413":{"description":"File too large","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"description":"Rate limit exceeded","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}}},"/api/v2/external/messages/send-media":{"post":{"summary":"Send media message","description":"Send a media message (image, document, audio, video) to a WhatsApp user. Supports optional caption, lead qualification data, and AI agent control.","tags":["📤 External API - Messages"],"security":[{"ApiKeyAuth":[]},{"ApiKeyHeader":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["phoneNumberId","to","mediaId","mediaType"],"properties":{"phoneNumberId":{"type":"string","description":"WhatsApp Business Phone Number ID","example":"123456789012345"},"to":{"type":"string","description":"Recipient phone number with country code","example":"+1234567890"},"mediaId":{"type":"string","description":"Media ID from upload endpoint","example":"media_123456789"},"mediaType":{"type":"string","enum":["image","document","audio","video"],"description":"Type of media being sent","example":"image"},"caption":{"type":"string","description":"Optional caption for the media. Not required - can be omitted.","example":"Check out this image!"},"filename":{"type":"string","description":"Optional filename (for documents)","example":"document.pdf"},"replyToMessageId":{"type":"string","description":"ID of message to reply to (optional)","example":"msg_123456789"},"ai_agent_enabled":{"type":"boolean","description":"Override AI agent auto-enable behavior","example":true},"lead_qualification":{"type":"object","description":"Optional lead qualification data","properties":{"lead_status":{"type":"string","example":"qualified"},"lead_score":{"type":"number","example":85},"lead_company":{"type":"string","example":"Acme Inc"}}}}},"examples":{"withCaption":{"summary":"Send image with caption","value":{"phoneNumberId":"123456789012345","to":"+1234567890","mediaId":"media_123456789","mediaType":"image","caption":"Product catalog image","ai_agent_enabled":false}},"withoutCaption":{"summary":"Send image without caption","value":{"phoneNumberId":"123456789012345","to":"+1234567890","mediaId":"media_123456789","mediaType":"image"}},"documentWithFilename":{"summary":"Send document with filename","value":{"phoneNumberId":"123456789012345","to":"+1234567890","mediaId":"media_987654321","mediaType":"document","filename":"product_brochure.pdf","caption":"Latest product information"}}}}}},"responses":{"200":{"description":"Media message sent successfully","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ExternalSendMessageResponse"}}}},"400":{"description":"Invalid request data","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"description":"Invalid or missing API token","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"404":{"description":"Media ID not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"description":"Rate limit exceeded","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}}},"/api/v2/external/phone-numbers":{"get":{"summary":"Get available phone numbers","description":"Retrieve a list of WhatsApp Business phone numbers available to the API token","tags":["📱 External API - Phone Numbers"],"security":[{"ApiKeyAuth":[]},{"ApiKeyHeader":[]}],"responses":{"200":{"description":"Phone numbers retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"type":"object","properties":{"phoneNumbers":{"type":"array","items":{"$ref":"#/components/schemas/ExternalPhoneNumber"}}}}}}}}},"401":{"description":"Invalid or missing API token","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"description":"Rate limit exceeded","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}}},"/api/v2/external/health":{"get":{"summary":"Check API health","description":"Verify that the API is running and the API token is valid","tags":["🏥 External API - Health"],"security":[{"ApiKeyAuth":[]},{"ApiKeyHeader":[]}],"responses":{"200":{"description":"API is healthy","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ExternalHealthResponse"}}}},"401":{"description":"Invalid or missing API token","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}}},"/api/v2/external/webhook/test":{"post":{"summary":"Test webhook endpoint","description":"Send a test webhook to verify your webhook endpoint is working correctly","tags":["🔗 External API - Webhooks"],"security":[{"ApiKeyAuth":[]},{"ApiKeyHeader":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["webhookUrl"],"properties":{"webhookUrl":{"type":"string","format":"url","description":"Webhook endpoint URL to test","example":"https://myapp.com/webhooks/whatsapp"},"eventType":{"type":"string","enum":["message.received","message.status","conversation.created","conversation.updated"],"default":"message.received","description":"Type of event to simulate"}}}}}},"responses":{"200":{"description":"Webhook test sent successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"type":"object","properties":{"webhookUrl":{"type":"string","format":"url"},"eventType":{"type":"string"},"sentAt":{"type":"string","format":"date-time"},"responseStatus":{"type":"integer","example":200},"responseTime":{"type":"number","description":"Response time in milliseconds","example":150.5}}}}}}}},"400":{"description":"Invalid webhook URL","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"description":"Invalid or missing API token","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}}},"/api/v2/external/rate-limit-test":{"get":{"summary":"Test rate limiting","description":"Check your current rate limit status and remaining requests","tags":["📊 External API - Rate Limiting"],"security":[{"ApiKeyAuth":[]},{"ApiKeyHeader":[]}],"responses":{"200":{"description":"Rate limit information retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"$ref":"#/components/schemas/RateLimitInfo"}}}}},"headers":{"X-RateLimit-Limit":{"description":"Rate limit for the endpoint","schema":{"type":"integer","example":1000}},"X-RateLimit-Remaining":{"description":"Remaining requests in the current window","schema":{"type":"integer","example":950}},"X-RateLimit-Reset":{"description":"When the rate limit window resets","schema":{"type":"string","format":"date-time","example":"2023-12-01T11:00:00Z"}}}},"401":{"description":"Invalid or missing API token","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}}},"/api/v2/external/conversations/{conversationId}/lead-qualification":{"patch":{"tags":["🎯 External API - Lead Qualification"],"summary":"Update lead qualification data for a conversation","description":"Updates lead qualification information for a specific conversation.\nThis is a dedicated endpoint for managing lead data separately from message sending.\nAll fields are optional - only send the fields you want to update.\n\n## 📋 Quick Start Guide\n\n### Step 1: Get a Conversation ID\nFirst, get the conversation ID from one of these methods:\n\n**Method A: List conversations**\n```bash\ncurl -H \"Authorization: Bearer YOUR_API_TOKEN\" \\\n     http://localhost:4000/api/v2/external/conversations\n```\n\n**Method B: Send a message (returns conversationId)**\n```bash\ncurl -X POST -H \"Authorization: Bearer YOUR_API_TOKEN\" \\\n     -H \"Content-Type: application/json\" \\\n     -d '{\"phoneNumberId\":\"123\",\"to\":\"+1234567890\",\"message\":\"Hello\"}' \\\n     http://localhost:4000/api/v2/external/messages/send\n```\n\n### Step 2: Update Lead Qualification\n```bash\ncurl -X PATCH -H \"Authorization: Bearer YOUR_API_TOKEN\" \\\n     -H \"Content-Type: application/json\" \\\n     -d '{\"lead_status\":\"qualified\",\"lead_score\":85}' \\\n     http://localhost:4000/api/v2/external/conversations/clx1a2b3c4d5e6f7890abc/lead-qualification\n```\n\n### Use Cases:\n- **CRM Integration**: Update lead status when deal moves through sales pipeline\n- **AI Agent Results**: Store AI-processed lead qualification data  \n- **Manual Updates**: Sales team manually qualifies leads\n- **Webhook Integration**: N8N/Zapier workflows update lead data\n","security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"conversationId","required":true,"schema":{"type":"string"},"description":"The conversation ID from your WhatsApp conversations.\n\n**How to get conversation IDs:**\n1. **From GET /conversations** - Returns list of all conversations with IDs\n2. **From message sending** - Returns conversationId in response when sending messages\n3. **From webhooks** - Includes conversationId in webhook payload\n\n**Conversation ID format:** CUID (Collision Resistant Unique Identifier)\n- Format: `clx` + random alphanumeric characters\n- Length: ~25 characters\n- Example: `clx1234567890abcdef`\n","example":"clx1a2b3c4d5e6f7890abc"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","description":"Lead qualification data. All fields are optional - only include the fields you want to update.\nYou can send just one field (e.g., only lead_status) or multiple fields in the same request.\n\n## 📝 Example Payloads\n\n**Simple status update:**\n```json\n{\n  \"lead_status\": \"qualified\"\n}\n```\n\n**Basic lead info:**\n```json\n{\n  \"lead_status\": \"interested\",\n  \"lead_score\": 75,\n  \"lead_company\": \"Tech Solutions Inc\",\n  \"lead_name\": \"John Smith\"\n}\n```\n\n**Complete lead profile:**\n```json\n{\n  \"lead_status\": \"qualified\",\n  \"lead_score\": 92,\n  \"lead_company\": \"Enterprise Corp\",\n  \"lead_name\": \"Sarah Johnson\",\n  \"lead_notes\": \"Very interested in enterprise plan. Budget approved.\",\n  \"lead_source\": \"linkedin_campaign\", \n  \"lead_budget\": \"$50k-100k\",\n  \"lead_timeline\": \"Q1 2025\",\n  \"lead_industry\": \"Technology\",\n  \"lead_job_title\": \"VP Engineering\",\n  \"lead_location\": \"San Francisco, CA\",\n  \"lead_qualification_date\": \"2025-01-15T14:30:00Z\",\n  \"source_api\": \"n8n_integration\",\n  \"external_id\": \"lead_12345\"\n}\n```\n\n**CRM Integration with metadata:**\n```json\n{\n  \"lead_status\": \"hot\",\n  \"lead_score\": 88,\n  \"lead_company\": \"BigCorp Ltd\",\n  \"lead_name\": \"Michael Chen\",\n  \"lead_notes\": \"Demo scheduled for next week\",\n  \"raw_data\": {\n    \"crm_id\": \"CRM_789\",\n    \"lead_owner\": \"sales_rep_456\",\n    \"campaign\": \"webinar_2024\"\n  },\n  \"processed_data\": {\n    \"priority\": \"high\",\n    \"follow_up_required\": true\n  },\n  \"source_api\": \"hubspot\",\n  \"external_id\": \"hubspot_789\"\n}\n```\n","properties":{"lead_status":{"type":"string","enum":["new_lead","contacted","interested","in_progress","qualified","hot","warm","cold","lost","won","disqualified"],"description":"Current status of the lead","example":"qualified"},"lead_score":{"type":"number","minimum":0,"maximum":100,"description":"Lead score (0-100)","example":85},"lead_company":{"type":"string","maxLength":255,"description":"Company name","example":"Acme Inc"},"lead_name":{"type":"string","maxLength":255,"description":"Lead contact name","example":"John Doe"},"lead_notes":{"type":"string","maxLength":1000,"description":"Notes about the lead","example":"Interested in enterprise plan"},"lead_source":{"type":"string","maxLength":255,"description":"Source of the lead","example":"website"},"lead_budget":{"type":"string","maxLength":255,"description":"Budget range","example":"$10k-50k"},"lead_timeline":{"type":"string","maxLength":255,"description":"Expected timeline","example":"Q1 2025"},"lead_industry":{"type":"string","maxLength":255,"description":"Industry","example":"Technology"},"lead_job_title":{"type":"string","maxLength":255,"description":"Job title","example":"CTO"},"lead_location":{"type":"string","maxLength":255,"description":"Location","example":"San Francisco"},"lead_qualification_date":{"type":"string","format":"date-time","description":"Date when lead was qualified","example":"2025-01-15T10:00:00Z"},"raw_data":{"type":"object","description":"Raw data from external system","example":{}},"processed_data":{"type":"object","description":"Processed data","example":{}},"source_api":{"type":"string","maxLength":255,"description":"Source API identifier","example":"n8n_ai_agent"},"external_id":{"type":"string","maxLength":255,"description":"External system ID","example":"ext_123"}}},"examples":{"simpleStatusUpdate":{"summary":"Simple status update","description":"Update just the lead status","value":{"lead_status":"qualified"}},"statusWithScore":{"summary":"Status with score update","description":"Update status and score together","value":{"lead_status":"qualified","lead_score":85}},"basicLeadInfo":{"summary":"Basic lead information","description":"Update core lead details","value":{"lead_status":"interested","lead_score":75,"lead_company":"Acme Corporation","lead_name":"John Smith","lead_source":"website_form"}},"fullLeadProfile":{"summary":"Complete lead profile","description":"Update all lead qualification fields","value":{"lead_status":"qualified","lead_score":92,"lead_company":"TechStart Inc","lead_name":"Sarah Johnson","lead_notes":"Very interested in enterprise plan. Has budget approved. Decision maker confirmed.","lead_source":"linkedin_campaign","lead_budget":"$25k-50k annually","lead_timeline":"Q1 2025 implementation","lead_industry":"Software Technology","lead_job_title":"VP of Engineering","lead_location":"San Francisco, CA","lead_qualification_date":"2025-01-15T14:30:00Z","source_api":"n8n_ai_agent","external_id":"lead_12345"}},"crmIntegration":{"summary":"CRM system integration","description":"Example payload from CRM system integration with raw and processed data","value":{"lead_status":"hot","lead_score":88,"lead_company":"Enterprise Solutions Ltd","lead_name":"Michael Chen","lead_notes":"Warm lead from webinar. Requested demo next week.","lead_budget":"$100k+","lead_timeline":"Q4 2024","raw_data":{"crm_id":"CRM_789123","lead_owner":"sales_rep_456","campaign_source":"webinar_dec_2024","original_score":88,"tags":["enterprise","hot_lead","demo_requested"]},"processed_data":{"priority_level":"high","follow_up_required":true,"demo_scheduled":false,"next_action":"schedule_demo"},"source_api":"hubspot_integration","external_id":"hubspot_contact_789123"}}}}}},"responses":{"200":{"description":"Lead qualification updated successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"type":"object","properties":{"conversation":{"type":"object","description":"Updated conversation with lead data"},"updatedAt":{"type":"string","format":"date-time"}}},"message":{"type":"string","example":"Lead qualification updated successfully"}}}}}},"400":{"description":"Invalid request"},"404":{"description":"Conversation not found"},"500":{"description":"Internal server error"}}}}},"tags":[{"name":"📤 External API - Messages","description":"Send text messages, media messages, upload media, and check message status"},{"name":"💬 External API - Conversations","description":"List conversations and retrieve conversation messages"},{"name":"🤖 External API - AI Agent","description":"Enable/disable AI agent and check AI agent status for conversations"},{"name":"🎯 External API - Lead Qualification","description":"Update and manage lead qualification data for conversations"},{"name":"📱 External API - Phone Numbers","description":"List available WhatsApp Business phone numbers"},{"name":"🏥 External API - Health","description":"API health checks and status monitoring"},{"name":"🔗 External API - Webhooks","description":"Test webhook endpoints and delivery"},{"name":"📊 External API - Rate Limiting","description":"Check rate limit status and remaining quota"}]}