Skip to content

πŸ’¬ WhatsApp Integration Architecture

⚠️ POST-MVP FEATURE: This feature is planned for Month 3-6 after MVP launch. MVP will use email notifications for critical alerts.

Overview

This document outlines the technical architecture for integrating WhatsApp Business API into GetCimple, enabling secure communication channels for compliance updates, alerts, and stakeholder engagement.

Integration Architecture

High-Level Architecture

graph TB
    subgraph "GetCimple Platform"
        API[API Gateway]
        WS[WhatsApp Service]
        Q[Message Queue]
        DB[Database]
    end

    subgraph "External Services"
        WA[WhatsApp Business API]
        TW[Twilio API]
    end

    subgraph "Users"
        D[Directors]
        M[Managers]
        I[Implementers]
    end

    API --> WS
    WS --> Q
    Q --> TW
    TW --> WA
    WA --> D
    WA --> M
    WA --> I
    WS --> DB

Component Architecture

WhatsApp Service

  • Message composition and formatting
  • Template management
  • Contact synchronization
  • Delivery tracking
  • Response handling

Message Queue

  • Asynchronous processing
  • Rate limiting compliance
  • Retry logic
  • Priority handling
  • Batch processing

Integration Layer

  • Twilio WhatsApp API wrapper
  • Authentication management
  • Webhook handling
  • Error management
  • Monitoring integration

Implementation Details

Message Types

Compliance Alerts

interface ComplianceAlert {
  type: 'compliance_alert'
  severity: 'critical' | 'high' | 'medium' | 'low'
  title: string
  description: string
  actionRequired: boolean
  actionUrl?: string
  dueDate?: Date
}

Status Updates

interface StatusUpdate {
  type: 'status_update'
  framework: string
  completionPercentage: number
  recentChanges: string[]
  nextSteps: string[]
}

Task Notifications

interface TaskNotification {
  type: 'task_notification'
  taskId: string
  taskTitle: string
  assignee: string
  dueDate: Date
  priority: 'high' | 'medium' | 'low'
}

API Integration

Twilio Configuration

// WhatsApp service configuration
export const twilioConfig = {
  accountSid: process.env.TWILIO_ACCOUNT_SID,
  authToken: process.env.TWILIO_AUTH_TOKEN,
  whatsappNumber: process.env.TWILIO_WHATSAPP_NUMBER,
  statusCallback: `${process.env.API_URL}/webhooks/whatsapp/status`,
}

Message Sending

class WhatsAppService {
  async sendMessage(
    recipient: string,
    message: Message
  ): Promise<MessageResult> {
    // Validate recipient opt-in
    const hasOptedIn = await this.checkOptInStatus(recipient)
    if (!hasOptedIn) {
      throw new Error('Recipient has not opted in')
    }

    // Format message based on type
    const formatted = await this.formatMessage(message)

    // Queue for sending
    await this.messageQueue.add({
      to: recipient,
      body: formatted.body,
      mediaUrl: formatted.mediaUrl,
      priority: message.priority,
    })

    return { queued: true, messageId: formatted.id }
  }
}

Message Templates

Compliance Alert Template

🚨 *Compliance Alert: {{ framework_name }}*

{{ alert_description }}

*Severity:* {{ severity }}
*Action Required:* {{ action_required }}

{{ action_instructions }}

View details: {{ detail_url }}

Reply STOP to unsubscribe.

Weekly Summary Template

πŸ“Š *Weekly Compliance Summary*

Hi {{ user_name }}, here's your compliance status:

{{ framework_list }}

*Overall Compliance:* {{ overall_percentage }}%

*This Week:*
βœ… Completed: {{ completed_tasks }}
⏳ In Progress: {{ in_progress_tasks }}
πŸ”΄ Overdue: {{ overdue_tasks }}

View dashboard: {{ dashboard_url }}

Webhook Handling

Incoming Messages

app.post('/webhooks/whatsapp/incoming', async (req, res) => {
  const { From, Body, MessageSid } = req.body

  // Log incoming message
  await logIncomingMessage({
    from: From,
    body: Body,
    messageId: MessageSid,
    timestamp: new Date(),
  })

  // Process commands
  const command = parseCommand(Body)
  const response = await processCommand(command, From)

  // Send response
  if (response) {
    await sendResponse(From, response)
  }

  res.status(200).send()
})

Status Callbacks

app.post('/webhooks/whatsapp/status', async (req, res) => {
  const { MessageSid, MessageStatus, ErrorCode } = req.body

  // Update message status
  await updateMessageStatus({
    messageId: MessageSid,
    status: MessageStatus,
    errorCode: ErrorCode,
    timestamp: new Date(),
  })

  // Handle failures
  if (MessageStatus === 'failed') {
    await handleMessageFailure(MessageSid, ErrorCode)
  }

  res.status(200).send()
})

Security Considerations

Authentication & Authorization

  • Webhook signature verification
  • API key rotation
  • Rate limiting per user
  • IP whitelisting for webhooks

Data Protection

  • End-to-end encryption (WhatsApp native)
  • Message content encryption at rest
  • PII redaction in logs
  • Audit trail maintenance

Compliance

  • Opt-in/opt-out management
  • Message retention policies
  • GDPR compliance for EU users
  • Australian privacy principles

User Management

Opt-In Process

  1. User initiates contact via WhatsApp
  2. Bot sends welcome message with terms
  3. User confirms opt-in
  4. Preferences captured and stored
  5. Confirmation message sent

Preference Management

interface UserPreferences {
  userId: string
  whatsappNumber: string
  optedIn: boolean
  optInDate: Date
  preferences: {
    complianceAlerts: boolean
    weeklyReports: boolean
    taskNotifications: boolean
    quietHours: {
      enabled: boolean
      start: string // "22:00"
      end: string // "08:00"
      timezone: string
    }
  }
}

Monitoring & Analytics

Key Metrics

  • Message delivery rate
  • Read receipt rate
  • Response time
  • Opt-out rate
  • Error rate by type

Monitoring Implementation

class WhatsAppMonitor {
  async trackMessage(message: OutboundMessage): Promise<void> {
    await this.metrics.increment('whatsapp.messages.sent', {
      type: message.type,
      recipient_role: message.recipientRole,
    })
  }

  async trackDelivery(status: DeliveryStatus): Promise<void> {
    await this.metrics.increment('whatsapp.messages.delivered', {
      status: status.code,
      error: status.error,
    })
  }
}

Rate Limiting & Scaling

Rate Limit Management

  • Twilio tier limits respected
  • Internal queue management
  • Batch processing for bulk sends
  • Priority queue for critical alerts

Scaling Strategy

  • Horizontal scaling of workers
  • Message queue partitioning
  • Database read replicas
  • CDN for media files

Testing Strategy

Unit Tests

  • Message formatting
  • Command parsing
  • Queue management
  • Error handling

Integration Tests

  • Twilio API integration
  • Webhook processing
  • End-to-end message flow
  • Rate limit handling

User Acceptance Testing

  • Message clarity
  • Delivery timing
  • Command responsiveness
  • Opt-out process

Post-MVP Future Enhancements

  • Rich media support (PDFs, images)
  • Interactive message buttons
  • Multi-language support
  • Voice message integration
  • WhatsApp Business catalog integration
  • Advanced analytics dashboard
  • AI-powered response suggestions (Post-MVP only - requires AI infrastructure)
  • Group messaging for teams